commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
da996ffe748d2d30821284f1ccf48ad0fa0d193d
osu.Game/Overlays/BreadcrumbControlOverlayHeader.cs
osu.Game/Overlays/BreadcrumbControlOverlayHeader.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; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { Text.Font = Text.Font.With(size: 14); Chevron.Y = 3; Bar.Height = 0; } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays { public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string> { protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl(); public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string> { public OverlayHeaderBreadcrumbControl() { RelativeSizeAxes = Axes.X; Height = 47; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { AccentColour = colourProvider.Light2; } protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value); private class ControlTabItem : BreadcrumbTabItem { protected override float ChevronSize => 8; public ControlTabItem(string value) : base(value) { RelativeSizeAxes = Axes.Y; Text.Font = Text.Font.With(size: 14); Text.Anchor = Anchor.CentreLeft; Text.Origin = Anchor.CentreLeft; Chevron.Y = 1; Bar.Height = 0; } // base OsuTabItem makes font bold on activation, we don't want that here protected override void OnActivated() => FadeHovered(); protected override void OnDeactivated() => FadeUnhovered(); } } } }
Update header breadcrumb tab control
Update header breadcrumb tab control
C#
mit
EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,peppy/osu,peppy/osu
7da8cc3c3e3e488cec93ea79f114766711f18ccb
Source/Assets/Editor/PlayFabEdExPackager.cs
Source/Assets/Editor/PlayFabEdExPackager.cs
using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } }
using UnityEditor; using UnityEngine; namespace PlayFab.Internal { public static class PlayFabEdExPackager { private static readonly string[] SdkAssets = { "Assets/PlayFabEditorExtensions" }; [MenuItem("PlayFab/Testing/Build PlayFab EdEx UnityPackage")] public static void BuildUnityPackage() { var packagePath = "C:/depot/sdks/UnityEditorExtensions/Packages/PlayFabEditorExtensions.unitypackage"; AssetDatabase.ExportPackage(SdkAssets, packagePath, ExportPackageOptions.Recurse); Debug.Log("Package built: " + packagePath); } } }
Revise dropdowns for building unitypackages.
Revise dropdowns for building unitypackages.
C#
apache-2.0
PlayFab/UnityEditorExtensions
90ef72e50defd269fdf4373f6eaf95c6b451b30a
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.10.0.0")] [assembly: AssemblyFileVersion("0.10.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.11.0.0")] [assembly: AssemblyFileVersion("0.11.0.0")]
Increase project version number to 0.11.0
Increase project version number to 0.11.0
C#
apache-2.0
atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata
28ebec8332b1dfae1d8258fe8c4f14f75262e3b3
src/CSharpClient/Bit.CSharpClient.Prism/ViewModel/BitExceptionHandler.cs
src/CSharpClient/Bit.CSharpClient.Prism/ViewModel/BitExceptionHandler.cs
#define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } }
#define Debug using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel { public class BitExceptionHandler { public static BitExceptionHandler Current { get; set; } = new BitExceptionHandler(); public virtual void OnExceptionReceived(Exception exp, IDictionary<string, string> properties = null) { properties = properties ?? new Dictionary<string, string>(); if (exp != null && Debugger.IsAttached) { Debug.WriteLine($"DateTime: {DateTime.Now.ToLongTimeString()} Message: {exp}", category: "ApplicationException"); } } } }
Check debugger is attached before writing something to it
Check debugger is attached before writing something to it
C#
mit
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
1326905a3b85fc7a5ef81cc92ee9bbb7591001e1
src/Porthor/ResourceRequestValidators/ContentValidators/JsonValidator.cs
src/Porthor/ResourceRequestValidators/ContentValidators/JsonValidator.cs
using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Count > 0) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } }
using Microsoft.AspNetCore.Http; using NJsonSchema; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Porthor.ResourceRequestValidators.ContentValidators { /// <summary> /// Request validator for json content. /// </summary> public class JsonValidator : ContentValidatorBase { private readonly JsonSchema4 _schema; /// <summary> /// Constructs a new instance of <see cref="JsonValidator"/>. /// </summary> /// <param name="template">Template for json schema.</param> public JsonValidator(string template) : base(template) { _schema = JsonSchema4.FromJsonAsync(template).GetAwaiter().GetResult(); } /// <summary> /// Validates the content of the current <see cref="HttpContext"/> agains the json schema. /// </summary> /// <param name="context">Current context.</param> /// <returns> /// The <see cref="Task{HttpRequestMessage}"/> that represents the asynchronous query string validation process. /// Returns null if the content is valid agains the json schema. /// </returns> public override async Task<HttpResponseMessage> ValidateAsync(HttpContext context) { var errors = _schema.Validate(await StreamToString(context.Request.Body)); if (errors.Any()) { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return null; } private Task<string> StreamToString(Stream stream) { var streamContent = new StreamContent(stream); stream.Position = 0; return streamContent.ReadAsStringAsync(); } } }
Use Any instead of Count > 0
Use Any instead of Count > 0
C#
apache-2.0
NicatorBa/Porthor
9984debf927338698464f7e12a8d8e43109b2d7d
Saveyour/Saveyour/Settings.xaml.cs
Saveyour/Saveyour/Settings.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else if (qnotes.IsActive) qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Saveyour { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window, Module { Window qnotes; public Settings() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (qnotes.IsVisible) qnotes.Hide(); else qnotes.Show(); } public void addQNotes(Window module) { qnotes = module; } public String moduleID() { return "Settings"; } public Boolean update() { return false; } public String save() { return ""; } public Boolean load(String data) { return false; } public Boolean Equals(Module other) { return false; } } }
Revert "Fixed a bug where closing the quicknotes window then clicking show/hide quicknotes on the settings window would crash the program."
Revert "Fixed a bug where closing the quicknotes window then clicking show/hide quicknotes on the settings window would crash the program." This reverts commit 37590fdc25d5c4a40da7c400df340c68f7501c2d.
C#
apache-2.0
Saveyour-Team/Saveyour
85dcea5b8fc8707728c92e280a8ff5644f012e2d
src/NerdBank.GitVersioning/CloudBuildServices/VisualStudioTeamServices.cs
src/NerdBank.GitVersioning/CloudBuildServices/VisualStudioTeamServices.cs
namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); } } }
namespace Nerdbank.GitVersioning.CloudBuildServices { using System; using System.IO; /// <summary> /// /// </summary> /// <remarks> /// The VSTS-specific properties referenced here are documented here: /// https://msdn.microsoft.com/en-us/Library/vs/alm/Build/scripts/variables /// </remarks> internal class VisualStudioTeamServices : ICloudBuild { public bool IsPullRequest => false; // VSTS doesn't define this. public string BuildingTag => null; // VSTS doesn't define this. public string BuildingBranch => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public string BuildingRef => this.BuildingBranch; public string GitCommitId => null; public bool IsApplicable => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECTID")); public void SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[build.updatebuildnumber]{buildNumber}"); SetEnvVariableForBuildVariable("Build.BuildNumber", buildNumber); } public void SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##vso[task.setvariable variable={name};]{value}"); SetEnvVariableForBuildVariable(name, value); } private static void SetEnvVariableForBuildVariable(string name, string value) { string envVarName = name.ToUpperInvariant().Replace('.', '_'); Environment.SetEnvironmentVariable(envVarName, value); } } }
Set env vars when updating VSTS variables
Set env vars when updating VSTS variables
C#
mit
AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning
a62118ff46b6ee57f8ce241637625232e3c69291
OctopusPuppet.Gui/AppBootstrapper.cs
OctopusPuppet.Gui/AppBootstrapper.cs
using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { DisplayRootViewFor<DeploymentPlannerViewModel>(); } } }
using System.Collections.Generic; using System.Windows; using Caliburn.Micro; using OctopusPuppet.Gui.ViewModels; namespace OctopusPuppet.Gui { public class AppBootstrapper : BootstrapperBase { public AppBootstrapper() { Initialize(); } protected override void OnStartup(object sender, StartupEventArgs e) { var settings = new Dictionary<string, object> { { "SizeToContent", SizeToContent.Manual }, { "Height" , 768 }, { "Width" , 768 }, }; DisplayRootViewFor<DeploymentPlannerViewModel>(settings); } } }
Set default size for window
Set default size for window
C#
apache-2.0
Aqovia/OctopusPuppet
468bd0ab7f05c7c84f2677a526e3b5b8639a6a85
DeRange/Config/KeyboardShortcut.cs
DeRange/Config/KeyboardShortcut.cs
using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } } }
using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } public KeyModifier KeyModifier { get { KeyModifier mod = KeyModifier.None; if (AltModifier) { mod |= KeyModifier.Alt; } if (WinModifier) { mod |= KeyModifier.Win; } if (ShiftModifier) { mod |= KeyModifier.Shift; } if (CtrlModifier) { mod |= KeyModifier.Ctrl; } return mod; } } } }
Add helper method to return KeyModifier
Add helper method to return KeyModifier
C#
apache-2.0
bright-tools/DeRange
9d4260187896c063bbe21af135b6248b8da555f9
DevTyr.Gullap/Guard.cs
DevTyr.Gullap/Guard.cs
using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (object obj, string argumentName) { NotNull (obj, argumentName); if (!(obj is String)) return; var val = (String)obj; if (string.IsNullOrWhiteSpace(val)) throw new ArgumentException(argumentName); } } }
using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (string obj, string argumentName) { NotNull (obj, argumentName); if (string.IsNullOrWhiteSpace(obj)) throw new ArgumentException(argumentName); } } }
Change type signature of NotNullOrEmpty to string since it's only used for strings.
Change type signature of NotNullOrEmpty to string since it's only used for strings.
C#
mit
devtyr/gullap
04abb2ce8f1723fbf342d7cb215eea0d20d221bb
osu.Game.Rulesets.Osu/Skinning/Default/DefaultSmoke.cs
osu.Game.Rulesets.Osu/Skinning/Default/DefaultSmoke.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. namespace osu.Game.Rulesets.Osu.Skinning.Default { public class DefaultSmoke : Smoke { public DefaultSmoke() { Radius = 2; } } }
// 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.Textures; namespace osu.Game.Rulesets.Osu.Skinning.Default { public class DefaultSmoke : Smoke { [BackgroundDependencyLoader] private void load(TextureStore textures) { // ISkinSource doesn't currently fallback to global textures. // We might want to change this in the future if the intention is to allow the user to skin this as per legacy skins. Texture = textures.Get("Gameplay/osu/cursor-smoke"); } } }
Update default cursor smoke implementation to use a texture
Update default cursor smoke implementation to use a texture
C#
mit
peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu
d1e4b2164be26209b5be9d148b91b77b1b444b76
Harmony/Transpilers.cs
Harmony/Transpilers.cs
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { if (instruction.operand == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }
Make Visual Studio 2017 Enterprise happy
Make Visual Studio 2017 Enterprise happy
C#
mit
pardeike/Harmony
bbf9f477f3dc318045520b8a52c909b8044402d2
Assets/Scripts/Player/CountDown.cs
Assets/Scripts/Player/CountDown.cs
using UnityEngine; using System.Collections; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; // Use this for initialization void Start () { curTime = maxTime; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); Debug.Log(prettyTime); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; private Text text; // Use this for initialization void Start () { curTime = maxTime; text = gameObject.GetComponent( typeof(Text) ) as Text; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); //Debug.Log(prettyTime); text.text = prettyTime; } }
Update text on countdown timer GUI
Update text on countdown timer GUI
C#
mit
hcorion/RoverVR
9af2b3573dd60300e9f814f034ac5bcaa412b7dd
DesktopWidgets/Classes/FilePath.cs
DesktopWidgets/Classes/FilePath.cs
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } } }
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } = ""; } }
Fix file paths default value null
Fix file paths default value null
C#
apache-2.0
danielchalmers/DesktopWidgets
930b22d30b0caaec01b6a79c9afc379ee680e969
Assets/Scripts/MakeItRain.cs
Assets/Scripts/MakeItRain.cs
using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; // Use this for initialization void Start() { // Here only for test Rain(); } // Update is called once per frame void Update() { } void Rain() { int whichRain = Random.Range(1, 4); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(-4f, 4f); float y_rand = Random.Range(-1f, 1f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y + y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } }
using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; int count = 0; // Use this for initialization void Start() { } // Update is called once per frame // Just for test void Update() { if (count % 100 == 0) { Rain(); count++; } count++; } // Called only when dance is finished void Rain() { int whichRain = Random.Range(1, 5); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(minX, maxX - rain.GetComponent<BoxCollider2D>().size.x); float y_rand = Random.Range(1f, 3f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y - y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } }
Make it Rain now rains blocks constantly
Make it Rain now rains blocks constantly
C#
mit
TheMagnificentSeven/MakeItRain
8be4a079caba68b286884885acb19875ce4d97fa
MonadTests/StaticContractsCases.cs
MonadTests/StaticContractsCases.cs
using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct MaybeAssume<T> { ///<summary>Create a new Maybe{T}.</summary> private MaybeAssume(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = !_hasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } }
using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct Maybe<T> { ///<summary>Create a new Maybe{T}.</summary> private Maybe(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = ! HasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } }
Align failing CodeContracts case better to object Invariant.
Align failing CodeContracts case better to object Invariant.
C#
mit
pgeerkens/Monads
78e7af5bbf74319f7869630ac750ad8b0eab8987
src/Samples/PubSubUsingConfiguration/Bootstrapper.cs
src/Samples/PubSubUsingConfiguration/Bootstrapper.cs
using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) .EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }
using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) //.EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }
Disable partitioning in the bootstrapper.
Disable partitioning in the bootstrapper.
C#
bsd-3-clause
ProjectExtensions/ProjectExtensions.Azure.ServiceBus
58bb93065147cc41822fdec8d54e1958db3d9a38
src/Squidex/Areas/Api/Controllers/Schemas/Models/CreateSchemaNestedFieldDto.cs
src/Squidex/Areas/Api/Controllers/Schemas/Models/CreateSchemaNestedFieldDto.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is locked. /// </summary> public bool IsLocked { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }
Fix in API, added IsLocked field to nested schema.
Fix in API, added IsLocked field to nested schema.
C#
mit
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
1528ccd2635c7e03fd05df43731086f39ea6582a
Assets/Scripts/MainMenu.cs
Assets/Scripts/MainMenu.cs
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { //DontDestroyOnLoad(money); Application.LoadLevel(1); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { Screen.SetResolution(1080, 1920, true); //DontDestroyOnLoad(money); Application.LoadLevel(1); } }
Adjust screen resolution to samsung galaxy s4
Adjust screen resolution to samsung galaxy s4
C#
mit
ImperialBeasts-OxfordHack16/skybreak-android
19530fa692fdc772fea01117288a88d847980c2b
Assert.cs
Assert.cs
using System; namespace TDDUnit { class Assert { public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { string message = string.Format("Expected: Not '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void That(bool condition) { Equal(true, condition); } } }
using System; namespace TDDUnit { class Assert { private static void Fail(object expected, object actual) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { Fail(expected, actual); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { Fail(expected, actual); } } public static void That(bool condition) { Equal(true, condition); } } }
Refactor the error caused by a failing assertion
Refactor the error caused by a failing assertion
C#
apache-2.0
yawaramin/TDDUnit
75f19f1856901a00e616aa2f2b9b05d77f110490
src/Topshelf.Unity.Sample/Program.cs
src/Topshelf.Unity.Sample/Program.cs
using System; using Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } }
using System; using Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } }
Clean up: removed empty line
Clean up: removed empty line
C#
mit
alexandrnikitin/Topshelf.Unity
b444b6e8b8eb041579ab5b2877a562b6dd04ca76
TeamTracker/Settings.aspx.cs
TeamTracker/Settings.aspx.cs
using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); } //--------------------------------------------------------------------------- }
using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; settingsView.Focus(); } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); settingsView.Focus(); } //--------------------------------------------------------------------------- }
Fix for 'new' setting button triggering if you hit enter when editing a setting.
Fix for 'new' setting button triggering if you hit enter when editing a setting.
C#
mit
grae22/TeamTracker
682455e4fc3d0db782a89eab4456d4c930d886c2
source/ADAPT/Equipment/ConnectorTypeEnum.cs
source/ADAPT/Equipment/ConnectorTypeEnum.cs
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, } }
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, ChassisMountedSelfPropelled } }
Update List of ConnectorTypes to be compatible with ISOBUS.net List
Update List of ConnectorTypes to be compatible with ISOBUS.net List
C#
epl-1.0
ADAPT/ADAPT
54f0ab7b705f20dee3a07ffa8cebe3a097a7125b
Source/Engine/AGS.Engine.Desktop/DesktopFileSystem.cs
Source/Engine/AGS.Engine.Desktop/DesktopFileSystem.cs
using System; using System.Collections.Generic; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } public IEnumerable<string> GetDirectories(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetFiles: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetDirectories(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetDirectories: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } }
Test fix- catching permission denied exceptions
Test fix- catching permission denied exceptions
C#
artistic-2.0
tzachshabtay/MonoAGS
aeabdcf100f064f737fa8d995aeca3d7927a5142
Common/CommonAssemblyInfo.cs
Common/CommonAssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] // If you change this version, make sure to change Build\build.proj accordingly [assembly: AssemblyVersion("28.0.0")] [assembly: AssemblyFileVersion("28.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] // If you change this version, make sure to change Build\build.proj accordingly [assembly: AssemblyVersion("28.0.0.0")] [assembly: AssemblyFileVersion("28.0.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
Make version 4 digits to fix replacement regex
Make version 4 digits to fix replacement regex
C#
apache-2.0
badescuga/kudu,chrisrpatterson/kudu,sitereactor/kudu,EricSten-MSFT/kudu,shrimpy/kudu,mauricionr/kudu,kali786516/kudu,kenegozi/kudu,kali786516/kudu,shrimpy/kudu,bbauya/kudu,MavenRain/kudu,kenegozi/kudu,sitereactor/kudu,shibayan/kudu,juoni/kudu,badescuga/kudu,barnyp/kudu,oliver-feng/kudu,juvchan/kudu,sitereactor/kudu,juoni/kudu,barnyp/kudu,duncansmart/kudu,MavenRain/kudu,kenegozi/kudu,projectkudu/kudu,puneet-gupta/kudu,juvchan/kudu,YOTOV-LIMITED/kudu,projectkudu/kudu,uQr/kudu,puneet-gupta/kudu,juoni/kudu,duncansmart/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,dev-enthusiast/kudu,kali786516/kudu,barnyp/kudu,juoni/kudu,kali786516/kudu,bbauya/kudu,YOTOV-LIMITED/kudu,chrisrpatterson/kudu,juvchan/kudu,dev-enthusiast/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,puneet-gupta/kudu,badescuga/kudu,shrimpy/kudu,shrimpy/kudu,projectkudu/kudu,mauricionr/kudu,mauricionr/kudu,badescuga/kudu,uQr/kudu,EricSten-MSFT/kudu,bbauya/kudu,oliver-feng/kudu,chrisrpatterson/kudu,projectkudu/kudu,chrisrpatterson/kudu,mauricionr/kudu,dev-enthusiast/kudu,MavenRain/kudu,uQr/kudu,shibayan/kudu,MavenRain/kudu,projectkudu/kudu,bbauya/kudu,EricSten-MSFT/kudu,sitereactor/kudu,shibayan/kudu,juvchan/kudu,shibayan/kudu,barnyp/kudu,duncansmart/kudu,duncansmart/kudu,uQr/kudu,sitereactor/kudu,puneet-gupta/kudu,kenegozi/kudu,dev-enthusiast/kudu,puneet-gupta/kudu,oliver-feng/kudu,juvchan/kudu,oliver-feng/kudu,YOTOV-LIMITED/kudu,shibayan/kudu
be589ef4df09d9c5eb9072d395515ee3b0cb1dbb
LibGit2Sharp/FetchOptions.cs
LibGit2Sharp/FetchOptions.cs
using LibGit2Sharp.Handlers; namespace LibGit2Sharp { /// <summary> /// Collection of parameters controlling Fetch behavior. /// </summary> public sealed class FetchOptions { /// <summary> /// Specifies the tag-following behavior of the fetch operation. /// <para> /// If not set, the fetch operation will follow the default behavior for the <see cref="Remote"/> /// based on the remote's <see cref="Remote.TagFetchMode"/> configuration. /// </para> /// <para>If neither this property nor the remote `tagopt` configuration is set, /// this will default to <see cref="TagFetchMode.Auto"/> (i.e. tags that point to objects /// retrieved during this fetch will be retrieved as well).</para> /// </summary> public TagFetchMode? TagFetchMode { get; set; } /// <summary> /// Delegate that progress updates of the network transfer portion of fetch /// will be reported through. /// </summary> public ProgressHandler OnProgress { get; set; } /// <summary> /// Delegate that updates of remote tracking branches will be reported through. /// </summary> public UpdateTipsHandler OnUpdateTips { get; set; } /// <summary> /// Callback method that transfer progress will be reported through. /// <para> /// Reports the client's state regarding the received and processed (bytes, objects) from the server. /// </para> /// </summary> public TransferProgressHandler OnTransferProgress { get; set; } /// <summary> /// Credentials to use for username/password authentication. /// </summary> public Credentials Credentials { get; set; } } }
using LibGit2Sharp.Handlers; namespace LibGit2Sharp { /// <summary> /// Collection of parameters controlling Fetch behavior. /// </summary> public sealed class FetchOptions { /// <summary> /// Specifies the tag-following behavior of the fetch operation. /// <para> /// If not set, the fetch operation will follow the default behavior for the <see cref="Remote"/> /// based on the remote's <see cref="Remote.TagFetchMode"/> configuration. /// </para> /// <para>If neither this property nor the remote `tagopt` configuration is set, /// this will default to <see cref="F:TagFetchMode.Auto"/> (i.e. tags that point to objects /// retrieved during this fetch will be retrieved as well).</para> /// </summary> public TagFetchMode? TagFetchMode { get; set; } /// <summary> /// Delegate that progress updates of the network transfer portion of fetch /// will be reported through. /// </summary> public ProgressHandler OnProgress { get; set; } /// <summary> /// Delegate that updates of remote tracking branches will be reported through. /// </summary> public UpdateTipsHandler OnUpdateTips { get; set; } /// <summary> /// Callback method that transfer progress will be reported through. /// <para> /// Reports the client's state regarding the received and processed (bytes, objects) from the server. /// </para> /// </summary> public TransferProgressHandler OnTransferProgress { get; set; } /// <summary> /// Credentials to use for username/password authentication. /// </summary> public Credentials Credentials { get; set; } } }
Fix Xml documentation compilation warning
Fix Xml documentation compilation warning
C#
mit
jorgeamado/libgit2sharp,shana/libgit2sharp,Zoxive/libgit2sharp,rcorre/libgit2sharp,dlsteuer/libgit2sharp,xoofx/libgit2sharp,OidaTiftla/libgit2sharp,red-gate/libgit2sharp,vivekpradhanC/libgit2sharp,AMSadek/libgit2sharp,ethomson/libgit2sharp,nulltoken/libgit2sharp,jorgeamado/libgit2sharp,Skybladev2/libgit2sharp,rcorre/libgit2sharp,Zoxive/libgit2sharp,whoisj/libgit2sharp,sushihangover/libgit2sharp,psawey/libgit2sharp,psawey/libgit2sharp,mono/libgit2sharp,nulltoken/libgit2sharp,dlsteuer/libgit2sharp,AMSadek/libgit2sharp,PKRoma/libgit2sharp,xoofx/libgit2sharp,red-gate/libgit2sharp,GeertvanHorrik/libgit2sharp,OidaTiftla/libgit2sharp,libgit2/libgit2sharp,sushihangover/libgit2sharp,Skybladev2/libgit2sharp,shana/libgit2sharp,github/libgit2sharp,vivekpradhanC/libgit2sharp,oliver-feng/libgit2sharp,jeffhostetler/public_libgit2sharp,jeffhostetler/public_libgit2sharp,oliver-feng/libgit2sharp,GeertvanHorrik/libgit2sharp,whoisj/libgit2sharp,mono/libgit2sharp,vorou/libgit2sharp,vorou/libgit2sharp,ethomson/libgit2sharp,jamill/libgit2sharp,AArnott/libgit2sharp,AArnott/libgit2sharp,github/libgit2sharp,jamill/libgit2sharp
54363cc27bb1e1354627e71ba6a61468f9579176
Configgy/Properties/AssemblyInfo.cs
Configgy/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; // 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("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.0.0-alpha1")]
using System.Resources; using System.Reflection; // 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("Configgy")] [assembly: AssemblyDescription("Configgy: Configuration library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Configgy")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.0.1.1")] [assembly: AssemblyFileVersion("1.0.1.1")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.0.1-beta1")]
Update to beta1 for next release
Update to beta1 for next release
C#
mit
bungeemonkee/Configgy
37e3a47e4fa896f4ada4a7be7b4f87cc07f7fd90
FuzzyCore/CommandClasses/GetFile.cs
FuzzyCore/CommandClasses/GetFile.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using FuzzyCore.Server; namespace FuzzyCore.Commands { public class GetFile { ConsoleMessage Message = new ConsoleMessage(); public void GetFileBytes(Data.JsonCommand Command) { try { byte[] file = File.ReadAllBytes(Command.FilePath + "\\" + Command.Text); if (file.Length > 0) { SendDataArray(file, Command.Client_Socket); Message.Write(Command.CommandType,ConsoleMessage.MessageType.SUCCESS); } } catch (Exception ex) { Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR); } } public void SendDataArray(byte[] Data, Socket Client) { try { Thread.Sleep(100); Client.Send(Data); } catch (Exception ex) { Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR); } } } }
using FuzzyCore.Data; using FuzzyCore.Server; using System; using System.IO; namespace FuzzyCore.Commands { public class GetFile { ConsoleMessage Message = new ConsoleMessage(); private String FilePath; private String FileName; private JsonCommand mCommand; public GetFile(Data.JsonCommand Command) { FilePath = Command.FilePath; FileName = Command.Text; this.mCommand = Command; } bool FileControl() { FileInfo mfileInfo = new FileInfo(FilePath); return mfileInfo.Exists; } public byte[] GetFileBytes() { if (FileControl()) { byte[] file = File.ReadAllBytes(FilePath + "/" + FileName); return file; } return new byte[0]; } public string GetFileText() { if (FileControl()) { return File.ReadAllText(FilePath + "/" + FileName); } return ""; } } }
Delete sender and edit constructor functions
Delete sender and edit constructor functions
C#
mit
muhammedikinci/FuzzyCore
df8da304379bafeb89edf9a65ff174a3b75eb07e
EchoClient/Program.cs
EchoClient/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace EchoClient { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { TcpClient client = new TcpClient("::1", 8080); NetworkStream stream = client.GetStream(); StreamReader reader = new StreamReader(stream); StreamWriter writer = new StreamWriter(stream) { AutoFlush = true }; while (true) { Console.WriteLine("What to send?"); string line = Console.ReadLine(); await writer.WriteLineAsync(line); string response = await reader.ReadLineAsync(); Console.WriteLine($"Response from server {response}"); } client.Close(); } } }
using System; using System.IO; using System.Net.Sockets; using System.Threading.Tasks; namespace EchoClient { class Program { const int MAX_WRITE_RETRY = 3; const int WRITE_RETRY_DELAY_SECONDS = 3; static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { using (TcpClient client = new TcpClient("::1", 8080)) { using (NetworkStream stream = client.GetStream()) { using (StreamReader reader = new StreamReader(stream)) { using (StreamWriter writer = new StreamWriter(stream) { AutoFlush = true }) { while (true) { Console.WriteLine("What to send?"); string line = Console.ReadLine(); int writeTry = 0; bool writtenSuccessfully = false; while (!writtenSuccessfully && writeTry < MAX_WRITE_RETRY) { try { writeTry++; await writer.WriteLineAsync(line); writtenSuccessfully = true; } catch (Exception ex) { Console.WriteLine($"Failed to send data to server, try {writeTry} / {MAX_WRITE_RETRY}"); if (!writtenSuccessfully && writeTry == MAX_WRITE_RETRY) { Console.WriteLine($"Write retry reach, please check your connectivity with the server and try again. Error details: {Environment.NewLine}{ex.Message}"); } else { await Task.Delay(WRITE_RETRY_DELAY_SECONDS * 1000); } } } if (!writtenSuccessfully) { continue; } string response = await reader.ReadLineAsync(); Console.WriteLine($"Response from server {response}"); } } } } } } } }
Add write retry mechanism into the client.
Add write retry mechanism into the client.
C#
mit
darkriszty/NetworkCardsGame
2f898b912c34b9e20e06c7c919ca1e01f0c9c38c
Assets/Alensia/Core/Input/BindingKey.cs
Assets/Alensia/Core/Input/BindingKey.cs
using Alensia.Core.Input.Generic; using UnityEngine.Assertions; namespace Alensia.Core.Input { public class BindingKey<T> : IBindingKey<T> where T : IInput { public string Id { get; } public BindingKey(string id) { Assert.IsNotNull(id, "id != null"); Id = id; } public override bool Equals(object obj) { var item = obj as BindingKey<T>; return item != null && Id.Equals(item.Id); } public override int GetHashCode() { return Id.GetHashCode(); } } }
using Alensia.Core.Input.Generic; using UnityEngine.Assertions; namespace Alensia.Core.Input { public class BindingKey<T> : IBindingKey<T> where T : IInput { public string Id { get; } public BindingKey(string id) { Assert.IsNotNull(id, "id != null"); Id = id; } public override bool Equals(object obj) => Id.Equals((obj as BindingKey<T>)?.Id); public override int GetHashCode() => Id.GetHashCode(); } }
Use expression bodied methods for compact code
Use expression bodied methods for compact code
C#
apache-2.0
mysticfall/Alensia
65b1ff23c9213bbb1b3fcc2fd23578f0f7b59f8a
test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs
test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Metadata.ModelConventions; namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels { public static class TestModel { public static IModel Model { get { var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet()); builder.Entity<Product>() .Reference(p => p.ProductCategory) .InverseCollection(c => c.CategoryProducts) .ForeignKey(e => e.ProductCategoryId); return builder.Model; } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Metadata.Conventions.Internal; namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels { public static class TestModel { public static IModel Model { get { var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet()); builder.Entity<Product>() .Reference(p => p.ProductCategory) .InverseCollection(c => c.CategoryProducts) .ForeignKey(e => e.ProductCategoryId); return builder.Model; } } } }
Fix build: react to EF namespace change
Fix build: react to EF namespace change
C#
mit
OmniSharp/omnisharp-scaffolding,OmniSharp/omnisharp-scaffolding
1591f4cafd693121545424055748720a48f41f03
SharedAssemblyInfo.cs
SharedAssemblyInfo.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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AudioSharp")] [assembly: AssemblyCopyright("Copyright (c) 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.3.0")] [assembly: AssemblyFileVersion("1.4.3.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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AudioSharp")] [assembly: AssemblyCopyright("Copyright (c) 2015-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.3.0")] [assembly: AssemblyFileVersion("1.4.3.0")]
Update copyright year in assembly info
Update copyright year in assembly info
C#
mit
Heufneutje/HeufyAudioRecorder,Heufneutje/AudioSharp
2a231695d005fc84a5d0ebd79c8afc4543d3707f
DotNetRu.Utils/Config/AppConfig.cs
DotNetRu.Utils/Config/AppConfig.cs
using System.Text; using DotNetRu.Utils.Helpers; using Newtonsoft.Json; namespace DotNetRu.Clients.UI { public class AppConfig { public string AppCenterAndroidKey { get; set; } public string AppCenteriOSKey { get; set; } public string PushNotificationsChannel { get; set; } public string UpdateFunctionURL { get; set; } public string TweetFunctionUrl { get; set; } public static AppConfig GetConfig() { #if DEBUG return new AppConfig() { AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa", AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae", PushNotificationsChannel = "AuditUpdateDebug", UpdateFunctionURL = "https://dotnetruapp.azurewebsites.net/api/Update", TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets" }; #endif #pragma warning disable CS0162 // Unreachable code detected var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json"); var configBytesAsString = Encoding.UTF8.GetString(configBytes); return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString); #pragma warning restore CS0162 // Unreachable code detected } } }
using System.Text; using DotNetRu.Utils.Helpers; using Newtonsoft.Json; namespace DotNetRu.Clients.UI { public class AppConfig { public string AppCenterAndroidKey { get; set; } public string AppCenteriOSKey { get; set; } public string PushNotificationsChannel { get; set; } public string UpdateFunctionURL { get; set; } public string TweetFunctionUrl { get; set; } public static AppConfig GetConfig() { #if DEBUG return new AppConfig() { AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa", AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae", PushNotificationsChannel = "AuditUpdateDebug", UpdateFunctionURL = "https://dotnetruazure.azurewebsites.net/api/Update", TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets" }; #endif #pragma warning disable CS0162 // Unreachable code detected var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json"); var configBytesAsString = Encoding.UTF8.GetString(configBytes); return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString); #pragma warning restore CS0162 // Unreachable code detected } } }
Update link to Update function
Update link to Update function
C#
mit
DotNetRu/App,DotNetRu/App
7af2e04a49944e7b12849a2af609bbeec1ef2438
src/Test/XamExample/MyPage.xaml.cs
src/Test/XamExample/MyPage.xaml.cs
using System; using System.Collections.Generic; using Xamarin.Forms; namespace XamExample { public partial class MyPage : ContentPage { public MyPage() { InitializeComponent(); var c = 0; XamEffects.TouchEffect.SetColor(plus, Color.White); XamEffects.Commands.SetTap(plus, new Command(() => { c++; counter.Text = $"Touches: {c}"; })); XamEffects.TouchEffect.SetColor(minus, Color.White); XamEffects.Commands.SetTap(minus, new Command(() => { c--; counter.Text = $"Touches: {c}"; })); } } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace XamExample { public partial class MyPage : ContentPage { public MyPage() { InitializeComponent(); var c = 0; XamEffects.TouchEffect.SetColor(plus, Color.White); XamEffects.Commands.SetTap(plus, new Command(() => { c++; counter.Text = $"Touches: {c}"; })); XamEffects.TouchEffect.SetColor(minus, Color.White); XamEffects.Commands.SetLongTap(minus, new Command(() => { c--; counter.Text = $"Touches: {c}"; })); } } }
Update example, add long tap
Update example, add long tap
C#
mit
mrxten/XamEffects
a2116bdf5dc0458cc275369870f779117124caba
XwtPlus.TextEditor/TextEditorOptions.cs
XwtPlus.TextEditor/TextEditorOptions.cs
using Mono.TextEditor.Highlighting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xwt.Drawing; namespace XwtPlus.TextEditor { public class TextEditorOptions { public Font EditorFont = Font.FromName("Consolas 13"); public IndentStyle IndentStyle = IndentStyle.Auto; public int TabSize = 4; public Color Background = Colors.White; public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle; public bool CurrentLineNumberBold = true; } }
using Mono.TextEditor.Highlighting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xwt.Drawing; namespace XwtPlus.TextEditor { public class TextEditorOptions { public Font EditorFont = Font.SystemMonospaceFont; public IndentStyle IndentStyle = IndentStyle.Auto; public int TabSize = 4; public Color Background = Colors.White; public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle; public bool CurrentLineNumberBold = true; } }
Set Default Font to something that should be on all systems
Set Default Font to something that should be on all systems
C#
mit
luiscubal/XwtPlus.TextEditor,cra0zy/XwtPlus.TextEditor
8e8fdc7643afa27ffec62094b2d9f5ae6696b453
Sources/VersionInfo.cs
Sources/VersionInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="VersionInfo.cs" company="Dani Michel"> // Dani Michel 2013 // </copyright> // -------------------------------------------------------------------------------------------------------------------- [assembly: System.Reflection.AssemblyCompany("Dani Michel")] [assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")] [assembly: System.Reflection.AssemblyVersion("0.8.0.*")] [assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="VersionInfo.cs" company="Dani Michel"> // Dani Michel 2013 // </copyright> // -------------------------------------------------------------------------------------------------------------------- [assembly: System.Reflection.AssemblyCompany("Dani Michel")] [assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")] [assembly: System.Reflection.AssemblyVersion("0.8.1")] [assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.1")]
Build number removed from the version string, as this creates problems with NuGet dependencies.
Build number removed from the version string, as this creates problems with NuGet dependencies.
C#
mit
thedmi/MayBee,thedmi/Equ,thedmi/Finalist,thedmi/Equ,thedmi/Finalist,thedmi/MiniGuard
b4369ea97cb410519bc6cc651d711e91a5403279
Scripts/Messages/BaseAckMessage.cs
Scripts/Messages/BaseAckMessage.cs
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public abstract class BaseAckMessage : ILiteNetLibMessage { public uint ackId; public AckResponseCode responseCode; public void Deserialize(NetDataReader reader) { ackId = reader.GetUInt(); responseCode = (AckResponseCode)reader.GetByte(); DeserializeData(reader); } public void Serialize(NetDataWriter writer) { writer.Put(ackId); writer.Put((byte)responseCode); SerializeData(writer); } public abstract void DeserializeData(NetDataReader reader); public abstract void SerializeData(NetDataWriter writer); } }
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public class BaseAckMessage : ILiteNetLibMessage { public uint ackId; public AckResponseCode responseCode; public void Deserialize(NetDataReader reader) { ackId = reader.GetUInt(); responseCode = (AckResponseCode)reader.GetByte(); DeserializeData(reader); } public void Serialize(NetDataWriter writer) { writer.Put(ackId); writer.Put((byte)responseCode); SerializeData(writer); } public virtual void DeserializeData(NetDataReader reader) { } public virtual void SerializeData(NetDataWriter writer) { } } }
Make base ack message not abstract
Make base ack message not abstract
C#
mit
insthync/LiteNetLibManager,insthync/LiteNetLibManager
a537c1d0f95aa6836933e563bdf201dfe861373a
LtiLibrary.AspNet.Tests/LineItemsControllerUnitTests.cs
LtiLibrary.AspNet.Tests/LineItemsControllerUnitTests.cs
using System; using System.Net; using LtiLibrary.Core.Outcomes.v2; using Newtonsoft.Json; using Xunit; namespace LtiLibrary.AspNet.Tests { public class LineItemsControllerUnitTests { [Fact] public void GetLineItemBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.Get(LineItemsController.LineItemId); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } [Fact] public void PostLineItemReturnsValidLineItem() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var lineitem = new LineItem { LineItemOf = new Context { ContextId = LineItemsController.ContextId }, ReportingMethod = "res:Result" }; var result = controller.Post(LineItemsController.ContextId, lineitem); Assert.Equal(HttpStatusCode.Created, result.Result.StatusCode); var lineItem = JsonConvert.DeserializeObject<LineItem>(result.Result.Content.ReadAsStringAsync().Result); Assert.NotNull(lineItem); Assert.Equal(LineItemsController.LineItemId, lineItem.Id.ToString()); } [Fact] public void GetLineItemsBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.Get(); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } } }
using System; using System.Net; using LtiLibrary.Core.Outcomes.v2; using Newtonsoft.Json; using Xunit; namespace LtiLibrary.AspNet.Tests { public class LineItemsControllerUnitTests { [Fact] public void GetLineItemBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.GetAsync(LineItemsController.LineItemId); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } [Fact] public void PostLineItemReturnsValidLineItem() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var lineitem = new LineItem { LineItemOf = new Context { ContextId = LineItemsController.ContextId }, ReportingMethod = "res:Result" }; var result = controller.PostAsync(LineItemsController.ContextId, lineitem); Assert.Equal(HttpStatusCode.Created, result.Result.StatusCode); var lineItem = JsonConvert.DeserializeObject<LineItem>(result.Result.Content.ReadAsStringAsync().Result); Assert.NotNull(lineItem); Assert.Equal(LineItemsController.LineItemId, lineItem.Id.ToString()); } [Fact] public void GetLineItemsBeforePostReturnsNotFound() { var controller = new LineItemsController(); ControllerSetup.RegisterContext(controller, "LineItems"); var result = controller.GetAsync(); Assert.Equal(HttpStatusCode.NotFound, result.Result.StatusCode); } } }
Add Async suffix to async methods
Add Async suffix to async methods
C#
apache-2.0
andyfmiller/LtiLibrary
4a0613672488e4bdcc5d931f7a1b4eebbe0edcf0
Source/Slinqy.Test.Functional/Utilities/Polling/Poll.cs
Source/Slinqy.Test.Functional/Utilities/Polling/Poll.cs
namespace Slinqy.Test.Functional.Utilities.Polling { using System; using System.Diagnostics; using System.Threading; /// <summary> /// Provides common polling functionality. /// </summary> internal static class Poll { /// <summary> /// Polls the specified function until a certain criteria is met. /// </summary> /// <typeparam name="T">Specifies the return type of the from function.</typeparam> /// <param name="from">Specifies the function to use to retrieve the value.</param> /// <param name="until">Specifies the function to use to test the value.</param> /// <param name="interval">Specifies how often to get the latest value via the from function.</param> /// <param name="maxPollDuration">Specifies the max amount of time to wait for the right value before giving up.</param> public static void Value<T>( Func<T> from, Func<T, bool> until, TimeSpan interval, TimeSpan maxPollDuration) { var stopwatch = Stopwatch.StartNew(); while (until(from())) { if (stopwatch.Elapsed > maxPollDuration) throw new PollTimeoutException(maxPollDuration); Thread.Sleep(interval); } } } }
namespace Slinqy.Test.Functional.Utilities.Polling { using System; using System.Diagnostics; using System.Threading; /// <summary> /// Provides common polling functionality. /// </summary> internal static class Poll { /// <summary> /// Polls the specified function until a certain criteria is met. /// </summary> /// <typeparam name="T">Specifies the return type of the from function.</typeparam> /// <param name="from">Specifies the function to use to retrieve the value.</param> /// <param name="until">Specifies the function to use to test the value.</param> /// <param name="interval">Specifies how often to get the latest value via the from function.</param> /// <param name="maxPollDuration">Specifies the max amount of time to wait for the right value before giving up.</param> public static void Value<T>( Func<T> from, Func<T, bool> until, TimeSpan interval, TimeSpan maxPollDuration) { var stopwatch = Stopwatch.StartNew(); while (until(from()) == false) { if (stopwatch.Elapsed > maxPollDuration) throw new PollTimeoutException(maxPollDuration); Thread.Sleep(interval); } } } }
Fix bug in polling logic.
Fix bug in polling logic.
C#
mit
rakutensf-malex/slinqy,rakutensf-malex/slinqy
40f7858e5fa1a1c84be32ae002daeb837a086eb2
NLogger/NLogger/CustomLogFactory.cs
NLogger/NLogger/CustomLogFactory.cs
using System.Collections.Generic; using System.Configuration; using System.Linq; namespace NLogger { public class CustomLogFactory<T> where T : NLoggerSection { private readonly List<ILogWriterRegistration<T>> _logWriterTypes; public CustomLogFactory() { _logWriterTypes= new List<ILogWriterRegistration<T>>(); } public void RegisterLogWriterType(ILogWriterRegistration<T> registration) { _logWriterTypes.Add(registration); } /// <summary> /// Create a logger using App.config or Web.config settings /// </summary> /// <returns></returns> public ILogger CreateLogger(string sectionName) { var config = (T) ConfigurationManager.GetSection(sectionName); if (config != null) { var writer = GetLogWriter(config); if (writer != null) { return new Logger(writer, config.LogLevel); } } return LoggerFactory.CreateLogger(config); } private ILogWriter GetLogWriter(T config) { var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config)); return type != null ? type.GetWriter(config) : null; } } }
using System.Collections.Generic; using System.Configuration; using System.Linq; namespace NLogger { public class CustomLogFactory<T> where T : NLoggerSection { private readonly List<ILogWriterRegistration<T>> _logWriterTypes; public CustomLogFactory() { _logWriterTypes= new List<ILogWriterRegistration<T>>(); } public void RegisterLogWriterType(ILogWriterRegistration<T> registration) { _logWriterTypes.Add(registration); } public ILogger CreateLogger(string sectionName, Configuration configFile) { var config = (T)configFile.GetSection(sectionName); return CreateLogger(config); } /// <summary> /// Create a logger using App.config or Web.config settings /// </summary> /// <returns></returns> public ILogger CreateLogger(string sectionName) { var config = (T) ConfigurationManager.GetSection(sectionName); return CreateLogger(config); } private ILogger CreateLogger(T config) { if (config != null) { var writer = GetLogWriter(config); if (writer != null) { return new Logger(writer, config.LogLevel); } } return LoggerFactory.CreateLogger(config); } private ILogWriter GetLogWriter(T config) { var type = _logWriterTypes.FirstOrDefault(t => t.HasSection(config)); return type != null ? type.GetWriter(config) : null; } } }
Support config from alternative source
Support config from alternative source
C#
mit
Lethrir/NLogger
80e1d55909210da8fc1a748289805ac5dda76c51
JustEnoughVi/ViMode.cs
JustEnoughVi/ViMode.cs
using System; using MonoDevelop.Ide.Editor; using MonoDevelop.Ide.Editor.Extension; namespace JustEnoughVi { public abstract class ViMode { protected TextEditor Editor { get; set; } public Mode RequestedMode { get; internal set; } protected ViMode(TextEditor editor) { Editor = editor; RequestedMode = Mode.None; } public abstract void Activate(); public abstract void Deactivate(); public abstract bool KeyPress (KeyDescriptor descriptor); protected void SetSelectLines(int start, int end) { var startLine = start > end ? Editor.GetLine(end) : Editor.GetLine(start); var endLine = start > end ? Editor.GetLine(start) : Editor.GetLine(end); Editor.SetSelection(startLine.Offset, endLine.EndOffsetIncludingDelimiter); } } }
using System; using MonoDevelop.Ide.Editor; using MonoDevelop.Ide.Editor.Extension; namespace JustEnoughVi { public abstract class ViMode { protected TextEditor Editor { get; set; } public Mode RequestedMode { get; internal set; } protected ViMode(TextEditor editor) { Editor = editor; RequestedMode = Mode.None; } public abstract void Activate(); public abstract void Deactivate(); public abstract bool KeyPress (KeyDescriptor descriptor); protected void SetSelectLines(int start, int end) { start = Math.Min(start, Editor.LineCount); end = Math.Min(end, Editor.LineCount); var startLine = start > end ? Editor.GetLine(end) : Editor.GetLine(start); var endLine = start > end ? Editor.GetLine(start) : Editor.GetLine(end); Editor.SetSelection(startLine.Offset, endLine.EndOffsetIncludingDelimiter); } } }
Handle overflows in line selection
Handle overflows in line selection
C#
mit
fadookie/monodevelop-justenoughvi,hifi/monodevelop-justenoughvi
c5afcf1c9c394c156e791cb7b6d03ea37ac571f3
src/Umbraco.Core/IO/SystemFiles.cs
src/Umbraco.Core/IO/SystemFiles.cs
using System.IO; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { public class SystemFiles { public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config"; public static string TelemetricsIdentifier => SystemDirectories.Umbraco + "/telemetrics-id.umb"; // TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache public static string GetContentCacheXml(IGlobalSettings globalSettings) { return Path.Combine(globalSettings.LocalTempPath, "umbraco.config"); } } }
using System.IO; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { public class SystemFiles { public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config"; public static string TelemetricsIdentifier => SystemDirectories.Data + "/telemetrics-id.umb"; // TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache public static string GetContentCacheXml(IGlobalSettings globalSettings) { return Path.Combine(globalSettings.LocalTempPath, "umbraco.config"); } } }
Move marker file into App_Data a folder that can never be served
Move marker file into App_Data a folder that can never be served
C#
mit
mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS
63ea463f5d40a6bd244bb5b47cf2328a8f53e0d7
Mono.Nat/SemaphoreSlimExtensions.cs
Mono.Nat/SemaphoreSlimExtensions.cs
using System; using System.Threading; using System.Threading.Tasks; namespace Mono.Nat { public static class SemaphoreSlimExtensions { class SemaphoreSlimDisposable : IDisposable { SemaphoreSlim Semaphore; public SemaphoreSlimDisposable (SemaphoreSlim semaphore) { Semaphore = semaphore; } public void Dispose () { Semaphore?.Release (); Semaphore = null; } } public static async Task<IDisposable> DisposableWaitAsync (this SemaphoreSlim semaphore) { await semaphore.WaitAsync (); return new SemaphoreSlimDisposable (semaphore); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace Mono.Nat { static class SemaphoreSlimExtensions { class SemaphoreSlimDisposable : IDisposable { SemaphoreSlim Semaphore; public SemaphoreSlimDisposable (SemaphoreSlim semaphore) { Semaphore = semaphore; } public void Dispose () { Semaphore?.Release (); Semaphore = null; } } public static async Task<IDisposable> DisposableWaitAsync (this SemaphoreSlim semaphore) { await semaphore.WaitAsync (); return new SemaphoreSlimDisposable (semaphore); } } }
Make this internal. It's not supposed to be part of the API
Make this internal. It's not supposed to be part of the API
C#
mit
mono/Mono.Nat
50ae9d782204f3c9a7eee93785203d96308e16c4
NuPack.Dialog/GlobalSuppressions.cs
NuPack.Dialog/GlobalSuppressions.cs
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")]
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "XamlGeneratedNamespace")]
Add supression for generated xaml class
Add supression for generated xaml class --HG-- extra : rebase_source : 4c3bb4f12c4e333546b0eca536616e3bf8c33b7b
C#
apache-2.0
oliver-feng/nuget,rikoe/nuget,rikoe/nuget,mono/nuget,jholovacs/NuGet,dolkensp/node.net,mrward/NuGet.V2,mrward/NuGet.V2,themotleyfool/NuGet,mrward/NuGet.V2,anurse/NuGet,indsoft/NuGet2,chester89/nugetApi,GearedToWar/NuGet2,oliver-feng/nuget,jholovacs/NuGet,pratikkagda/nuget,zskullz/nuget,atheken/nuget,jholovacs/NuGet,chocolatey/nuget-chocolatey,mrward/nuget,chester89/nugetApi,jmezach/NuGet2,jmezach/NuGet2,kumavis/NuGet,antiufo/NuGet2,xoofx/NuGet,zskullz/nuget,antiufo/NuGet2,pratikkagda/nuget,RichiCoder1/nuget-chocolatey,xoofx/NuGet,jmezach/NuGet2,OneGet/nuget,alluran/node.net,mrward/nuget,mono/nuget,indsoft/NuGet2,RichiCoder1/nuget-chocolatey,pratikkagda/nuget,xoofx/NuGet,mrward/NuGet.V2,antiufo/NuGet2,themotleyfool/NuGet,pratikkagda/nuget,mrward/NuGet.V2,rikoe/nuget,GearedToWar/NuGet2,dolkensp/node.net,kumavis/NuGet,indsoft/NuGet2,GearedToWar/NuGet2,alluran/node.net,jmezach/NuGet2,rikoe/nuget,RichiCoder1/nuget-chocolatey,ctaggart/nuget,alluran/node.net,oliver-feng/nuget,chocolatey/nuget-chocolatey,akrisiun/NuGet,OneGet/nuget,alluran/node.net,mrward/nuget,indsoft/NuGet2,jmezach/NuGet2,ctaggart/nuget,mrward/NuGet.V2,GearedToWar/NuGet2,mrward/nuget,jholovacs/NuGet,chocolatey/nuget-chocolatey,antiufo/NuGet2,zskullz/nuget,chocolatey/nuget-chocolatey,chocolatey/nuget-chocolatey,jmezach/NuGet2,mono/nuget,mrward/nuget,mrward/nuget,RichiCoder1/nuget-chocolatey,zskullz/nuget,anurse/NuGet,indsoft/NuGet2,GearedToWar/NuGet2,oliver-feng/nuget,xoofx/NuGet,pratikkagda/nuget,pratikkagda/nuget,dolkensp/node.net,RichiCoder1/nuget-chocolatey,akrisiun/NuGet,indsoft/NuGet2,RichiCoder1/nuget-chocolatey,xoofx/NuGet,atheken/nuget,ctaggart/nuget,oliver-feng/nuget,OneGet/nuget,antiufo/NuGet2,antiufo/NuGet2,mono/nuget,dolkensp/node.net,OneGet/nuget,jholovacs/NuGet,xoofx/NuGet,xero-github/Nuget,themotleyfool/NuGet,oliver-feng/nuget,ctaggart/nuget,GearedToWar/NuGet2,jholovacs/NuGet,chocolatey/nuget-chocolatey
ca86524c922012b32e7a1420c54b49d96a6df3d6
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.cs
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoom.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; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoom { private object writeLock = new object(); public long RoomID { get; set; } public MultiplayerRoomState State { get; set; } private List<MultiplayerRoomUser> users = new List<MultiplayerRoomUser>(); public IReadOnlyList<MultiplayerRoomUser> Users { get { lock (writeLock) return users.ToArray(); } } public void Join(int user) { lock (writeLock) users.Add(new MultiplayerRoomUser(user)); } public void Leave(int user) { lock (writeLock) users.RemoveAll(u => u.UserID == user); } } }
// 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; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoom { private object writeLock = new object(); public long RoomID { get; set; } public MultiplayerRoomState State { get; set; } private List<MultiplayerRoomUser> users = new List<MultiplayerRoomUser>(); public IReadOnlyList<MultiplayerRoomUser> Users { get { lock (writeLock) return users.ToArray(); } } public MultiplayerRoomUser Join(int userId) { var user = new MultiplayerRoomUser(userId); lock (writeLock) users.Add(user); return user; } public MultiplayerRoomUser Leave(int userId) { lock (writeLock) { var user = users.Find(u => u.UserID == userId); if (user == null) return null; users.Remove(user); return user; } } } }
Add locking on join/leave operations
Add locking on join/leave operations
C#
mit
peppy/osu-new,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu
469ac7f48d4b432b83136887cc322e63252ed600
src/MitternachtBot/Modules/Forum/Services/ForumService.cs
src/MitternachtBot/Modules/Forum/Services/ForumService.cs
using System; using System.Threading.Tasks; using Mitternacht.Services; using NLog; namespace Mitternacht.Modules.Forum.Services { public class ForumService : IMService { private readonly IBotCredentials _creds; private readonly Logger _log; public GommeHDnetForumAPI.Forum Forum { get; private set; } public bool HasForumInstance => Forum != null; public bool LoggedIn => Forum?.LoggedIn ?? false; private Task _loginTask; public ForumService(IBotCredentials creds) { _creds = creds; _log = LogManager.GetCurrentClassLogger(); InitForumInstance(); } public void InitForumInstance() { _loginTask?.Dispose(); _loginTask = Task.Run(() => { try { Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword); _log.Info($"Initialized new Forum instance."); } catch(Exception e) { _log.Warn(e, $"Initializing new Forum instance failed."); } }); } } }
using System; using System.Threading.Tasks; using Mitternacht.Services; using NLog; namespace Mitternacht.Modules.Forum.Services { public class ForumService : IMService { private readonly IBotCredentials _creds; private readonly Logger _log; public GommeHDnetForumAPI.Forum Forum { get; private set; } public bool HasForumInstance => Forum != null; public bool LoggedIn => Forum?.LoggedIn ?? false; private Task _loginTask; public ForumService(IBotCredentials creds) { _creds = creds; _log = LogManager.GetCurrentClassLogger(); InitForumInstance(); } public void InitForumInstance() { _loginTask?.Dispose(); _loginTask = Task.Run(() => { try { Forum = new GommeHDnetForumAPI.Forum(_creds.ForumUsername, _creds.ForumPassword); _log.Info($"Initialized new Forum instance."); } catch(Exception e) { _log.Warn(e, $"Initializing new Forum instance failed: {e}"); } }); } } }
Print information about the exception when the bot fails to log in to the forum.
Print information about the exception when the bot fails to log in to the forum.
C#
mit
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
04cc8f883a26b35a4d26ee90994dd5d73096cf5c
csharp/Hello/HelloClient/Program.cs
csharp/Hello/HelloClient/Program.cs
using System; using Grpc.Core; using Hello; namespace HelloClient { class Program { public static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new HelloService.HelloServiceClient(channel); String user = "Euler"; var reply = client.SayHello(new HelloReq { Name = user }); Console.WriteLine(reply.Result); channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
using System; using Grpc.Core; using Hello; namespace HelloClient { class Program { public static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new HelloService.HelloServiceClient(channel); // ideally you should check for errors here too var reply = client.SayHello(new HelloReq { Name = "Euler" }); Console.WriteLine(reply.Result); try { reply = client.SayHelloStrict(new HelloReq { Name = "Leonhard Euler" }); Console.WriteLine(reply.Result); } catch (RpcException e) { // ouch! // lets print the gRPC error message // which is "Length of `Name` cannot be more than 10 characters" Console.WriteLine(e.Status.Detail); // lets access the error code, which is `INVALID_ARGUMENT` Console.WriteLine(e.Status.StatusCode); // Want its int version for some reason? // you shouldn't actually do this, but if you need for debugging, // you can access `e.Status.StatusCode` which will give you `3` Console.WriteLine((int)e.Status.StatusCode); // Want to take specific action based on specific error? if (e.Status.StatusCode == Grpc.Core.StatusCode.InvalidArgument) { // do your thing } } channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
Add error handling for the client
Add error handling for the client
C#
mit
avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors
9e1578624d13a59b0e4ffb780ba9c856021ec68b
src/content/CloudBoilerplateNet/Views/Home/Index.cshtml
src/content/CloudBoilerplateNet/Views/Home/Index.cshtml
@model IEnumerable<Article> @{ ViewData["Title"] = "Home Page"; } <div class="header clearfix"> <nav> <ul class="nav nav-pills pull-right"> <li role="presentation" class="active"><a href="/">Home</a></li> <li role="presentation"><a href="https://kenticocloud.com/" target="_blank">Kentico Cloud</a></li> <li role="presentation"><a href="https://app.kenticocloud.com/sign-up" target="_blank">Sign up</a></li> </ul> </nav> <h3 class="text-muted">Kentico Cloud Boilerplate</h3> </div> <div class="jumbotron"> <h1>Let's Get Started</h1> <p class="lead">This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code how this page works.</p> <p><a class="btn btn-lg btn-success" href="https://github.com/Kentico/cloud-boilerplate-net#quick-start" target="_blank" role="button">Read the Quick Start</a></p> </div> <div class="row marketing"> <h2>Articles from the Dancing Goat Sample Site</h2> </div> <div class="row marketing"> @* This MVC helper method ensures that current model is rendered with suitable view from /Views/Shared/DisplayTemplates *@ @Html.DisplayForModel() </div>
@model IEnumerable<Article> @{ ViewData["Title"] = "Home Page"; } <div class="header clearfix"> <nav> <ul class="nav nav-pills pull-right"> <li role="presentation" class="active"><a href="/">Home</a></li> <li role="presentation"><a href="https://kenticocloud.com/" target="_blank">Kentico Cloud</a></li> <li role="presentation"><a href="https://app.kenticocloud.com/sign-up" target="_blank">Sign up</a></li> </ul> </nav> <h3 class="text-muted">Kentico Cloud Boilerplate</h3> </div> <div class="jumbotron"> <h1>Let's Get Started</h1> <p class="lead">This boilerplate includes a set of features and best practices to kick off your website development with Kentico Cloud smoothly. Take a look into the code to see how it works.</p> <p><a class="btn btn-lg btn-success" href="https://github.com/Kentico/cloud-boilerplate-net#quick-start" target="_blank" role="button">Read the Quick Start</a></p> </div> <div class="row marketing"> <h2>Articles from the Dancing Goat Sample Site</h2> </div> <div class="row marketing"> @* This MVC helper method ensures that current model is rendered with suitable view from /Views/Shared/DisplayTemplates *@ @Html.DisplayForModel() </div>
Correct copy on the home page
Correct copy on the home page The last sentence in the jumbotron on home page is missing a verb.
C#
mit
Kentico/cloud-boilerplate-net,Kentico/cloud-boilerplate-net,Kentico/cloud-boilerplate-net
f55b3faa6e0c4cbebe04e92c28c171b8f897ecab
Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs
Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase { public override bool CanHandle(Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); } private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer) { var array = new JsonArray(); for (int i = 0; i < stack.Count; i++) { array.Add(serializer.Serialize(stack.ElementAt(i))); } return array; } private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer) { var stack = new Stack<T>(); for (int i = 0; i < json.Array.Count; i++) { stack.Push(serializer.Deserialize<T>(json.Array[i])); } return stack; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { internal class StackSerializationDelegateProvider : SerializationDelegateProviderBase { public override bool CanHandle(Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); } private static JsonValue _Encode<T>(Stack<T> stack, JsonSerializer serializer) { var values = new JsonValue[stack.Count]; for (int i = 0; i < values.Length; i++) { values[0] = serializer.Serialize(stack.ElementAt(i)); } return new JsonArray(values); } private static Stack<T> _Decode<T>(JsonValue json, JsonSerializer serializer) { var array = json.Array; var values = new T[array.Count]; for (int i = 0; i < values.Length; i++) { values[i] = serializer.Deserialize<T>(array[i]); } return new Stack<T>(values); } } }
Decrease allocations in stack serializer
Decrease allocations in stack serializer
C#
mit
gregsdennis/Manatee.Json,gregsdennis/Manatee.Json
07c9cf2a4b9133a218323a4817a6e0d6b69e15f1
HeadRaceTiming-Site/Models/Crew.cs
HeadRaceTiming-Site/Models/Crew.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HeadRaceTimingSite.Models { public class Crew { public int CrewId { get; set; } public string Name { get; set; } public int StartNumber { get; set; } public List<Result> Results { get; set; } public int CompetitionId { get; set; } public Competition Competition { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HeadRaceTimingSite.Models { public class Crew { public int CrewId { get; set; } public string Name { get; set; } public int StartNumber { get; set; } public TimeSpan? RunTime(TimingPoint startPoint, TimingPoint finishPoint) { Result start = Results.First(r => r.TimingPointId == startPoint.TimingPointId); Result finish = Results.First(r => r.TimingPointId == finishPoint.TimingPointId); if (start != null && finish != null) return finish.TimeOfDay - start.TimeOfDay; else return null; } public List<Result> Results { get; set; } public int CompetitionId { get; set; } public Competition Competition { get; set; } } }
Add method to calculate time
Add method to calculate time
C#
mit
MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site
d7057af49f2e136b2a5f8246cc32e56d6ebc28e7
Source/HelixToolkit.SharpDX.SharedModel/Element3D/PostEffects/PostEffectMeshBorderHighlight.cs
Source/HelixToolkit.SharpDX.SharedModel/Element3D/PostEffects/PostEffectMeshBorderHighlight.cs
#if NETFX_CORE namespace HelixToolkit.UWP #else namespace HelixToolkit.Wpf.SharpDX #endif { using Model.Scene; /// <summary> /// Highlight the border of meshes /// </summary> public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur { protected override SceneNode OnCreateSceneNode() { return new NodePostEffectMeshOutlineBlur(); } } }
#if NETFX_CORE namespace HelixToolkit.UWP #else namespace HelixToolkit.Wpf.SharpDX #endif { using Model.Scene; /// <summary> /// Highlight the border of meshes /// </summary> public class PostEffectMeshBorderHighlight : PostEffectMeshOutlineBlur { protected override SceneNode OnCreateSceneNode() { return new NodePostEffectBorderHighlight(); } } }
Fix border highlight effects gets the wrong effect node
Fix border highlight effects gets the wrong effect node
C#
mit
JeremyAnsel/helix-toolkit,holance/helix-toolkit,chrkon/helix-toolkit,helix-toolkit/helix-toolkit
ccbf34725d6148682d7d29bf2b6a3c295d231f2b
Source/Core/Pipeline/080_NotifySignalRAction.cs
Source/Core/Pipeline/080_NotifySignalRAction.cs
#region Copyright 2014 Exceptionless // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // http://www.gnu.org/licenses/agpl-3.0.html #endregion using System; using System.Threading.Tasks; using CodeSmith.Core.Component; using Exceptionless.Core.Messaging; using Exceptionless.Core.Messaging.Models; using Exceptionless.Core.Plugins.EventProcessor; namespace Exceptionless.Core.Pipeline { [Priority(80)] public class NotifySignalRAction : EventPipelineActionBase { private readonly IMessagePublisher _publisher; public NotifySignalRAction(IMessagePublisher publisher) { _publisher = publisher; } protected override bool ContinueOnError { get { return true; } } public override void Process(EventContext ctx) { Task.Factory.StartNewDelayed(1000, () => _publisher.Publish(new EventOccurrence { Id = ctx.Event.Id, OrganizationId = ctx.Event.OrganizationId, ProjectId = ctx.Event.ProjectId, StackId = ctx.Event.StackId, Type = ctx.Event.Type, IsHidden = ctx.Event.IsHidden, IsFixed = ctx.Event.IsFixed, IsNotFound = ctx.Event.IsNotFound(), IsRegression = ctx.IsRegression })); } } }
#region Copyright 2014 Exceptionless // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // http://www.gnu.org/licenses/agpl-3.0.html #endregion using System; using System.Threading.Tasks; using CodeSmith.Core.Component; using Exceptionless.Core.Messaging; using Exceptionless.Core.Messaging.Models; using Exceptionless.Core.Plugins.EventProcessor; namespace Exceptionless.Core.Pipeline { [Priority(80)] public class NotifySignalRAction : EventPipelineActionBase { private readonly IMessagePublisher _publisher; public NotifySignalRAction(IMessagePublisher publisher) { _publisher = publisher; } protected override bool ContinueOnError { get { return true; } } public override void Process(EventContext ctx) { Task.Factory.StartNewDelayed(1500, () => _publisher.Publish(new EventOccurrence { Id = ctx.Event.Id, OrganizationId = ctx.Event.OrganizationId, ProjectId = ctx.Event.ProjectId, StackId = ctx.Event.StackId, Type = ctx.Event.Type, IsHidden = ctx.Event.IsHidden, IsFixed = ctx.Event.IsFixed, IsNotFound = ctx.Event.IsNotFound(), IsRegression = ctx.IsRegression })); } } }
Increase the message notification delay slightly.
Increase the message notification delay slightly.
C#
apache-2.0
adamzolotarev/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless,adamzolotarev/Exceptionless,adamzolotarev/Exceptionless,exceptionless/Exceptionless
1e5efe755937a65d71be0ad625eca98a995882d2
Battlezeppelins/Controllers/GameController.cs
Battlezeppelins/Controllers/GameController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public class GameController : BaseController { public ActionResult Metadata() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { return Json(new { playing = true, opponent = game.opponent.name }, JsonRequestBehavior.AllowGet); } else { return Json(new { playing = false }, JsonRequestBehavior.AllowGet); } } public ActionResult Surrender() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { game.Surrender(); } return null; } public ActionResult AddZeppelin() { Game game = Game.GetInstance(base.GetPlayer()); string typeStr = Request.Form["type"]; ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true); int x = Int32.Parse(Request.Form["x"]); int y = Int32.Parse(Request.Form["y"]); bool rotDown = Boolean.Parse(Request.Form["rotDown"]); Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown); bool zeppelinAdded = game.AddZeppelin(zeppelin); return Json(zeppelinAdded, JsonRequestBehavior.AllowGet); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Battlezeppelins.Models; namespace Battlezeppelins.Controllers { public class GameController : BaseController { public ActionResult Metadata() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { return Json(new { playing = true, opponent = game.opponent.name, gameState = game.gameState.ToString() }, JsonRequestBehavior.AllowGet); } else { return Json(new { playing = false }, JsonRequestBehavior.AllowGet); } } public ActionResult Surrender() { Game game = Game.GetInstance(base.GetPlayer()); if (game != null) { game.Surrender(); } return null; } public ActionResult AddZeppelin() { Game game = Game.GetInstance(base.GetPlayer()); string typeStr = Request.Form["type"]; ZeppelinType type = (ZeppelinType)Enum.Parse(typeof(ZeppelinType), typeStr, true); int x = Int32.Parse(Request.Form["x"]); int y = Int32.Parse(Request.Form["y"]); bool rotDown = Boolean.Parse(Request.Form["rotDown"]); Zeppelin zeppelin = new Zeppelin(type, x, y, rotDown); bool zeppelinAdded = game.AddZeppelin(zeppelin); return Json(zeppelinAdded, JsonRequestBehavior.AllowGet); } } }
Send game state to client.
Send game state to client.
C#
apache-2.0
Mikuz/Battlezeppelins,Mikuz/Battlezeppelins
57e936e6bda2a9f9f60cc9329ab5ad559679a2bc
Ductus.FluentDocker/Model/HostEvents/Event.cs
Ductus.FluentDocker/Model/HostEvents/Event.cs
namespace Ductus.FluentDocker.Model.HostEvents { /// <summary> /// Base evnet emitte by the docker dameon using e.g. docker events. /// </summary> /// <remarks> /// See docker documentation https://docs.docker.com/engine/reference/commandline/events/ /// </remarks> public class Event { /// <summary> /// The type of the event. /// </summary> public EventType Type { get; set; } /// <summary> /// The event action /// </summary> public EventAction Action { get; set; } } }
namespace Ductus.FluentDocker.Model.HostEvents { /// <summary> /// Base evnet emitte by the docker dameon using e.g. docker events. /// </summary> /// <remarks> /// See docker documentation https://docs.docker.com/engine/reference/commandline/events/ /// </remarks> public class Event { /// <summary> /// The type of the event. /// </summary> public EventType Type { get; set; } /// <summary> /// The event action /// </summary> public EventAction Action { get; set; } } }
Fix formatting in events so it will build
Fix formatting in events so it will build
C#
apache-2.0
mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker
3f2f8eaf535de487c7ac4fc7032ecf0011b4b771
src/FakeItEasy/Core/StrictFakeRule.cs
src/FakeItEasy/Core/StrictFakeRule.cs
namespace FakeItEasy.Core { using System; using static FakeItEasy.ObjectMembers; internal class StrictFakeRule : IFakeObjectCallRule { private readonly StrictFakeOptions options; public StrictFakeRule(StrictFakeOptions options) { this.options = options; } public int? NumberOfTimesToCall => null; public bool IsApplicableTo(IFakeObjectCall fakeObjectCall) { if (fakeObjectCall.Method.IsSameMethodAs(EqualsMethod)) { return !this.HasOption(StrictFakeOptions.AllowEquals); } if (fakeObjectCall.Method.IsSameMethodAs(GetHashCodeMethod)) { return !this.HasOption(StrictFakeOptions.AllowGetHashCode); } if (fakeObjectCall.Method.IsSameMethodAs(ToStringMethod)) { return !this.HasOption(StrictFakeOptions.AllowToString); } if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { return !this.HasOption(StrictFakeOptions.AllowEvents); } return true; } public void Apply(IInterceptedFakeObjectCall fakeObjectCall) { string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall); if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes; } throw new ExpectationException(message); } private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag; } }
namespace FakeItEasy.Core { using System; using static FakeItEasy.ObjectMembers; internal class StrictFakeRule : IFakeObjectCallRule { private readonly StrictFakeOptions options; public StrictFakeRule(StrictFakeOptions options) { this.options = options; } public int? NumberOfTimesToCall => null; public bool IsApplicableTo(IFakeObjectCall fakeObjectCall) { if (fakeObjectCall.Method.HasSameBaseMethodAs(EqualsMethod)) { return !this.HasOption(StrictFakeOptions.AllowEquals); } if (fakeObjectCall.Method.HasSameBaseMethodAs(GetHashCodeMethod)) { return !this.HasOption(StrictFakeOptions.AllowGetHashCode); } if (fakeObjectCall.Method.HasSameBaseMethodAs(ToStringMethod)) { return !this.HasOption(StrictFakeOptions.AllowToString); } if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { return !this.HasOption(StrictFakeOptions.AllowEvents); } return true; } public void Apply(IInterceptedFakeObjectCall fakeObjectCall) { string message = ExceptionMessages.CallToUnconfiguredMethodOfStrictFake(fakeObjectCall); if (EventCall.TryGetEventCall(fakeObjectCall, out _)) { message += Environment.NewLine + ExceptionMessages.HandleEventsOnStrictFakes; } throw new ExpectationException(message); } private bool HasOption(StrictFakeOptions flag) => (flag & this.options) == flag; } }
Allow strict Fake to permit access to overridden Object methods
Allow strict Fake to permit access to overridden Object methods
C#
mit
thomaslevesque/FakeItEasy,blairconrad/FakeItEasy,blairconrad/FakeItEasy,FakeItEasy/FakeItEasy,FakeItEasy/FakeItEasy,thomaslevesque/FakeItEasy
f561243f495be0452151dcc0b155b6e5cdbd3b4a
OpenKh.Tools.LayoutViewer/Properties/Settings.Designer.cs
OpenKh.Tools.LayoutViewer/Properties/Settings.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OpenKh.Tools.LayoutViewer { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Drawing.Color BackgroundColor { get { return ((global::System.Drawing.Color)(this["BackgroundColor"])); } set { this["BackgroundColor"] = value; } } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OpenKh.Tools.LayoutViewer { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValue("Magenta")] public global::System.Drawing.Color BackgroundColor { get { return ((global::System.Drawing.Color)(this["BackgroundColor"])); } set { this["BackgroundColor"] = value; } } } }
Set default value to BackgroundColor
Set default value to BackgroundColor
C#
mit
Xeeynamo/KingdomHearts
d0fa35e851f13fb00b4789d0151f3a6c8c378e26
Espera/Espera.Core/SoundCloudSong.cs
Espera/Espera.Core/SoundCloudSong.cs
using Espera.Network; using Newtonsoft.Json; using System; namespace Espera.Core { public class SoundCloudSong : Song { public SoundCloudSong() : base(String.Empty, TimeSpan.Zero) { } [JsonProperty("artwork_url")] public Uri ArtworkUrl { get; set; } public string Description { get; set; } [JsonProperty("duration")] public int DurationMilliseconds { get { return (int)this.Duration.TotalMilliseconds; } set { this.Duration = TimeSpan.FromMilliseconds(value); } } public int Id { get; set; } [JsonProperty("streamable")] public bool IsStreamable { get; set; } public override bool IsVideo { get { return false; } } public override NetworkSongSource NetworkSongSource { get { return NetworkSongSource.Youtube; } } [JsonProperty("permalink_url")] public Uri PermaLinkUrl { get { return new Uri(this.OriginalPath); } set { this.OriginalPath = value.ToString(); } } [JsonProperty("stream_url")] public Uri StreamUrl { get { return new Uri(this.PlaybackPath); } set { this.PlaybackPath = value.ToString(); } } public User User { get; set; } } public class User { public string Username { get; set; } } }
using Espera.Network; using Newtonsoft.Json; using System; namespace Espera.Core { public class SoundCloudSong : Song { private User user; public SoundCloudSong() : base(String.Empty, TimeSpan.Zero) { } [JsonProperty("artwork_url")] public Uri ArtworkUrl { get; set; } public string Description { get; set; } [JsonProperty("duration")] public int DurationMilliseconds { get { return (int)this.Duration.TotalMilliseconds; } set { this.Duration = TimeSpan.FromMilliseconds(value); } } public int Id { get; set; } [JsonProperty("streamable")] public bool IsStreamable { get; set; } public override bool IsVideo { get { return false; } } public override NetworkSongSource NetworkSongSource { get { return NetworkSongSource.Youtube; } } [JsonProperty("permalink_url")] public Uri PermaLinkUrl { get { return new Uri(this.OriginalPath); } set { this.OriginalPath = value.ToString(); } } [JsonProperty("stream_url")] public Uri StreamUrl { get { return new Uri(this.PlaybackPath); } set { this.PlaybackPath = value.ToString(); } } public User User { get { return this.user; } set { this.user = value; this.Artist = value.Username; } } } public class User { public string Username { get; set; } } }
Set the artist to the username
Set the artist to the username
C#
mit
flagbug/Espera,punker76/Espera
17102b7283bbde0b1f79a217a47fc2217fc41a52
WinUsbInit/DeviceArrivalListener.cs
WinUsbInit/DeviceArrivalListener.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinUsbInit { class DeviceArrivalListener : NativeWindow { // Constant value was found in the "windows.h" header file. private const int WM_DEVICECHANGE = 537; private const int DBT_DEVICEARRIVAL = 0x8000; private readonly WinUsbInitForm _parent; public DeviceArrivalListener(WinUsbInitForm parent) { parent.HandleCreated += OnHandleCreated; parent.HandleDestroyed += OnHandleDestroyed; _parent = parent; } // Listen for the control's window creation and then hook into it. internal void OnHandleCreated(object sender, EventArgs e) { // Window is now created, assign handle to NativeWindow. AssignHandle(((WinUsbInitForm)sender).Handle); } internal void OnHandleDestroyed(object sender, EventArgs e) { // Window was destroyed, release hook. ReleaseHandle(); } protected override void WndProc(ref Message m) { // Listen for operating system messages if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL) { // Notify the form that this message was received. _parent.DeviceInserted(); } base.WndProc(ref m); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinUsbInit { class DeviceArrivalListener : NativeWindow { // Constant values was found in the "windows.h" header file. private const int WM_DEVICECHANGE = 0x219; private const int DBT_DEVICEARRIVAL = 0x8000; private readonly WinUsbInitForm _parent; public DeviceArrivalListener(WinUsbInitForm parent) { parent.HandleCreated += OnHandleCreated; parent.HandleDestroyed += OnHandleDestroyed; _parent = parent; } // Listen for the control's window creation and then hook into it. internal void OnHandleCreated(object sender, EventArgs e) { // Window is now created, assign handle to NativeWindow. AssignHandle(((WinUsbInitForm)sender).Handle); } internal void OnHandleDestroyed(object sender, EventArgs e) { // Window was destroyed, release hook. ReleaseHandle(); } protected override void WndProc(ref Message m) { // Listen for operating system messages if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL) { // Notify the form that this message was received. _parent.DeviceInserted(); } base.WndProc(ref m); } } }
Change WM_DEVICECHANGE value to hexadecimal
Change WM_DEVICECHANGE value to hexadecimal
C#
mit
ggobbe/WinUsbInit
e9c44438d6256604d8c4b53012eaec67e35c19ee
LynnaLab/UI/SpinButtonHexadecimal.cs
LynnaLab/UI/SpinButtonHexadecimal.cs
using System; using Gtk; namespace LynnaLab { [System.ComponentModel.ToolboxItem(true)] public partial class SpinButtonHexadecimal : Gtk.SpinButton { public SpinButtonHexadecimal() : base(0,100,1) { this.Numeric = false; } protected override int OnOutput() { this.Numeric = false; Text = "0x" + ValueAsInt.ToString("X" + Digits); return 1; } protected override int OnInput(out double value) { try { value = Convert.ToInt32(Text); } catch (Exception e) { try { value = Convert.ToInt32(Text.Substring(2),16); } catch (Exception) { value = Value; } } return 1; } } }
using System; using Gtk; namespace LynnaLab { [System.ComponentModel.ToolboxItem(true)] public partial class SpinButtonHexadecimal : Gtk.SpinButton { public SpinButtonHexadecimal() : base(0,100,1) { this.Numeric = false; } protected override int OnOutput() { this.Numeric = false; Text = "$" + ValueAsInt.ToString("X" + Digits); return 1; } protected override int OnInput(out double value) { string text = Text.Trim(); bool success = false; value = Value; try { value = Convert.ToInt32(text); success = true; } catch (Exception e) { } try { if (text.Length > 0 && text[0] == '$') { value = Convert.ToInt32(text.Substring(1),16); success = true; } } catch (Exception) { } if (!success) value = Value; return 1; } } }
Use $ for hex symbol to match wla
Use $ for hex symbol to match wla
C#
mit
Drenn1/LynnaLab,Drenn1/LynnaLab
f68541e4aac5906a7911d350705dccc2f9c6fcca
Graph/IUndirectedEdge.cs
Graph/IUndirectedEdge.cs
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> /// <typeparam name="W"> /// The type used for the edge weight. /// </typeparam> public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>> where V : struct, IEquatable<V> where W : struct, IComparable<W>, IEquatable<W> { /// <summary> /// The vertices comprising the <see cref="IUndirectedEdge{V}"/>. /// </summary> ISet<V> Vertices { get; } } }
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> /// <typeparam name="W"> /// The type used for the edge weight. /// </typeparam> public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>> where V : struct, IEquatable<V> where W : struct, IComparable<W>, IEquatable<W> { } }
Fix signature of undirected edge
Fix signature of undirected edge
C#
apache-2.0
DasAllFolks/SharpGraphs
04b2b56690a55852f61e02c498c40df749359369
Phoebe/Data/ForeignKeyJsonConverter.cs
Phoebe/Data/ForeignKeyJsonConverter.cs
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
Fix temporary models for relations.
Fix temporary models for relations. ForeignKeyJsonConverter creates temporary models for relations when they don't exist. However, the change in 64362cd changed the default ModifiedAt for models, thus the temporary models became the dominant ones and sync couldn't update them with correct data from server.
C#
bsd-3-clause
peeedge/mobile,masterrr/mobile,eatskolnikov/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,peeedge/mobile
f1f8d3fba8d56987154aaa097014e72b649870cf
Joey/Net/GcmBroadcastReceiver.cs
Joey/Net/GcmBroadcastReceiver.cs
using System; using Android.App; using Android.Content; using Android.Support.V4.Content; namespace Toggl.Joey.Net { [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")] [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[]{ "com.toggl.timer" })] public class GcmBroadcastReceiver : WakefulBroadcastReceiver { public override void OnReceive (Context context, Intent intent) { var comp = new ComponentName (context, Java.Lang.Class.FromType (typeof(GcmService))); StartWakefulService (context, (intent.SetComponent (comp))); ResultCode = Result.Ok; } } }
using System; using Android.App; using Android.Content; using Android.Support.V4.Content; namespace Toggl.Joey.Net { [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")] [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[]{ "com.toggl.timer" })] public class GcmBroadcastReceiver : WakefulBroadcastReceiver { public override void OnReceive (Context context, Intent intent) { var serviceIntent = new Intent (context, typeof(GcmService)); serviceIntent.ReplaceExtras (intent.Extras); StartWakefulService (context, serviceIntent); ResultCode = Result.Ok; } } }
Use new intent instead of reusing broadcast one.
Use new intent instead of reusing broadcast one.
C#
bsd-3-clause
eatskolnikov/mobile,masterrr/mobile,ZhangLeiCharles/mobile,ZhangLeiCharles/mobile,eatskolnikov/mobile,eatskolnikov/mobile,masterrr/mobile,peeedge/mobile,peeedge/mobile
bc3b0a1f77f509307ae86225eeb3bd4c77f4c5a8
SIL.Windows.Forms/ReleaseNotes/ShowReleaseNotesDialog.cs
SIL.Windows.Forms/ReleaseNotes/ShowReleaseNotesDialog.cs
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using MarkdownDeep; using SIL.IO; namespace SIL.Windows.Forms.ReleaseNotes { /// <summary> /// Shows a dialog for release notes; accepts html and markdown /// </summary> public partial class ShowReleaseNotesDialog : Form { private readonly string _path; private TempFile _temp; private readonly Icon _icon; public ShowReleaseNotesDialog(Icon icon, string path) { _path = path; _icon = icon; InitializeComponent(); } private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); _temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp File.WriteAllText(_temp.Path, md.Transform(contents)); _browser.Url = new Uri(_temp.Path); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // a bug in Mono requires us to wait to set Icon until handle created. Icon = _icon; } } }
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using MarkdownDeep; using SIL.IO; namespace SIL.Windows.Forms.ReleaseNotes { /// <summary> /// Shows a dialog for release notes; accepts html and markdown /// </summary> public partial class ShowReleaseNotesDialog : Form { private readonly string _path; private TempFile _temp; private readonly Icon _icon; public ShowReleaseNotesDialog(Icon icon, string path) { _path = path; _icon = icon; InitializeComponent(); } private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); _temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents))); _browser.Url = new Uri(_temp.Path); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // a bug in Mono requires us to wait to set Icon until handle created. Icon = _icon; } private string GetBasicHtmlFromMarkdown(string markdownHtml) { return string.Format("<html><head><meta charset=\"utf-8\"/></head><body>{0}</body></html>", markdownHtml); } } }
Set character encoding when displaying html from markdown (BL-3785)
Set character encoding when displaying html from markdown (BL-3785)
C#
mit
ermshiperete/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,gmartin7/libpalaso
7207c3d58d96b4db0a261fbcb435bfa885257ca5
VasysRomanNumeralsKata/RomanNumeral.cs
VasysRomanNumeralsKata/RomanNumeral.cs
using System; using System.Collections.Generic; using System.Text; namespace VasysRomanNumeralsKata { public class RomanNumeral { private int? _baseTenRepresentation = null; public RomanNumeral(int baseTenNumber) { _baseTenRepresentation = baseTenNumber; } public string GenerateRomanNumeralRepresntation() { StringBuilder romanNumeralBuilder = new StringBuilder(); int numberOfThousands = (int)_baseTenRepresentation / 1000; if (numberOfThousands > 0) { for(int i = 0; i < numberOfThousands; i++) { romanNumeralBuilder.Append("M"); } } int remainder = (int)_baseTenRepresentation % 1000; if (remainder >= 900) { romanNumeralBuilder.Append("CM"); remainder -= 900; } if(remainder >= 500) { romanNumeralBuilder.Append("D"); remainder -= 500; } if (remainder >= 400) { romanNumeralBuilder.Append("CD"); remainder -= 400; } while(remainder >= 100) { romanNumeralBuilder.Append("C"); remainder -= 100; } int numberOfTens = remainder / 10; if (numberOfTens > 0) { for (int i = 0; i < numberOfTens; i++) { romanNumeralBuilder.Append("X"); } } return romanNumeralBuilder.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace VasysRomanNumeralsKata { public class RomanNumeral { private int? _baseTenRepresentation = null; public RomanNumeral(int baseTenNumber) { _baseTenRepresentation = baseTenNumber; } public string GenerateRomanNumeralRepresntation() { StringBuilder romanNumeralBuilder = new StringBuilder(); int remainder = (int)_baseTenRepresentation; while(remainder / 1000 > 0) { romanNumeralBuilder.Append("M"); remainder -= 1000; } if (remainder >= 900) { romanNumeralBuilder.Append("CM"); remainder -= 900; } if(remainder >= 500) { romanNumeralBuilder.Append("D"); remainder -= 500; } if (remainder >= 400) { romanNumeralBuilder.Append("CD"); remainder -= 400; } while(remainder >= 100) { romanNumeralBuilder.Append("C"); remainder -= 100; } int numberOfTens = remainder / 10; if (numberOfTens > 0) { for (int i = 0; i < numberOfTens; i++) { romanNumeralBuilder.Append("X"); } } return romanNumeralBuilder.ToString(); } } }
Refactor logic for thousands (M, MM, MMM).
Refactor logic for thousands (M, MM, MMM).
C#
mit
pvasys/PillarRomanNumeralKata
e1d3052862e28885918c4d0d40c038dc5d1a5238
AssemblyInfo/Program.cs
AssemblyInfo/Program.cs
using System; using System.Reflection; namespace AssemblyInfo { class Program { static void Main(string[] args) { if (args != null && args.Length > 0) { Assembly asm = null; var name = args[0]; try { if (name.Substring(name.Length - 4, 4) != ".dll") name += ".dll"; asm = Assembly.LoadFrom(name); } catch { try { var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name; asm = Assembly.LoadFrom(path); } catch (Exception e) { System.Console.WriteLine(e.Message); return; } } var x = asm.GetName(); System.Console.WriteLine("CodeBase: {0}", x.CodeBase); System.Console.WriteLine("ContentType: {0}", x.ContentType); System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo); System.Console.WriteLine("CultureName: {0}", x.CultureName); System.Console.WriteLine("FullName: {0}", x.FullName); System.Console.WriteLine("Name: {0}", x.Name); System.Console.WriteLine("Version: {0}", x.Version); System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility); } else { System.Console.WriteLine("Usage: asminfo.exe assembly"); } } } }
using System; using System.Reflection; namespace AssemblyInfo { class Program { static void Main(string[] args) { if (args != null && args.Length > 0) { Assembly asm = null; var name = args[0]; try { if (name.Substring(name.Length - 4, 4) != ".dll") { name += ".dll"; } asm = Assembly.LoadFrom(name); } catch { try { var path = AppDomain.CurrentDomain.BaseDirectory + @"\" + name; asm = Assembly.LoadFrom(path); } catch (Exception e) { System.Console.WriteLine(e.Message); return; } } var x = asm.GetName(); System.Console.WriteLine("CodeBase: {0}", x.CodeBase); System.Console.WriteLine("ContentType: {0}", x.ContentType); System.Console.WriteLine("CultureInfo: {0}", x.CultureInfo); System.Console.WriteLine("CultureName: {0}", x.CultureName); System.Console.WriteLine("FullName: {0}", x.FullName); System.Console.WriteLine("Name: {0}", x.Name); System.Console.WriteLine("Version: {0}", x.Version); System.Console.WriteLine("VersionCompatibility: {0}", x.VersionCompatibility); } else { System.Console.WriteLine("Usage: asminfo.exe assembly"); } } } }
Add braces for the 'if (name.Substring(... '
Add braces for the 'if (name.Substring(... '
C#
mit
mansoor-omrani/AssemblyInfo
8f8abab942364670aa9138beef0a0916ca901a70
XlsxValidator/Program.cs
XlsxValidator/Program.cs
using System; using System.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; // Adapted from // https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/ namespace XlsxValidator { class MainClass { public static void Main(string[] args) { if (args.Count() == 0) { Console.WriteLine("No document given"); return; } using (SpreadsheetDocument doc = SpreadsheetDocument.Open(args[0], false)) { var validator = new OpenXmlValidator(); var errors = validator.Validate(doc); if (errors.Count() == 0) { Console.WriteLine("Document is valid"); } else { Console.WriteLine("Document is not valid"); } Console.WriteLine(); foreach (var error in errors) { Console.WriteLine("Error description: {0}", error.Description); Console.WriteLine("Content type of part with error: {0}", error.Part.ContentType); Console.WriteLine("Location of error: {0}", error.Path.XPath); Console.WriteLine(); } } } } }
using System; using System.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; // Adapted from // https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/ namespace XlsxValidator { class MainClass { public static void Main(string[] args) { if (args.Count() == 0) { Console.WriteLine("No document given"); return; } var path = args[0]; using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false)) { var validator = new OpenXmlValidator(); var errors = validator.Validate(doc); if (errors.Count() == 0) { Console.WriteLine("Document is valid"); } else { Console.WriteLine("Document is not valid"); } Console.WriteLine(); foreach (var error in errors) { Console.WriteLine("File: {0}", path); Console.WriteLine("Error: {0}", error.Description); Console.WriteLine("ContentType: {0}", error.Part.ContentType); Console.WriteLine("XPath: {0}", error.Path.XPath); Console.WriteLine(); } } } } }
Print filename with each error
Print filename with each error
C#
apache-2.0
vindvaki/xlsx-validator
16e5e4007c8f73018b23a73fd0470538ed759be1
test/DiceApi.WebApi.Tests/DieControllerTest.cs
test/DiceApi.WebApi.Tests/DieControllerTest.cs
using Microsoft.AspNetCore.Mvc; using Xunit; using DiceApi.WebApi.Controllers; namespace DiceApi.WebApi.Tests { /// <summary> /// Test class for <see cref="DieController" />. /// </summary> public class DieControllerTest { /// <summary> /// Verifies that Get() returns a BadRequestResult when given an invalid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult() { var sut = new DieController(); var result = sut.Get(-1); Assert.Equal(typeof(BadRequestResult), result.GetType()); } /// <summary> /// Verifies that Get() returns an OkObjectResult when given an valid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenValidSizeValue_ReturnsOkResult() { var sut = new DieController(); var result = sut.Get(6); Assert.Equal(typeof(OkObjectResult), result.GetType()); } } }
using Microsoft.AspNetCore.Mvc; using Xunit; using DiceApi.WebApi.Controllers; namespace DiceApi.WebApi.Tests { /// <summary> /// Test class for <see cref="DieController" />. /// </summary> public class DieControllerTest { /// <summary> /// Verifies that Get() returns a BadRequestResult when given an invalid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult() { var sut = new DieController(); var result = sut.Get(-1); Assert.Equal(typeof(BadRequestResult), result.GetType()); } /// <summary> /// Verifies that Get() returns an OkObjectResult when given an valid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenValidSizeValue_ReturnsOkResult() { var sut = new DieController(); var result = sut.Get(6); Assert.Equal(typeof(OkObjectResult), result.GetType()); Assert.Equal(typeof(int), ((OkObjectResult)result).Value.GetType()); } } }
Add extra check on result type
Add extra check on result type
C#
mit
mspons/DiceApi
eb92831b23a5a4060f8f1d8b28f9c07ab0411be1
test/SerilogWeb.Test/Global.asax.cs
test/SerilogWeb.Test/Global.asax.cs
using System; using Serilog; using Serilog.Events; using SerilogWeb.Classic; namespace SerilogWeb.Test { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { ApplicationLifecycleModule.FormDataLoggingLevel = LogEventLevel.Debug; ApplicationLifecycleModule.LogPostedFormData = LogPostedFormDataOption.OnMatch; ApplicationLifecycleModule.ShouldLogPostedFormData = context => context.Response.StatusCode >= 400; // ReSharper disable once PossibleNullReferenceException ApplicationLifecycleModule.RequestFilter = context => context.Request.Url.PathAndQuery.StartsWith("/__browserLink"); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" ) .CreateLogger(); } } }
using System; using Serilog; using Serilog.Events; using SerilogWeb.Classic; namespace SerilogWeb.Test { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { // ReSharper disable once PossibleNullReferenceException SerilogWebClassic.Configuration .IgnoreRequestsMatching(ctx => ctx.Request.Url.PathAndQuery.StartsWith("/__browserLink")) .EnableFormDataLogging(formData => formData .AtLevel(LogEventLevel.Debug) .OnMatch(ctx => ctx.Response.StatusCode >= 400)); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" ) .CreateLogger(); } } }
Update sample app to use newer config API
Update sample app to use newer config API
C#
apache-2.0
serilog-web/classic
503d238a2d80f5c784d1cd55a20a4364ff53cc09
src/core/BrightstarDB.InternalTests/TestConfiguration.cs
src/core/BrightstarDB.InternalTests/TestConfiguration.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrightstarDB.InternalTests { internal static class TestConfiguration { public static string DataLocation = "..\\..\\Data\\"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrightstarDB.InternalTests { internal static class TestConfiguration { public static string DataLocation = "..\\..\\..\\Data\\"; } }
Fix path to internal test data location
Fix path to internal test data location
C#
mit
BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB
bfc9cb955232d806a914c3603ee89b3423e43840
CefSharp/IsBrowserInitializedChangedEventArgs.cs
CefSharp/IsBrowserInitializedChangedEventArgs.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { /// <summary> /// Event arguments to the IsBrowserInitializedChanged event handler. /// </summary> public class IsBrowserInitializedChangedEventArgs : EventArgs { public bool IsBrowserInitialized { get; private set; } public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized) { IsBrowserInitialized = isBrowserInitialized; } } }; /// <summary> /// A delegate type used to listen to IsBrowserInitializedChanged events. /// </summary> public delegate void IsBrowserInitializedChangedEventHandler(object sender, IsBrowserInitializedChangedEventArgs args); }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { /// <summary> /// Event arguments to the IsBrowserInitializedChanged event handler. /// </summary> public class IsBrowserInitializedChangedEventArgs : EventArgs { public bool IsBrowserInitialized { get; private set; } public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized) { IsBrowserInitialized = isBrowserInitialized; } } }
Fix cherry pick, spaces not tabs and remove unused delegate
Fix cherry pick, spaces not tabs and remove unused delegate
C#
bsd-3-clause
rover886/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,AJDev77/CefSharp,dga711/CefSharp,battewr/CefSharp,wangzheng888520/CefSharp,rlmcneary2/CefSharp,Octopus-ITSM/CefSharp,yoder/CefSharp,ruisebastiao/CefSharp,ITGlobal/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,AJDev77/CefSharp,battewr/CefSharp,haozhouxu/CefSharp,illfang/CefSharp,dga711/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,gregmartinhtc/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,rover886/CefSharp,joshvera/CefSharp,yoder/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,gregmartinhtc/CefSharp,joshvera/CefSharp,AJDev77/CefSharp,dga711/CefSharp,Livit/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,twxstar/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,zhangjingpu/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,twxstar/CefSharp,windygu/CefSharp,Livit/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,illfang/CefSharp,NumbersInternational/CefSharp,haozhouxu/CefSharp,rover886/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,ruisebastiao/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,NumbersInternational/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,ITGlobal/CefSharp,Livit/CefSharp,twxstar/CefSharp,NumbersInternational/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,illfang/CefSharp,Octopus-ITSM/CefSharp,battewr/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,zhangjingpu/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,illfang/CefSharp,haozhouxu/CefSharp
e9a18f8f1b17e7046f7e4ba7e693cb5fd9df6441
src/Evolve/Metadata/MetadataTable.cs
src/Evolve/Metadata/MetadataTable.cs
using Evolve.Migration; using System.Collections.Generic; using Evolve.Utilities; using Evolve.Connection; namespace Evolve.Metadata { public abstract class MetadataTable : IEvolveMetadata { protected IWrappedConnection _wrappedConnection; public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection) { Schema = Check.NotNullOrEmpty(schema, nameof(schema)); TableName = Check.NotNullOrEmpty(schema, nameof(tableName)); _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection)); } public string Schema { get; private set; } public string TableName { get; private set; } public abstract void Lock(); public abstract bool CreateIfNotExists(); public void AddMigrationMetadata(MigrationScript migration, bool success) { CreateIfNotExists(); InternalAddMigrationMetadata(migration, success); } public IEnumerable<MigrationMetadata> GetAllMigrationMetadata() { CreateIfNotExists(); return InternalGetAllMigrationMetadata(); } protected abstract bool IsExists(); protected abstract void Create(); protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success); protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata(); } }
using Evolve.Migration; using System.Collections.Generic; using Evolve.Utilities; using Evolve.Connection; namespace Evolve.Metadata { public abstract class MetadataTable : IEvolveMetadata { protected IWrappedConnection _wrappedConnection; public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection) { Schema = Check.NotNullOrEmpty(schema, nameof(schema)); TableName = Check.NotNullOrEmpty(tableName, nameof(tableName)); _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection)); } public string Schema { get; private set; } public string TableName { get; private set; } public abstract void Lock(); public abstract bool CreateIfNotExists(); public void AddMigrationMetadata(MigrationScript migration, bool success) { CreateIfNotExists(); InternalAddMigrationMetadata(migration, success); } public IEnumerable<MigrationMetadata> GetAllMigrationMetadata() { CreateIfNotExists(); return InternalGetAllMigrationMetadata(); } protected abstract bool IsExists(); protected abstract void Create(); protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success); protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata(); } }
Fix tableName not correctly saved
Fix tableName not correctly saved
C#
mit
lecaillon/Evolve
361b0d2db83f2bc00706f1bde137b3ca93b0f2de
src/Kernel32.Tests/Kernel32Facts.cs
src/Kernel32.Tests/Kernel32Facts.cs
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using PInvoke; using Xunit; using static PInvoke.Kernel32; public partial class Kernel32Facts { [Fact] public void GetTickCount_Nonzero() { uint result = GetTickCount(); Assert.NotEqual(0u, result); } [Fact] public void GetTickCount64_Nonzero() { ulong result = GetTickCount64(); Assert.NotEqual(0ul, result); } [Fact] public void SetLastError_ImpactsMarshalGetLastWin32Error() { SetLastError(2); Assert.Equal(2, Marshal.GetLastWin32Error()); } [Fact] public unsafe void GetStartupInfo_Title() { var startupInfo = STARTUPINFO.Create(); GetStartupInfo(ref startupInfo); Assert.NotNull(startupInfo.Title); Assert.NotEqual(0, startupInfo.Title.Length); } }
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; using PInvoke; using Xunit; using static PInvoke.Kernel32; public partial class Kernel32Facts { [Fact] public void GetTickCount_Nonzero() { uint result = GetTickCount(); Assert.NotEqual(0u, result); } [Fact] public void GetTickCount64_Nonzero() { ulong result = GetTickCount64(); Assert.NotEqual(0ul, result); } [Fact] public void SetLastError_ImpactsMarshalGetLastWin32Error() { SetLastError(2); Assert.Equal(2, Marshal.GetLastWin32Error()); } [Fact] public unsafe void GetStartupInfo_Title() { var startupInfo = STARTUPINFO.Create(); GetStartupInfo(ref startupInfo); Assert.NotNull(startupInfo.Title); Assert.NotEqual(0, startupInfo.Title.Length); } [Fact] public void GetHandleInformation_DoesNotThrow() { var manualResetEvent = new ManualResetEvent(false); GetHandleInformation(manualResetEvent.SafeWaitHandle, out var lpdwFlags); } [Fact] public void SetHandleInformation_DoesNotThrow() { var manualResetEvent = new ManualResetEvent(false); SetHandleInformation( manualResetEvent.SafeWaitHandle, HandleFlags.HANDLE_FLAG_INHERIT | HandleFlags.HANDLE_FLAG_PROTECT_FROM_CLOSE, HandleFlags.HANDLE_FLAG_NONE); } }
Add tests for `kernel32!SetHandleInformation` and `kernel32!GetHandleInformation`
Add tests for `kernel32!SetHandleInformation` and `kernel32!GetHandleInformation`
C#
mit
AArnott/pinvoke
a125cc70a3bfaa7287b1285eb0d2994278c19946
Assets/Scripts/RootContext.cs
Assets/Scripts/RootContext.cs
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); IMaterialManager materialManager = managers.GetComponent<MaterialManager>(); injectionBinder.Bind<IMaterialManager>().ToValue(materialManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
Add the Material Manager to the context for injection.
Add the Material Manager to the context for injection.
C#
mit
Mitsugaru/game-off-2016
928bce8fcdee3daf785539cd068b48274eae30e0
osu.Game/Scoring/LegacyDatabasedScore.cs
osu.Game/Scoring/LegacyDatabasedScore.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. #nullable disable using System; using System.Linq; using osu.Framework.IO.Stores; using osu.Game.Beatmaps; using osu.Game.Extensions; using osu.Game.Rulesets; using osu.Game.Scoring.Legacy; namespace osu.Game.Scoring { public class LegacyDatabasedScore : Score { public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store) { ScoreInfo = score; string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath(); if (replayFilename == null) return; using (var stream = store.GetStream(replayFilename)) Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay; } } }
// 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. #nullable disable using System; using System.Linq; using osu.Framework.IO.Stores; using osu.Game.Beatmaps; using osu.Game.Extensions; using osu.Game.Rulesets; using osu.Game.Scoring.Legacy; namespace osu.Game.Scoring { public class LegacyDatabasedScore : Score { public LegacyDatabasedScore(ScoreInfo score, RulesetStore rulesets, BeatmapManager beatmaps, IResourceStore<byte[]> store) { ScoreInfo = score; string replayFilename = score.Files.FirstOrDefault(f => f.Filename.EndsWith(".osr", StringComparison.InvariantCultureIgnoreCase))?.File.GetStoragePath(); if (replayFilename == null) return; using (var stream = store.GetStream(replayFilename)) { if (stream == null) return; Replay = new DatabasedLegacyScoreDecoder(rulesets, beatmaps).Parse(stream).Replay; } } } }
Fix crash when attempting to watch a replay when the storage file doesn't exist
Fix crash when attempting to watch a replay when the storage file doesn't exist
C#
mit
ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
78d027b8d11f38256eb56004f9f6f84f5a6767df
src/Arango/Arango.Client/Protocol/Response.cs
src/Arango/Arango.Client/Protocol/Response.cs
using System; using System.Net; using Arango.fastJSON; namespace Arango.Client.Protocol { internal class Response { internal int StatusCode { get; set; } internal WebHeaderCollection Headers { get; set; } internal string Body { get; set; } internal DataType DataType { get; set; } internal object Data { get; set; } internal Exception Exception { get; set; } internal AEerror Error { get; set; } internal void DeserializeBody() { if (string.IsNullOrEmpty(Body)) { DataType = DataType.Null; Data = null; } else { var trimmedBody = Body.Trim(); // body contains JSON array if (trimmedBody[0] == '[') { DataType = DataType.List; } // body contains JSON object else if (trimmedBody[0] == '{') { DataType = DataType.Document; } else { DataType = DataType.Primitive; } Data = JSON.Parse(trimmedBody); } } } }
using System; using System.Net; using Arango.fastJSON; namespace Arango.Client.Protocol { internal class Response { internal int StatusCode { get; set; } internal WebHeaderCollection Headers { get; set; } internal string Body { get; set; } internal DataType DataType { get; set; } internal object Data { get; set; } internal Exception Exception { get; set; } internal AEerror Error { get; set; } internal void DeserializeBody() { if (string.IsNullOrEmpty(Body)) { DataType = DataType.Null; Data = null; } else { var trimmedBody = Body.Trim(); switch (trimmedBody[0]) { // body contains JSON array case '[': DataType = DataType.List; break; // body contains JSON object case '{': DataType = DataType.Document; break; default: DataType = DataType.Primitive; break; } Data = JSON.Parse(trimmedBody); } } } }
Put body data type check into switch statement
Put body data type check into switch statement
C#
mit
yojimbo87/ArangoDB-NET
ba6c5309e44adeafd2fce84b39cb629dec59b29a
SnittListan/Infrastructure/AutoMapperProfiles/MatchProfile.cs
SnittListan/Infrastructure/AutoMapperProfiles/MatchProfile.cs
using AutoMapper; using SnittListan.Models; using SnittListan.ViewModels; namespace SnittListan.Infrastructure { public class MatchProfile : Profile { protected override void Configure() { Mapper.CreateMap<Match, MatchViewModel>() .ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToShortDateString())) .ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore())) .ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam))); } } }
using System.Threading; using AutoMapper; using SnittListan.Models; using SnittListan.ViewModels; namespace SnittListan.Infrastructure { public class MatchProfile : Profile { protected override void Configure() { Mapper.CreateMap<Match, MatchViewModel>() .ForMember(x => x.Date, o => o.MapFrom(y => y.Date.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, Thread.CurrentThread.CurrentCulture))) .ForMember(x => x.Results, o => o.MapFrom(y => y.FormattedLaneScore())) .ForMember(x => x.Teams, o => o.MapFrom(y => string.Format("{0}-{1}", y.HomeTeam, y.OppTeam))); } } }
Format date with user culture
Format date with user culture Date will be formatted as short date string with user preferred culture.
C#
mit
dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan
ae2120f9eb26e23ffb8fd49b91d98fbecf2dd26b
Harmony/Transpilers.cs
Harmony/Transpilers.cs
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
Revert back to old signature (transpilers get confused with multiple version); add opcode=Call
Revert back to old signature (transpilers get confused with multiple version); add opcode=Call
C#
mit
pardeike/Harmony
ac03ef3d108c8498f92df50cc3bbc2f9ff06a462
src/Website/Program.cs
src/Website/Program.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 System; using Extensions; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// The exit code from the application. /// </returns> public static int Main(string[] args) { try { using (var host = BuildWebHost(args)) { host.Run(); } return 0; } catch (Exception ex) { Console.Error.WriteLine($"Unhandled exception: {ex}"); return -1; } } private static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseKestrel((p) => p.AddServerHeader = false) .UseAutofac() .UseAzureAppServices() .UseApplicationInsights() .UseStartup<Startup>() .CaptureStartupErrors(true) .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 System; using System.Threading.Tasks; using Extensions; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// A <see cref="Task{TResult}"/> that returns the exit code from the application. /// </returns> public static async Task<int> Main(string[] args) { try { using (var host = BuildWebHost(args)) { await host.RunAsync(); } return 0; } catch (Exception ex) { Console.Error.WriteLine($"Unhandled exception: {ex}"); return -1; } } private static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseKestrel((p) => p.AddServerHeader = false) .UseAutofac() .UseAzureAppServices() .UseApplicationInsights() .UseStartup<Startup>() .CaptureStartupErrors(true) .Build(); } } }
Convert Main to be async
Convert Main to be async Convert the Main() method to be asynchronous.
C#
apache-2.0
martincostello/website,martincostello/website,martincostello/website,martincostello/website
c2956613bb1c41cf894f0ab2ee5abd7b363e9356
source/MilitaryPlanner/Views/MainWindow.xaml.cs
source/MilitaryPlanner/Views/MainWindow.xaml.cs
using System.Windows; namespace MilitaryPlanner.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { //InitializeComponent(); } } }
using System.Windows; namespace MilitaryPlanner.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { //InitializeComponent(); } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); // if window is minimized, restore to avoid opening minimized on next run if(WindowState == System.Windows.WindowState.Minimized) { WindowState = System.Windows.WindowState.Normal; } } } }
Fix for saving window state while minimized on closing
Fix for saving window state while minimized on closing
C#
apache-2.0
Esri/military-planner-application-csharp
fd0e50d57626c8fca9a3eb204468cc0ad0350c2c
ParcelTest/PrecedenceTests.cs
ParcelTest/PrecedenceTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>; using Expr = AST.Expression; namespace ParcelTest { [TestClass] class PrecedenceTests { [TestMethod] public void MultiplicationVsAdditionPrecedenceTest() { var mwb = MockWorkbook.standardMockWorkbook(); var e = mwb.envForSheet(1); var f = "=2*3+1"; ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName); Expr correct = Expr.NewBinOpExpr( "+", Expr.NewBinOpExpr( "*", Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0)) ), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0)) ); try { Expr ast = asto.Value; Assert.AreEqual(correct, ast); } catch (NullReferenceException nre) { Assert.Fail("Parse error: " + nre.Message); } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ExprOpt = Microsoft.FSharp.Core.FSharpOption<AST.Expression>; using Expr = AST.Expression; namespace ParcelTest { [TestClass] public class PrecedenceTests { [TestMethod] public void MultiplicationVsAdditionPrecedenceTest() { var mwb = MockWorkbook.standardMockWorkbook(); var e = mwb.envForSheet(1); var f = "=2*3+1"; ExprOpt asto = Parcel.parseFormula(f, e.Path, e.WorkbookName, e.WorksheetName); Expr correct = Expr.NewBinOpExpr( "+", Expr.NewBinOpExpr( "*", Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 2.0)), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 3.0)) ), Expr.NewReferenceExpr(new AST.ReferenceConstant(e, 1.0)) ); try { Expr ast = asto.Value; Assert.AreEqual(correct, ast); } catch (NullReferenceException nre) { Assert.Fail("Parse error: " + nre.Message); } } } }
Make precedence test public to be discoverable by test runner.
Make precedence test public to be discoverable by test runner.
C#
bsd-2-clause
plasma-umass/parcel,plasma-umass/parcel,plasma-umass/parcel
81c16d8d10260cd6aa4590dd55ce6af4228ca871
src/Nest/QueryDsl/MatchAllQuery.cs
src/Nest/QueryDsl/MatchAllQuery.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nest.Resolvers.Converters; using Newtonsoft.Json; namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))] public interface IMatchAllQuery : IQuery { [JsonProperty(PropertyName = "boost")] double? Boost { get; set; } [JsonProperty(PropertyName = "norm_field")] string NormField { get; set; } } public class MatchAllQuery : QueryBase, IMatchAllQuery { public double? Boost { get; set; } public string NormField { get; set; } bool IQuery.Conditionless => false; protected override void WrapInContainer(IQueryContainer container) { container.MatchAllQuery = this; } } public class MatchAllQueryDescriptor : QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery> , IMatchAllQuery { bool IQuery.Conditionless => false; string IQuery.Name { get; set; } double? IMatchAllQuery.Boost { get; set; } string IMatchAllQuery.NormField { get; set; } public MatchAllQueryDescriptor Boost(double? boost) => Assign(a => a.Boost = boost); public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nest.Resolvers.Converters; using Newtonsoft.Json; namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeConverter<MatchAllQuery>))] public interface IMatchAllQuery : IQuery { [JsonProperty(PropertyName = "norm_field")] string NormField { get; set; } } public class MatchAllQuery : QueryBase, IMatchAllQuery { public string NormField { get; set; } bool IQuery.Conditionless => false; protected override void WrapInContainer(IQueryContainer container) { container.MatchAllQuery = this; } } public class MatchAllQueryDescriptor : QueryDescriptorBase<MatchAllQueryDescriptor, IMatchAllQuery> , IMatchAllQuery { bool IQuery.Conditionless => false; string IMatchAllQuery.NormField { get; set; } public MatchAllQueryDescriptor NormField(string normField) => Assign(a => a.NormField = normField); } }
Fix post filter test after boost/descriptor refactoring
Fix post filter test after boost/descriptor refactoring
C#
apache-2.0
KodrAus/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,KodrAus/elasticsearch-net,azubanov/elasticsearch-net,jonyadamit/elasticsearch-net,jonyadamit/elasticsearch-net,jonyadamit/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,elastic/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,elastic/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net
ba0e233f85032e6534ffa6174a632cb7d906a3e7
ModIso8583.Test/Parse/TestEncoding.cs
ModIso8583.Test/Parse/TestEncoding.cs
using System; using System.Text; using ModIso8583.Parse; using ModIso8583.Util; using Xunit; namespace ModIso8583.Test.Parse { public class TestEncoding { [Fact(Skip = "character encoding issue")] public void WindowsToUtf8() { string data = "05ácido"; Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); if (OsUtil.IsLinux()) encoding = Encoding.Default; sbyte[] buf = data.GetSbytes(encoding); LlvarParseInfo parser = new LlvarParseInfo { Encoding = Encoding.Default }; IsoValue field = parser.Parse(1, buf, 0, null); Assert.Equal(field.Value, data.Substring(2)); parser.Encoding = encoding; field = parser.Parse(1, buf, 0, null); Assert.Equal(data.Substring(2), field.Value); } } }
using System; using System.Text; using ModIso8583.Parse; using ModIso8583.Util; using Xunit; namespace ModIso8583.Test.Parse { public class TestEncoding { [Fact] public void WindowsToUtf8() { string data = "05ácido"; Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); if (OsUtil.IsLinux()) encoding = Encoding.UTF8; sbyte[] buf = data.GetSbytes(encoding); LlvarParseInfo parser = new LlvarParseInfo { Encoding = Encoding.Default }; if (OsUtil.IsLinux()) parser.Encoding = Encoding.UTF8; IsoValue field = parser.Parse(1, buf, 0, null); Assert.Equal(field.Value, data.Substring(2)); parser.Encoding = encoding; field = parser.Parse(1, buf, 0, null); Assert.Equal(data.Substring(2), field.Value); } } }
Fix OS based character Encoding issue
Fix OS based character Encoding issue
C#
mit
Tochemey/Iso85834Net
e89d08f5f34eb8cac20a46b4f892bac2c84fd697
src/Repairis.Web.Core/Controllers/RepairisControllerBase.cs
src/Repairis.Web.Core/Controllers/RepairisControllerBase.cs
using Abp.AspNetCore.Mvc.Controllers; using Abp.IdentityFramework; using Microsoft.AspNetCore.Identity; namespace Repairis.Controllers { public abstract class RepairisControllerBase: AbpController { protected RepairisControllerBase() { LocalizationSourceName = RepairisConsts.LocalizationSourceName; } protected void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
using Abp.AspNetCore.Mvc.Controllers; using Abp.IdentityFramework; using Abp.Runtime.Validation; using Microsoft.AspNetCore.Identity; namespace Repairis.Controllers { [DisableValidation] public abstract class RepairisControllerBase: AbpController { protected RepairisControllerBase() { LocalizationSourceName = RepairisConsts.LocalizationSourceName; } protected void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
Disable exception throwing when ModelState is not valid
Disable exception throwing when ModelState is not valid
C#
mit
dmytrokuzmin/RepairisCore,dmytrokuzmin/RepairisCore,dmytrokuzmin/RepairisCore
04750ce524823faa1a0091e0e49c2e1419be2727
Ets.Mobile/Ets.Mobile.WindowsPhone/Pages/Main/MainPage.xaml.cs
Ets.Mobile/Ets.Mobile.WindowsPhone/Pages/Main/MainPage.xaml.cs
using ReactiveUI; using Windows.UI.Xaml; namespace Ets.Mobile.Pages.Main { public sealed partial class MainPage { partial void PartialInitialize() { // Ensure to hide the status bar var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView(); statusBar.BackgroundOpacity = 0; statusBar.HideAsync().GetResults(); // Grade Presenter // NOTE: Do not remove this code, can't bind to the presenter's source this.OneWayBind(ViewModel, x => x.GradesPresenter, x => x.Grade.DataContext); // Handle the button visibility according to Pivot Context (SelectedIndex) Loaded += (s, e) => { MainPivot.SelectionChanged += (sender, e2) => { RefreshToday.Visibility = Visibility.Collapsed; RefreshGrade.Visibility = Visibility.Collapsed; switch (MainPivot.SelectedIndex) { case (int)MainPivotItem.Today: RefreshToday.Visibility = Visibility.Visible; break; case (int)MainPivotItem.Grade: RefreshGrade.Visibility = Visibility.Visible; break; } }; }; } } }
using System; using Windows.UI.Xaml; using EventsMixin = Windows.UI.Xaml.Controls.EventsMixin; namespace Ets.Mobile.Pages.Main { public sealed partial class MainPage { partial void PartialInitialize() { // Ensure to hide the status bar var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView(); statusBar.BackgroundOpacity = 0; statusBar.HideAsync().GetResults(); // Handle the button visibility according to Pivot Context (SelectedIndex) this.Events().Loaded.Subscribe(e => { EventsMixin.Events(MainPivot).SelectionChanged.Subscribe(e2 => { RefreshToday.Visibility = Visibility.Collapsed; RefreshGrade.Visibility = Visibility.Collapsed; switch (MainPivot.SelectedIndex) { case (int)MainPivotItem.Today: RefreshToday.Visibility = Visibility.Visible; break; case (int)MainPivotItem.Grade: RefreshGrade.Visibility = Visibility.Visible; break; } }); }); } } }
Use ReactiveUI Events for Loaded and SelectionChanged
Use ReactiveUI Events for Loaded and SelectionChanged
C#
apache-2.0
ApplETS/ETSMobile-WindowsPlatforms,ApplETS/ETSMobile-WindowsPlatforms
9abd73e0350bb472351f23fbe7831da8000d4d37
CORS/Controllers/ValuesController.cs
CORS/Controllers/ValuesController.cs
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do return new string[] { "This is a CORS request.", "That works from any origin." }; } } }
Add GetTititleEstimate that accepts data from URI.
Add GetTititleEstimate that accepts data from URI.
C#
mit
bigfont/webapi-cors
ba98e0a15a7b44b1fc4911f4cf6b36409d655244
Torch/Patches/SessionDownloadPatch.cs
Torch/Patches/SessionDownloadPatch.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Sandbox.Game.World; using Torch.Managers.PatchManager; using Torch.Mod; using VRage.Game; namespace Torch.Patches { [PatchShim] internal class SessionDownloadPatch { internal static void Patch(PatchContext context) { context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic)); } // ReSharper disable once InconsistentNaming private static void SuffixGetWorld(ref MyObjectBuilder_World __result) { if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID)) __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Sandbox.Game.World; using Torch.Managers.PatchManager; using Torch.Mod; using VRage.Game; namespace Torch.Patches { [PatchShim] internal static class SessionDownloadPatch { internal static void Patch(PatchContext context) { context.GetPattern(typeof(MySession).GetMethod(nameof(MySession.GetWorld))).Suffixes.Add(typeof(SessionDownloadPatch).GetMethod(nameof(SuffixGetWorld), BindingFlags.Static | BindingFlags.NonPublic)); } // ReSharper disable once InconsistentNaming private static void SuffixGetWorld(ref MyObjectBuilder_World __result) { if (!__result.Checkpoint.Mods.Any(m => m.PublishedFileId == TorchModCore.MOD_ID)) __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID)); } } }
Stop Equinox complaining about session download patch not being static
Stop Equinox complaining about session download patch not being static
C#
apache-2.0
TorchAPI/Torch
522f7379e4ae244b27636657cbb020755013227f
Colore.Tests/ColoreExceptionTests.cs
Colore.Tests/ColoreExceptionTests.cs
namespace Colore.Tests { using System; using NUnit.Framework; [TestFixture] public class ColoreExceptionTests { [Test] public void ShouldSetMessage() { const string Expected = "Test message."; Assert.AreEqual(Expected, new ColoreException("Test message.")); } [Test] public void ShouldSetInnerException() { var expected = new Exception("Expected."); var actual = new ColoreException(null, new Exception("Expected.")).InnerException; Assert.AreEqual(expected.GetType(), actual.GetType()); Assert.AreEqual(expected.Message, actual.Message); } } }
namespace Colore.Tests { using System; using NUnit.Framework; [TestFixture] public class ColoreExceptionTests { [Test] public void ShouldSetMessage() { const string Expected = "Test message."; Assert.AreEqual(Expected, new ColoreException("Test message.").Message); } [Test] public void ShouldSetInnerException() { var expected = new Exception("Expected."); var actual = new ColoreException(null, new Exception("Expected.")).InnerException; Assert.AreEqual(expected.GetType(), actual.GetType()); Assert.AreEqual(expected.Message, actual.Message); } } }
Fix ColoreException test performing wrong comparison.
Fix ColoreException test performing wrong comparison.
C#
mit
danpierce1/Colore,CoraleStudios/Colore,Sharparam/Colore,WolfspiritM/Colore
d639d329789153a4b9e20890efcdf2f55276129f
Battery-Commander.Web/Views/Soldiers/List.cshtml
Battery-Commander.Web/Views/Soldiers/List.cshtml
@model IEnumerable<Soldier> <h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th> <th></th> </tr> </thead> <tbody> @foreach (var soldier in Model) { <tr> <td>@Html.DisplayFor(s => soldier.Rank)</td> <td>@Html.DisplayFor(s => soldier.LastName)</td> <td>@Html.DisplayFor(s => soldier.FirstName)</td> <td>@Html.DisplayFor(s => soldier.Unit)</td> <td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td> <td> @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }) @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }) </td> </tr> } </tbody> </table>
@model IEnumerable<Soldier> <h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th> <th></th> </tr> </thead> <tbody> @foreach (var soldier in Model) { <tr> <td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td> <td>@Html.DisplayFor(s => soldier.Rank)</td> <td>@Html.DisplayFor(s => soldier.LastName)</td> <td>@Html.DisplayFor(s => soldier.FirstName)</td> <td>@Html.DisplayFor(s => soldier.Unit)</td> <td> @Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) @Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" }) </td> </tr> } </tbody> </table>
Move details to first in list
Move details to first in list
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
01911993b4dd7140f8a4766365e5daebd0d13ee6
Faker/NumberFaker.cs
Faker/NumberFaker.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Faker { public static class NumberFaker { private static Random _random = new Random(); public static int Number() { return _random.Next(); } public static int Number(int maxValue) { return _random.Next(maxValue); } public static int Number(int minValue, int maxValue) { return _random.Next(minValue, maxValue); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Faker { public static class NumberFaker { private static readonly RNGCryptoServiceProvider Global = new RNGCryptoServiceProvider(); [ThreadStatic] private static Random _local; private static Random Local { get { Random inst = _local; if (inst == null) { byte[] buffer = new byte[4]; Global.GetBytes(buffer); _local = inst = new Random( BitConverter.ToInt32(buffer, 0)); } return inst; } } public static int Number() { return Local.Next(); } public static int Number(int maxValue) { return Local.Next(maxValue); } public static int Number(int minValue, int maxValue) { return Local.Next(minValue, maxValue); } } }
Add thread-safe random number instance
Add thread-safe random number instance
C#
apache-2.0
benjaminramey/Faker
2caa7b50735595fb114dac5222aad04486df1b54
MitternachtWeb/Areas/User/Views/Verifications/Index.cshtml
MitternachtWeb/Areas/User/Views/Verifications/Index.cshtml
@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)> <h4>Verifizierungen</h4> <div class="table-responsive"> <table class="table"> <thead> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.UserInfo.Username) </th> <th> @Html.DisplayNameFor(model => model.Guild.Name) </th> </tr> </thead> <tbody> @foreach(var (userInfo, guild) in Model) { <tr> <td> @if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) { <img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" /> } </td> <td> <a href="@userInfo.UrlPath">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.UrlPath : userInfo.Username)</a> </td> <td> <a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a> </td> </tr> } </tbody> </table> </div>
@model IEnumerable<(GommeHDnetForumAPI.Models.Entities.UserInfo UserInfo, Discord.WebSocket.SocketGuild Guild)> <h4>Verifizierungen</h4> <div class="table-responsive"> <table class="table"> <thead> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.UserInfo.Username) </th> <th> @Html.DisplayNameFor(model => model.Guild.Name) </th> </tr> </thead> <tbody> @foreach(var (userInfo, guild) in Model) { <tr> <td> @if(!string.IsNullOrWhiteSpace(userInfo.AvatarUrl)) { <img class="gommehdnet-forum-avatar" src="@userInfo.AvatarUrl" alt="Avatar" /> } </td> <td> <a href="@userInfo.Url">@(string.IsNullOrWhiteSpace(userInfo.Username) ? userInfo.Url : userInfo.Username)</a> </td> <td> <a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a> </td> </tr> } </tbody> </table> </div>
Use Url instead of UrlPath.
Use Url instead of UrlPath.
C#
mit
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
25964c541b8753c55b6b6e3329d1aff25e469f12
EventSourcingCQRS/Application/Interfaces/IInventoryService.cs
EventSourcingCQRS/Application/Interfaces/IInventoryService.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using DomainCore; using DomainCore.Interfaces; namespace Application.Interfaces { /// <summary> /// Primary application interface /// </summary> public interface IInventoryService { /* ReadModel */ // Get all Task<IEnumerable<InventoryItemDto>> InventoryAsync(); // Get one Task<InventoryItemDto> GetItemAsync(Guid id); Task<IEnumerable<AInventoryItemEvent>> InventoryEventsAsync(Guid id); /* Commands */ // Create Item Task PostItemAsync(InventoryItemDto item); // Update Full Item Task PutItemAsync(InventoryItemDto item); // Delete Item Task DeleteItemAsync(Guid id); // Edit Item Task PatchItemCountAsync(Guid id, int count, string reason); Task PatchItemNameAsync(Guid id, string name, string reason); Task PatchItemNoteAsync(Guid id, string note, string reason); // Increase Item count Task IncreaseInventory(Guid id, uint amount, string reason); // Decrease Item count Task DecreaseInventory(Guid id, uint amount, string reason); // Activate Item Task ActivateItem(Guid id, string reason); // Deactivate Item Task DisableItem(Guid id, string reason); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using DomainCore; namespace Application.Interfaces { public interface IInventoryService { /* ReadModel */ // Get all Task<IEnumerable<InventoryItemDto>> InventoryAsync(); // Get one Task<InventoryItemDto> GetItemAsync(Guid id); Task<IEnumerable<InventoryItemEvent>> InventoryEventsAsync(Guid id); /* Commands */ // Create Item Task PostItemAsync(InventoryItemDto item); // Update Full Item Task PutItemAsync(InventoryItemDto item); // Delete Item Task DeleteItemAsync(Guid id); // Edit Item Task PatchItemCountAsync(Guid id, int count, string reason); Task PatchItemNameAsync(Guid id, string name, string reason); Task PatchItemNoteAsync(Guid id, string note, string reason); // Increase Item count Task IncreaseInventory(Guid id, uint amount, string reason); // Decrease Item count Task DecreaseInventory(Guid id, uint amount, string reason); // Activate Item Task ActivateItem(Guid id, string reason); // Deactivate Item Task DisableItem(Guid id, string reason); } }
Revert "Changed generic object to a system object"
Revert "Changed generic object to a system object" This reverts commit 8338aa76f30a6e3898d79110494c66b167661eda.
C#
mit
tedbouskill/m-r-core-of,tedbouskill/m-r-core-of
5e06eef844a5e4c3687e5794780eebd7e0a63b7c
Source/Lib/TraktApiSharp/Objects/Get/Movies/TraktMovieImages.cs
Source/Lib/TraktApiSharp/Objects/Get/Movies/TraktMovieImages.cs
namespace TraktApiSharp.Objects.Get.Movies { using Basic; using Newtonsoft.Json; public class TraktMovieImages { [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
namespace TraktApiSharp.Objects.Get.Movies { using Basic; using Newtonsoft.Json; /// <summary>A collection of images and image sets for a Trakt movie.</summary> public class TraktMovieImages { /// <summary>Gets or sets the fan art image set.</summary> [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } /// <summary>Gets or sets the poster image set.</summary> [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } /// <summary>Gets or sets the loge image.</summary> [JsonProperty(PropertyName = "logo")] public TraktImage Logo { get; set; } /// <summary>Gets or sets the clear art image.</summary> [JsonProperty(PropertyName = "clearart")] public TraktImage ClearArt { get; set; } /// <summary>Gets or sets the banner image.</summary> [JsonProperty(PropertyName = "banner")] public TraktImage Banner { get; set; } /// <summary>Gets or sets the thumb image.</summary> [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
Add documentation for movie images.
Add documentation for movie images.
C#
mit
henrikfroehling/TraktApiSharp
ad25f6f78780d54c5bf6dc1abfb1a592181fe45b
WalletWasabi.Tests/UnitTests/SerializableExceptionTests.cs
WalletWasabi.Tests/UnitTests/SerializableExceptionTests.cs
using System; using System.Collections.Generic; using System.Text; using WalletWasabi.Models; using Xunit; namespace WalletWasabi.Tests.UnitTests { public class SerializableExceptionTests { [Fact] public void UtxoRefereeSerialization() { var message = "Foo Bar Buzz"; var innerMessage = "Inner Foo Bar Buzz"; string innerStackTrace = ""; Exception ex; string stackTrace; try { try { throw new OperationCanceledException(innerMessage); } catch (Exception inner) { innerStackTrace = inner.StackTrace; throw new InvalidOperationException(message, inner); } } catch (Exception x) { stackTrace = x.StackTrace; ex = x; } var serializableException = ex.ToSerializableException(); var base64string = SerializableException.ToBase64String(serializableException); var result = SerializableException.FromBase64String(base64string); Assert.Equal(message, result.Message); Assert.Equal(stackTrace, result.StackTrace); Assert.Equal(typeof(InvalidOperationException).FullName, result.ExceptionType); Assert.Equal(innerMessage, result.InnerException.Message); Assert.Equal(innerStackTrace, result.InnerException.StackTrace); Assert.Equal(typeof(OperationCanceledException).FullName, result.InnerException.ExceptionType); } } }
using System; using System.Collections.Generic; using System.Text; using WalletWasabi.Models; using Xunit; namespace WalletWasabi.Tests.UnitTests { public class SerializableExceptionTests { [Fact] public void UtxoRefereeSerialization() { var message = "Foo Bar Buzz"; var innerMessage = "Inner Foo Bar Buzz"; var innerStackTrace = ""; Exception ex; string stackTrace; try { try { throw new OperationCanceledException(innerMessage); } catch (Exception inner) { innerStackTrace = inner.StackTrace; throw new InvalidOperationException(message, inner); } } catch (Exception x) { stackTrace = x.StackTrace; ex = x; } var serializableException = ex.ToSerializableException(); var base64string = SerializableException.ToBase64String(serializableException); var result = SerializableException.FromBase64String(base64string); Assert.Equal(message, result.Message); Assert.Equal(stackTrace, result.StackTrace); Assert.Equal(typeof(InvalidOperationException).FullName, result.ExceptionType); Assert.Equal(innerMessage, result.InnerException.Message); Assert.Equal(innerStackTrace, result.InnerException.StackTrace); Assert.Equal(typeof(OperationCanceledException).FullName, result.InnerException.ExceptionType); } } }
Use var instead of string
Use var instead of string
C#
mit
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
566cdec77a981985a7d03dbb6a67a6f36b76ae0b
Kudu.Core/Deployment/DeploymentManager.cs
Kudu.Core/Deployment/DeploymentManager.cs
using System; using System.Collections.Generic; using System.Linq; using Kudu.Core.SourceControl; namespace Kudu.Core.Deployment { public class DeploymentManager : IDeploymentManager { private readonly IRepository _repository; private readonly IDeployerFactory _deployerFactory; public DeploymentManager(IRepositoryManager repositoryManager, IDeployerFactory deployerFactory) { _repository = repositoryManager.GetRepository(); _deployerFactory = deployerFactory; } public IEnumerable<DeployResult> GetResults() { throw new NotImplementedException(); } public DeployResult GetResult(string id) { throw new NotImplementedException(); } public void Deploy(string id) { IDeployer deployer = _deployerFactory.CreateDeployer(); deployer.Deploy(id); } public void Deploy() { var activeBranch = _repository.GetBranches().FirstOrDefault(b => b.Active); string id = _repository.CurrentId; if (activeBranch != null) { _repository.Update(activeBranch.Name); } else { _repository.Update(id); } Deploy(id); } } }
using System; using System.Collections.Generic; using System.Linq; using Kudu.Core.SourceControl; namespace Kudu.Core.Deployment { public class DeploymentManager : IDeploymentManager { private readonly IRepositoryManager _repositoryManager; private readonly IDeployerFactory _deployerFactory; public DeploymentManager(IRepositoryManager repositoryManager, IDeployerFactory deployerFactory) { _repositoryManager = repositoryManager; _deployerFactory = deployerFactory; } public IEnumerable<DeployResult> GetResults() { throw new NotImplementedException(); } public DeployResult GetResult(string id) { throw new NotImplementedException(); } public void Deploy(string id) { IDeployer deployer = _deployerFactory.CreateDeployer(); deployer.Deploy(id); } public void Deploy() { var repository = _repositoryManager.GetRepository(); if (repository == null) { return; } var activeBranch = repository.GetBranches().FirstOrDefault(b => b.Active); string id = repository.CurrentId; if (activeBranch != null) { repository.Update(activeBranch.Name); } else { repository.Update(id); } Deploy(id); } } }
Create the repository only when it's needed for deployment.
Create the repository only when it's needed for deployment.
C#
apache-2.0
juoni/kudu,juoni/kudu,MavenRain/kudu,projectkudu/kudu,bbauya/kudu,duncansmart/kudu,kali786516/kudu,puneet-gupta/kudu,YOTOV-LIMITED/kudu,shrimpy/kudu,MavenRain/kudu,WeAreMammoth/kudu-obsolete,projectkudu/kudu,duncansmart/kudu,EricSten-MSFT/kudu,juoni/kudu,shibayan/kudu,shibayan/kudu,WeAreMammoth/kudu-obsolete,puneet-gupta/kudu,barnyp/kudu,chrisrpatterson/kudu,juoni/kudu,sitereactor/kudu,oliver-feng/kudu,badescuga/kudu,shanselman/kudu,kenegozi/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,MavenRain/kudu,projectkudu/kudu,mauricionr/kudu,shanselman/kudu,oliver-feng/kudu,shibayan/kudu,dev-enthusiast/kudu,badescuga/kudu,juvchan/kudu,barnyp/kudu,EricSten-MSFT/kudu,chrisrpatterson/kudu,sitereactor/kudu,bbauya/kudu,kali786516/kudu,juvchan/kudu,uQr/kudu,projectkudu/kudu,barnyp/kudu,shibayan/kudu,duncansmart/kudu,dev-enthusiast/kudu,kali786516/kudu,dev-enthusiast/kudu,badescuga/kudu,sitereactor/kudu,mauricionr/kudu,uQr/kudu,kenegozi/kudu,shrimpy/kudu,mauricionr/kudu,oliver-feng/kudu,chrisrpatterson/kudu,puneet-gupta/kudu,shanselman/kudu,shibayan/kudu,uQr/kudu,YOTOV-LIMITED/kudu,badescuga/kudu,shrimpy/kudu,MavenRain/kudu,dev-enthusiast/kudu,EricSten-MSFT/kudu,kenegozi/kudu,juvchan/kudu,badescuga/kudu,duncansmart/kudu,puneet-gupta/kudu,sitereactor/kudu,juvchan/kudu,EricSten-MSFT/kudu,sitereactor/kudu,YOTOV-LIMITED/kudu,kali786516/kudu,chrisrpatterson/kudu,bbauya/kudu,YOTOV-LIMITED/kudu,shrimpy/kudu,WeAreMammoth/kudu-obsolete,oliver-feng/kudu,uQr/kudu,kenegozi/kudu,projectkudu/kudu,juvchan/kudu,mauricionr/kudu,bbauya/kudu,barnyp/kudu
8757a464068c5a3ac754720e4cdbe6217549d703
src/common/CoCo.UI/ViewModels/OptionViewModel.cs
src/common/CoCo.UI/ViewModels/OptionViewModel.cs
using System.Collections.ObjectModel; using CoCo.UI.Data; namespace CoCo.UI.ViewModels { public class OptionViewModel : BaseViewModel { public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider) { // TODO: it will invoke one event at invocation of clear and by one event per added item // Write custom BulkObservableCollection to avoid so many events Languages.Clear(); foreach (var language in option.Languages) { Languages.Add(new LanguageViewModel(language, resetValuesProvider)); } } public ObservableCollection<LanguageViewModel> Languages { get; } = new ObservableCollection<LanguageViewModel>(); private LanguageViewModel _selectedLanguage; public LanguageViewModel SelectedLanguage { get { if (_selectedLanguage is null && Languages.Count > 0) { SelectedLanguage = Languages[0]; } return _selectedLanguage; } set => SetProperty(ref _selectedLanguage, value); } public Option ExtractData() { var option = new Option(); foreach (var languageViewModel in Languages) { option.Languages.Add(languageViewModel.ExtractData()); } return option; } } }
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Data; using CoCo.UI.Data; namespace CoCo.UI.ViewModels { public class OptionViewModel : BaseViewModel { private readonly ObservableCollection<LanguageViewModel> _languages = new ObservableCollection<LanguageViewModel>(); public OptionViewModel(Option option, IResetValuesProvider resetValuesProvider) { // TODO: it will invoke one event at invocation of clear and by one event per added item // Write custom BulkObservableCollection to avoid so many events _languages.Clear(); foreach (var language in option.Languages) { _languages.Add(new LanguageViewModel(language, resetValuesProvider)); } Languages = CollectionViewSource.GetDefaultView(_languages); Languages.SortDescriptions.Add(new SortDescription(nameof(LanguageViewModel.Name), ListSortDirection.Ascending)); } public ICollectionView Languages { get; } private LanguageViewModel _selectedLanguage; public LanguageViewModel SelectedLanguage { get { if (_selectedLanguage is null && Languages.MoveCurrentToFirst()) { SelectedLanguage = (LanguageViewModel)Languages.CurrentItem; } return _selectedLanguage; } set => SetProperty(ref _selectedLanguage, value); } public Option ExtractData() { var option = new Option(); foreach (var languageViewModel in _languages) { option.Languages.Add(languageViewModel.ExtractData()); } return option; } } }
Sort languages by ascending order.
Sort languages by ascending order.
C#
mit
GeorgeAlexandria/CoCo
53ffb2271c545837de71111eeb39339ae5f34814
osu.Framework.Tests/Visual/Sprites/TestSceneTexturedTriangle.cs
osu.Framework.Tests/Visual/Sprites/TestSceneTexturedTriangle.cs
using osu.Framework.Allocation; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using System; using System.Collections.Generic; using osuTK; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTexturedTriangle : FrameworkTestScene { public TestSceneTexturedTriangle() { Add(new TexturedTriangle { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300, 150) }); } private class TexturedTriangle : Triangle { [BackgroundDependencyLoader] private void load(TextureStore textures) { Texture = textures.Get(@"sample-texture"); } } } }
// 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.Shapes; using osu.Framework.Graphics; using osu.Framework.Graphics.Textures; using osuTK; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTexturedTriangle : FrameworkTestScene { public TestSceneTexturedTriangle() { Add(new TexturedTriangle { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300, 150) }); } private class TexturedTriangle : Triangle { [BackgroundDependencyLoader] private void load(TextureStore textures) { Texture = textures.Get(@"sample-texture"); } } } }
Add the licence header and remove unused usings
Add the licence header and remove unused usings
C#
mit
EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework
8f168efd4e04aed2b3b2333a1070dee8f8607476
res/scripts/appveyor.cake
res/scripts/appveyor.cake
public sealed class AppVeyorSettings { public bool IsLocal { get; set; } public bool IsRunningOnAppVeyor { get; set; } public bool IsPullRequest { get; set; } public bool IsDevelopBranch { get; set; } public bool IsMasterBranch { get; set; } public bool IsTaggedBuild { get; set; } public bool IsMaintenanceBuild { get; set; } public static AppVeyorSettings Initialize(ICakeContext context) { var buildSystem = context.BuildSystem(); var branchName = buildSystem.AppVeyor.Environment.Repository.Branch; var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim(); var isMaintenanceBuild = commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false; return new AppVeyorSettings { IsLocal = buildSystem.IsLocalBuild, IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor, IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest, IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsTaggedBuild = IsBuildTagged(buildSystem), IsMaintenanceBuild = isMaintenanceBuild }; } public static bool IsBuildTagged(BuildSystem buildSystem) { return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); } }
public sealed class AppVeyorSettings { public bool IsLocal { get; set; } public bool IsRunningOnAppVeyor { get; set; } public bool IsPullRequest { get; set; } public bool IsDevelopBranch { get; set; } public bool IsMasterBranch { get; set; } public bool IsTaggedBuild { get; set; } public bool IsMaintenanceBuild { get; set; } public static AppVeyorSettings Initialize(ICakeContext context) { var buildSystem = context.BuildSystem(); var branchName = buildSystem.AppVeyor.Environment.Repository.Branch; var commitMessage = buildSystem.AppVeyor.Environment.Repository.Commit.Message?.Trim(); var isMaintenanceBuild = (commitMessage?.StartsWith("(build)", StringComparison.OrdinalIgnoreCase) ?? false) || (commitMessage?.StartsWith("(docs)", StringComparison.OrdinalIgnoreCase) ?? false); return new AppVeyorSettings { IsLocal = buildSystem.IsLocalBuild, IsRunningOnAppVeyor = buildSystem.AppVeyor.IsRunningOnAppVeyor, IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest, IsDevelopBranch = "develop".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsMasterBranch = "master".Equals(branchName, StringComparison.OrdinalIgnoreCase), IsTaggedBuild = IsBuildTagged(buildSystem), IsMaintenanceBuild = isMaintenanceBuild }; } public static bool IsBuildTagged(BuildSystem buildSystem) { return buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); } }
Allow skipping publish of package when fixing docs.
Allow skipping publish of package when fixing docs.
C#
mit
spectresystems/commandline
f3650f8dd95dca9aff4be8419f866a34bf8b4dbe
BindableApplicationBar/Properties/AssemblyInfo.cs
BindableApplicationBar/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BindableApplicationBar")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Filip Skakun")] [assembly: AssemblyProduct("BindableApplicationBar")] [assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")] [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("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BindableApplicationBar")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Filip Skakun")] [assembly: AssemblyProduct("BindableApplicationBar")] [assembly: AssemblyCopyright("Copyright © Filip Skakun, 2011-2013")] [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("d0df5e03-2f69-4d10-a40d-25afcbbb7e09")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.1")] [assembly: AssemblyFileVersion("1.1.1")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
Increase the version to 1.1.1.
Increase the version to 1.1.1.
C#
mit
Alovel/BindableApplicationBar,Alovel/BindableApplicationBar
5b2c0af105787653214bbbf5d0da31edfa27b979
CoolFish/ReleaseManager/ReleaseManager/Program.cs
CoolFish/ReleaseManager/ReleaseManager/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReleaseManager { class Program { static void Main(string[] args) { try { if (args.Length == 0) { return; } var mainFileName = args[0]; var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion; var archive = ZipFile.Open("Release_" + version + ".zip", ZipArchiveMode.Create); archive.CreateEntryFromFile(mainFileName, mainFileName); for (int i = 1; i < args.Length; i++) { archive.CreateEntryFromFile(args[i], args[i]); } archive.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(1); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReleaseManager { class Program { static void Main(string[] args) { try { if (args.Length == 0) { return; } var mainFileName = args[0]; var version = FileVersionInfo.GetVersionInfo(mainFileName).FileVersion; var archive = ZipFile.Open(version + ".zip", ZipArchiveMode.Create); archive.CreateEntryFromFile(mainFileName, mainFileName); for (int i = 1; i < args.Length; i++) { archive.CreateEntryFromFile(args[i], args[i]); } archive.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(1); } } } }
Change release manager zip file name
Change release manager zip file name
C#
mit
GliderPro/CoolFish,dgladkov/CoolFish
b9d99b5f4049531bcb9c255d78c088652c094b29
osu.Game/Graphics/UserInterface/ScreenBreadcrumbControl.cs
osu.Game/Graphics/UserInterface/ScreenBreadcrumbControl.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<Screen> { private Screen last; public ScreenBreadcrumbControl(Screen initialScreen) { Current.ValueChanged += newScreen => { if (last != newScreen && !newScreen.IsCurrentScreen) newScreen.MakeCurrent(); }; onPushed(initialScreen); } private void screenChanged(Screen newScreen) { if (last != null) { last.Exited -= screenChanged; last.ModePushed -= onPushed; } last = newScreen; newScreen.Exited += screenChanged; newScreen.ModePushed += onPushed; Current.Value = newScreen; } private void onPushed(Screen screen) { Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem); AddItem(screen); screenChanged(screen); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Screens; namespace osu.Game.Graphics.UserInterface { /// <summary> /// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack. /// </summary> public class ScreenBreadcrumbControl : BreadcrumbControl<Screen> { private Screen last; public ScreenBreadcrumbControl(Screen initialScreen) { Current.ValueChanged += newScreen => { if (last != newScreen && !newScreen.IsCurrentScreen) newScreen.MakeCurrent(); }; onPushed(initialScreen); } private void screenChanged(Screen newScreen) { if (newScreen == null) return; if (last != null) { last.Exited -= screenChanged; last.ModePushed -= onPushed; } last = newScreen; newScreen.Exited += screenChanged; newScreen.ModePushed += onPushed; Current.Value = newScreen; } private void onPushed(Screen screen) { Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem); AddItem(screen); screenChanged(screen); } } }
Fix nullref when exiting the last screen.
Fix nullref when exiting the last screen.
C#
mit
peppy/osu,DrabWeb/osu,naoey/osu,ppy/osu,naoey/osu,2yangk23/osu,johnneijzen/osu,naoey/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,smoogipooo/osu,ZLima12/osu,DrabWeb/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu,EVAST9919/osu