commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
da5481919be794d8cd9a738d7a7f176bc7078229
Add namning convention for dead letter exchange
pardahlman/RawRabbit,northspb/RawRabbit
src/RawRabbit/Common/NamingConvetions.cs
src/RawRabbit/Common/NamingConvetions.cs
using System; namespace RawRabbit.Common { public interface INamingConvetions { Func<Type, string> ExchangeNamingConvention { get; set; } Func<Type, string> QueueNamingConvention { get; set; } Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } Func<string> ErrorExchangeNamingConvention { get; set; } Func<string> ErrorQueueNamingConvention { get; set; } Func<string> DeadLetterExchangeNamingConvention { get; set; } } public class NamingConvetions : INamingConvetions { public Func<Type, string> ExchangeNamingConvention { get; set; } public Func<Type, string> QueueNamingConvention { get; set; } public Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } public Func<string> ErrorExchangeNamingConvention { get; set; } public Func<string> ErrorQueueNamingConvention { get; set; } public Func<string> DeadLetterExchangeNamingConvention { get; set; } public NamingConvetions() { ExchangeNamingConvention = type => type?.Namespace?.ToLower(); RpcExchangeNamingConvention = (request, response) => request?.Namespace?.ToLower() ?? "default_rpc_exchange"; QueueNamingConvention = type => CreateShortAfqn(type); ErrorQueueNamingConvention = () => "default_error_queue"; ErrorExchangeNamingConvention = () => "default_error_exchange"; DeadLetterExchangeNamingConvention = () => "default_dead_letter_exchange"; } private static string CreateShortAfqn(Type type, string path = "", string delimeter = ".") { var t = $"{path}{(string.IsNullOrEmpty(path) ? string.Empty : delimeter)}{GetNonGenericTypeName(type)}"; if (type.IsGenericType) { t += "["; foreach (var argument in type.GenericTypeArguments) { t = CreateShortAfqn(argument, t, t.EndsWith("[") ? string.Empty : ","); } t += "]"; } return (t.Length > 254 ? string.Concat("...", t.Substring(t.Length - 250)) : t).ToLowerInvariant(); } public static string GetNonGenericTypeName(Type type) { var name = !type.IsGenericType ? new[] { type.Name } : type.Name.Split('`'); return name[0]; } } }
using System; namespace RawRabbit.Common { public interface INamingConvetions { Func<Type, string> ExchangeNamingConvention { get; set; } Func<Type, string> QueueNamingConvention { get; set; } Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } Func<string> ErrorExchangeNamingConvention { get; set; } Func<string> ErrorQueueNamingConvention { get; set; } } public class NamingConvetions : INamingConvetions { public Func<Type, string> ExchangeNamingConvention { get; set; } public Func<Type, string> QueueNamingConvention { get; set; } public Func<Type, Type, string> RpcExchangeNamingConvention { get; set; } public Func<string> ErrorExchangeNamingConvention { get; set; } public Func<string> ErrorQueueNamingConvention { get; set; } public NamingConvetions() { ExchangeNamingConvention = type => type?.Namespace?.ToLower(); RpcExchangeNamingConvention = (request, response) => request?.Namespace?.ToLower() ?? "default_rpc_exchange"; QueueNamingConvention = type => CreateShortAfqn(type); ErrorQueueNamingConvention = () => "default_error_queue"; ErrorExchangeNamingConvention = () => "default_error_exchange"; } private static string CreateShortAfqn(Type type, string path = "", string delimeter = ".") { var t = $"{path}{(string.IsNullOrEmpty(path) ? string.Empty : delimeter)}{GetNonGenericTypeName(type)}"; if (type.IsGenericType) { t += "["; foreach (var argument in type.GenericTypeArguments) { t = CreateShortAfqn(argument, t, t.EndsWith("[") ? string.Empty : ","); } t += "]"; } return (t.Length > 254 ? string.Concat("...", t.Substring(t.Length - 250)) : t).ToLowerInvariant(); } public static string GetNonGenericTypeName(Type type) { var name = !type.IsGenericType ? new[] { type.Name } : type.Name.Split('`'); return name[0]; } } }
mit
C#
99d847f037462bcd54e293371a4b6fe49b5b475b
Simplify hotkey.
bojanrajkovic/GifWin
src/GifWin/App.xaml.cs
src/GifWin/App.xaml.cs
using System; using System.Windows; using System.Windows.Forms; using System.Linq; using GifWin.Properties; using Application = System.Windows.Application; using System.Windows.Input; namespace GifWin { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnExit (ExitEventArgs e) { Settings.Default.Save(); base.OnExit (e); } protected override void OnStartup (StartupEventArgs e) { base.OnStartup (e); if (this.window == null) { this.window = new MainWindow(); hotkey = new HotKey(ModifierKeys.Windows, Key.G, window); hotkey.HotKeyPressed += HotKeyPressed; } SetupTrayIcon(); } private NotifyIcon tray; private MainWindow window; HotKey hotkey; private void SetupTrayIcon() { var contextMenu = new ContextMenu (new[] { new MenuItem ("Exit"), }); contextMenu.MenuItems[0].Click += (sender, args) => Shutdown(); this.tray = new NotifyIcon { ContextMenu = contextMenu, Visible = true, Icon = GifWin.Properties.Resources.TrayIcon }; this.tray.Click += OnTrayClicked; } private void OnTrayClicked (object sender, EventArgs eventArgs) { this.window.Show(); this.window.Activate(); } private void HotKeyPressed(HotKey obj) { window.Show(); window.Activate(); } } }
using System; using System.Windows; using System.Windows.Forms; using System.Linq; using GifWin.Properties; using Application = System.Windows.Application; using System.Windows.Input; namespace GifWin { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnExit (ExitEventArgs e) { Settings.Default.Save(); base.OnExit (e); } protected override void OnStartup (StartupEventArgs e) { base.OnStartup (e); if (this.window == null) { this.window = new MainWindow(); hotkey = new HotKey(ModifierKeys.Windows | ModifierKeys.Alt, Key.G, window); hotkey.HotKeyPressed += HotKeyPressed; } SetupTrayIcon(); } private NotifyIcon tray; private MainWindow window; HotKey hotkey; private void SetupTrayIcon() { var contextMenu = new ContextMenu (new[] { new MenuItem ("Exit"), }); contextMenu.MenuItems[0].Click += (sender, args) => Shutdown(); this.tray = new NotifyIcon { ContextMenu = contextMenu, Visible = true, Icon = GifWin.Properties.Resources.TrayIcon }; this.tray.Click += OnTrayClicked; } private void OnTrayClicked (object sender, EventArgs eventArgs) { this.window.Show(); this.window.Activate(); } private void HotKeyPressed(HotKey obj) { window.Show(); window.Activate(); } } }
mit
C#
f78d7099332fba3337fde56a2ece9cd074263d40
Fix toggle-subfloor visual bugs (#11239)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Client/SubFloor/SubFloorHideSystem.cs
Content.Client/SubFloor/SubFloorHideSystem.cs
using Content.Shared.SubFloor; using Robust.Client.GameObjects; namespace Content.Client.SubFloor; public sealed class SubFloorHideSystem : SharedSubFloorHideSystem { [Dependency] private readonly AppearanceSystem _appearanceSystem = default!; private bool _showAll; [ViewVariables(VVAccess.ReadWrite)] public bool ShowAll { get => _showAll; set { if (_showAll == value) return; _showAll = value; UpdateAll(); } } public override void Initialize() { base.Initialize(); SubscribeLocalEvent<SubFloorHideComponent, AppearanceChangeEvent>(OnAppearanceChanged); } private void OnAppearanceChanged(EntityUid uid, SubFloorHideComponent component, ref AppearanceChangeEvent args) { if (args.Sprite == null) return; args.Component.TryGetData(SubFloorVisuals.Covered, out bool covered); args.Component.TryGetData(SubFloorVisuals.ScannerRevealed, out bool scannerRevealed); scannerRevealed &= !ShowAll; // no transparency for show-subfloor mode. var revealed = !covered || ShowAll || scannerRevealed; var transparency = scannerRevealed ? component.ScannerTransparency : 1f; // set visibility & color of each layer foreach (var layer in args.Sprite.AllLayers) { // pipe connection visuals are updated AFTER this, and may re-hide some layers layer.Visible = revealed; if (layer.Visible) layer.Color = layer.Color.WithAlpha(transparency); } // Is there some layer that is always visible? var hasVisibleLayer = false; foreach (var layerKey in component.VisibleLayers) { if (!args.Sprite.LayerMapTryGet(layerKey, out var layerIndex)) continue; var layer = args.Sprite[layerIndex]; layer.Visible = true; layer.Color = layer.Color.WithAlpha(1f); hasVisibleLayer = true; } args.Sprite.Visible = hasVisibleLayer || revealed; } private void UpdateAll() { foreach (var (_, appearance) in EntityManager.EntityQuery<SubFloorHideComponent, AppearanceComponent>(true)) { _appearanceSystem.MarkDirty(appearance, true); } } }
using Content.Shared.SubFloor; using Robust.Client.GameObjects; namespace Content.Client.SubFloor; public sealed class SubFloorHideSystem : SharedSubFloorHideSystem { [Dependency] private readonly AppearanceSystem _appearanceSystem = default!; private bool _showAll; [ViewVariables(VVAccess.ReadWrite)] public bool ShowAll { get => _showAll; set { if (_showAll == value) return; _showAll = value; UpdateAll(); } } public override void Initialize() { base.Initialize(); SubscribeLocalEvent<SubFloorHideComponent, AppearanceChangeEvent>(OnAppearanceChanged); } private void OnAppearanceChanged(EntityUid uid, SubFloorHideComponent component, ref AppearanceChangeEvent args) { if (args.Sprite == null) return; args.Component.TryGetData(SubFloorVisuals.Covered, out bool covered); args.Component.TryGetData(SubFloorVisuals.ScannerRevealed, out bool scannerRevealed); scannerRevealed &= !ShowAll; // no transparency for show-subfloor mode. var revealed = !covered || ShowAll || scannerRevealed; var transparency = scannerRevealed ? component.ScannerTransparency : 1f; // set visibility & color of each layer foreach (var layer in args.Sprite.AllLayers) { // pipe connection visuals are updated AFTER this, and may re-hide some layers layer.Visible = revealed; if (layer.Visible) layer.Color = layer.Color.WithAlpha(transparency); } // Is there some layer that is always visible? var hasVisibleLayer = false; foreach (var layerKey in component.VisibleLayers) { if (!args.Sprite.LayerMapTryGet(layerKey, out var layerIndex)) continue; var layer = args.Sprite[layerIndex]; layer.Visible = true; layer.Color = layer.Color.WithAlpha(1f); hasVisibleLayer = true; } args.Sprite.Visible = hasVisibleLayer || revealed; } private void UpdateAll() { foreach (var (_, appearance) in EntityManager.EntityQuery<SubFloorHideComponent, AppearanceComponent>(true)) { _appearanceSystem.MarkDirty(appearance); } } }
mit
C#
966507db5285d5c144e9e24626589d5f5e656bec
Make MutableLinkedListItem public (#97)
beardgame/utilities
src/Collections/MutableLinkedListItem.cs
src/Collections/MutableLinkedListItem.cs
namespace Bearded.Utilities.Collections { /// <summary> /// This type can be used to have a class be both the value as well as the node in a linked list to prevent unneeded allocations. /// Usage: /// MyClass : MutableLinkedListItem&lt;MyClass&gt; /// MutableLinkedList&lt;MyClass&gt; /// Make sure you add this as node and not as item to the linked list to prevent creation of the node wrapper. /// </summary> /// <typeparam name="TMe">The type of the inheriting class.</typeparam> public abstract class MutableLinkedListItem<TMe> : MutableLinkedListNode<TMe> where TMe : MutableLinkedListNode<TMe> { } }
namespace Bearded.Utilities.Collections { /// <summary> /// This type can be used to have a class be both the value as well as the node in a linked list to prevent unneeded allocations. /// Usage: /// MyClass : MutableLinkedListItem&lt;MyClass&gt; /// MutableLinkedList&lt;MyClass&gt; /// Make sure you add this as node and not as item to the linked list to prevent creation of the node wrapper. /// </summary> /// <typeparam name="TMe">The type of the inheriting class.</typeparam> abstract class MutableLinkedListItem<TMe> : MutableLinkedListNode<TMe> where TMe : MutableLinkedListNode<TMe> { } // ReSharper disable once UnusedTypeParameter /// <summary> /// This type can be used to have a class be both the value as well as the node in a linked list, mixed with actual nodes. /// Usage: /// MyClass : MutableLinkedListItem&lt;MyClass, MyInterface&gt; /// MutableLinkedList&lt;MyInterface&gt; /// Make sure you add this as node and not as item to the linked list to prevent creation of the node wrapper. /// </summary> /// <typeparam name="TMe">The type of the inheriting class.</typeparam> /// <typeparam name="TInterface">The type of the lists interface.</typeparam> abstract class MutableLinkedListItem<TMe, TInterface> : MutableLinkedListNode<TInterface> where TInterface : class where TMe : TInterface { } }
mit
C#
84ea2bd23d98a7dc63f962e8844672b91040382b
Fix GetKerning by overriding Equals and GetHashCode
cyotek/Cyotek.Drawing.BitmapFont
src/Cyotek.Drawing.BitmapFont/Kerning.cs
src/Cyotek.Drawing.BitmapFont/Kerning.cs
/* AngelCode bitmap font parsing using C# * http://www.cyotek.com/blog/angelcode-bitmap-font-parsing-using-csharp * * Copyright © 2012-2015 Cyotek Ltd. * * Licensed under the MIT License. See license.txt for the full text. */ namespace Cyotek.Drawing.BitmapFont { /// <summary> /// Represents the font kerning between two characters. /// </summary> public struct Kerning { #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="firstCharacter">The first character.</param> /// <param name="secondCharacter">The second character.</param> /// <param name="amount">How much the x position should be adjusted when drawing the second /// character immediately following the first.</param> public Kerning(char firstCharacter, char secondCharacter, int amount) : this() { this.FirstCharacter = firstCharacter; this.SecondCharacter = secondCharacter; this.Amount = amount; } #endregion #region Properties /// <summary> /// Gets or sets how much the x position should be adjusted when drawing the second character immediately following the first. /// </summary> /// <value> /// How much the x position should be adjusted when drawing the second character immediately following the first. /// </value> public int Amount { get; set; } /// <summary> /// Gets or sets the first character. /// </summary> /// <value> /// The first character. /// </value> public char FirstCharacter { get; set; } /// <summary> /// Gets or sets the second character. /// </summary> /// <value> /// The second character. /// </value> public char SecondCharacter { get; set; } #endregion #region Methods /// <summary> /// Returns the fully qualified type name of this instance. /// </summary> /// <returns> /// A <see cref="T:System.String" /> containing a fully qualified type name. /// </returns> /// <seealso cref="M:System.ValueType.ToString()"/> public override string ToString() { return string.Format("{0} to {1} = {2}", this.FirstCharacter, this.SecondCharacter, this.Amount); } /// <summary> /// Check if the object represents kerning between the same two characters. /// </summary> /// <param name="obj"></param> /// <returns> /// Whether or not the object represents kerning between the same two characters. /// </returns> public override bool Equals(object obj) { if (obj == null) return false; if (obj.GetType() != typeof(Kerning)) return false; Kerning k = (Kerning)obj; return FirstCharacter == k.FirstCharacter && SecondCharacter == k.SecondCharacter; } /// <summary> /// Return the hash code of the kerning between the two characters. /// </summary> /// <returns> /// A unique hash code of the kerning between the two characters. /// </returns> public override int GetHashCode() { unchecked { return (FirstCharacter << 16) | SecondCharacter; } } #endregion } }
/* AngelCode bitmap font parsing using C# * http://www.cyotek.com/blog/angelcode-bitmap-font-parsing-using-csharp * * Copyright © 2012-2015 Cyotek Ltd. * * Licensed under the MIT License. See license.txt for the full text. */ namespace Cyotek.Drawing.BitmapFont { /// <summary> /// Represents the font kerning between two characters. /// </summary> public struct Kerning { #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="firstCharacter">The first character.</param> /// <param name="secondCharacter">The second character.</param> /// <param name="amount">How much the x position should be adjusted when drawing the second /// character immediately following the first.</param> public Kerning(char firstCharacter, char secondCharacter, int amount) : this() { this.FirstCharacter = firstCharacter; this.SecondCharacter = secondCharacter; this.Amount = amount; } #endregion #region Properties /// <summary> /// Gets or sets how much the x position should be adjusted when drawing the second character immediately following the first. /// </summary> /// <value> /// How much the x position should be adjusted when drawing the second character immediately following the first. /// </value> public int Amount { get; set; } /// <summary> /// Gets or sets the first character. /// </summary> /// <value> /// The first character. /// </value> public char FirstCharacter { get; set; } /// <summary> /// Gets or sets the second character. /// </summary> /// <value> /// The second character. /// </value> public char SecondCharacter { get; set; } #endregion #region Methods /// <summary> /// Returns the fully qualified type name of this instance. /// </summary> /// <returns> /// A <see cref="T:System.String" /> containing a fully qualified type name. /// </returns> /// <seealso cref="M:System.ValueType.ToString()"/> public override string ToString() { return string.Format("{0} to {1} = {2}", this.FirstCharacter, this.SecondCharacter, this.Amount); } #endregion } }
mit
C#
cab1685971614020d0d31faf85536ba8a98a6513
Move some handy methods to `MenuBase` for sharing across menus
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.VisualStudio/Base/MenuBase.cs
src/GitHub.VisualStudio/Base/MenuBase.cs
using System; using System.Globalization; using System.Linq; using GitHub.Extensions; using GitHub.Models; using GitHub.Primitives; using GitHub.Services; using GitHub.UI; using System.Diagnostics; namespace GitHub.VisualStudio { public abstract class MenuBase { readonly IServiceProvider serviceProvider; protected IServiceProvider ServiceProvider { get { return serviceProvider; } } protected MenuBase() { } protected MenuBase(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } protected ISimpleRepositoryModel GetActiveRepo() { var activeRepo = ServiceProvider.GetExportedValue<ITeamExplorerServiceHolder>()?.ActiveRepo; // activeRepo can be null at this point because it is set elsewhere as the result of async operation that may not have completed yet. if (activeRepo == null) { var path = ServiceProvider.GetExportedValue<IVSServices>()?.GetActiveRepoPath() ?? String.Empty; try { activeRepo = !string.IsNullOrEmpty(path) ? new SimpleRepositoryModel(path) : null; } catch (Exception ex) { VsOutputLogger.WriteLine(string.Format(CultureInfo.CurrentCulture, "Error loading the repository from '{0}'. {1}", path, ex)); } } return activeRepo; } protected void StartFlow(UIControllerFlow controllerFlow) { var uiProvider = ServiceProvider.GetExportedValue<IUIProvider>(); Debug.Assert(uiProvider != null, "MenuBase:StartFlow:No UIProvider available."); if (uiProvider == null) return; IConnection connection = null; if (controllerFlow != UIControllerFlow.Authentication) { var activeRepo = GetActiveRepo(); connection = ServiceProvider.GetExportedValue<IConnectionManager>()?.Connections .FirstOrDefault(c => activeRepo?.CloneUrl?.RepositoryName != null && c.HostAddress.Equals(HostAddress.Create(activeRepo.CloneUrl))); } uiProvider.RunUI(controllerFlow, connection); } } }
using System; namespace GitHub.VisualStudio { public abstract class MenuBase { readonly IServiceProvider serviceProvider; protected IServiceProvider ServiceProvider { get { return serviceProvider; } } protected MenuBase() { } protected MenuBase(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } } }
mit
C#
65dd436da6874baa3704d65d830b397ab5fdee20
Bump build script to nuget 2.14
foxbot/Discord.Addons.Paginator,foxbot/Discord.Addons.Paginator,SubZero0/Discord.Addons.Paginator,SubZero0/Discord.Addons.Paginator
build.cake
build.cake
#addin nuget:?package=NuGet.Core&version=2.14.0 #addin "Cake.ExtendedNuGet" var MyGetKey = EnvironmentVariable("MYGET_KEY"); string BuildNumber = EnvironmentVariable("TRAVIS_BUILD_NUMBER"); string Branch = EnvironmentVariable("TRAVIS_BRANCH"); ReleaseNotes Notes = null; Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new[] { "https://www.myget.org/F/discord-net/api/v2", "https://www.nuget.org/api/v2" } }; DotNetCoreRestore(settings); }); Task("ReleaseNotes") .Does(() => { Notes = ParseReleaseNotes("./ReleaseNotes.md"); Information("Release Version: {0}", Notes.Version); }); Task("Build") .IsDependentOn("ReleaseNotes") .Does(() => { var suffix = BuildNumber != null ? BuildNumber.PadLeft(5,'0') : ""; var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "./artifacts/", EnvironmentVariables = new Dictionary<string, string> { { "BuildVersion", Notes.Version.ToString() }, { "BuildNumber", suffix }, { "ReleaseNotes", string.Join("\n", Notes.Notes) }, }, }; DotNetCorePack("./src/Discord.Addons.Paginator/", settings); DotNetCoreBuild("./src/Example/"); }); Task("Deploy") .WithCriteria(Branch == "master") .Does(() => { var settings = new NuGetPushSettings { Source = "https://www.myget.org/F/discord-net/api/v2/package", ApiKey = MyGetKey }; var packages = GetFiles("./artifacts/*.nupkg"); NuGetPush(packages, settings); }); Task("Default") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Deploy") .Does(() => { Information("Build Succeeded"); }); RunTarget("Default");
#addin nuget:?package=NuGet.Core&version=2.12.0 #addin "Cake.ExtendedNuGet" var MyGetKey = EnvironmentVariable("MYGET_KEY"); string BuildNumber = EnvironmentVariable("TRAVIS_BUILD_NUMBER"); string Branch = EnvironmentVariable("TRAVIS_BRANCH"); ReleaseNotes Notes = null; Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new[] { "https://www.myget.org/F/discord-net/api/v2", "https://www.nuget.org/api/v2" } }; DotNetCoreRestore(settings); }); Task("ReleaseNotes") .Does(() => { Notes = ParseReleaseNotes("./ReleaseNotes.md"); Information("Release Version: {0}", Notes.Version); }); Task("Build") .IsDependentOn("ReleaseNotes") .Does(() => { var suffix = BuildNumber != null ? BuildNumber.PadLeft(5,'0') : ""; var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "./artifacts/", EnvironmentVariables = new Dictionary<string, string> { { "BuildVersion", Notes.Version.ToString() }, { "BuildNumber", suffix }, { "ReleaseNotes", string.Join("\n", Notes.Notes) }, }, }; DotNetCorePack("./src/Discord.Addons.Paginator/", settings); DotNetCoreBuild("./src/Example/"); }); Task("Deploy") .WithCriteria(Branch == "master") .Does(() => { var settings = new NuGetPushSettings { Source = "https://www.myget.org/F/discord-net/api/v2/package", ApiKey = MyGetKey }; var packages = GetFiles("./artifacts/*.nupkg"); NuGetPush(packages, settings); }); Task("Default") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Deploy") .Does(() => { Information("Build Succeeded"); }); RunTarget("Default");
isc
C#
64d310a7a661c4e4c3c373babe39245903e8861e
remove ILRepack reference
SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore,damianh/Cedar.EventStore
build.cake
build.cake
#tool "nuget:?package=xunit.runner.console&version=2.1.0" #addin "Cake.FileHelpers" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var artifactsDir = Directory("./artifacts"); var solution = "./src/SqlStreamStore.sln"; var buildNumber = string.IsNullOrWhiteSpace(EnvironmentVariable("BUILD_NUMBER")) ? "0" : EnvironmentVariable("BUILD_NUMBER"); Task("Clean") .Does(() => { CleanDirectory(artifactsDir); }); Task("RestorePackages") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore(solution); NuGetRestore(solution); }); Task("Build") .IsDependentOn("RestorePackages") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; DotNetCoreBuild(solution, settings); }); Task("RunTests") .IsDependentOn("Build") .Does(() => { var testProjects = new string[] { "SqlStreamStore.Tests", "SqlStreamStore.MsSql.Tests" }; foreach(var testProject in testProjects) { var projectDir = "./src/"+ testProject + "/"; var settings = new ProcessSettings { Arguments = "xunit", WorkingDirectory = projectDir }; StartProcess("dotnet", settings); } }); Task("NuGetPack") .IsDependentOn("Build") .Does(() => { var versionSuffix = "build" + buildNumber.ToString().PadLeft(5, '0'); var dotNetCorePackSettings = new DotNetCorePackSettings { ArgumentCustomization = args => args.Append("/p:Version=1.0.0-" + versionSuffix), OutputDirectory = artifactsDir, NoBuild = true, Configuration = configuration, VersionSuffix = versionSuffix }; DotNetCorePack("./src/SqlStreamStore", dotNetCorePackSettings); DotNetCorePack("./src/SqlStreamStore.MsSql", dotNetCorePackSettings); }); Task("Default") .IsDependentOn("RunTests") .IsDependentOn("NuGetPack"); RunTarget(target);
#tool "nuget:?package=xunit.runner.console&version=2.1.0" #tool "nuget:?package=ILRepack&Version=2.0.12" #addin "Cake.FileHelpers" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var artifactsDir = Directory("./artifacts"); var solution = "./src/SqlStreamStore.sln"; var buildNumber = string.IsNullOrWhiteSpace(EnvironmentVariable("BUILD_NUMBER")) ? "0" : EnvironmentVariable("BUILD_NUMBER"); Task("Clean") .Does(() => { CleanDirectory(artifactsDir); }); Task("RestorePackages") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore(solution); NuGetRestore(solution); }); Task("Build") .IsDependentOn("RestorePackages") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; DotNetCoreBuild(solution, settings); }); Task("RunTests") .IsDependentOn("Build") .Does(() => { var testProjects = new string[] { "SqlStreamStore.Tests", "SqlStreamStore.MsSql.Tests" }; foreach(var testProject in testProjects) { var projectDir = "./src/"+ testProject + "/"; var settings = new ProcessSettings { Arguments = "xunit", WorkingDirectory = projectDir }; StartProcess("dotnet", settings); } }); Task("NuGetPack") .IsDependentOn("Build") .Does(() => { var versionSuffix = "build" + buildNumber.ToString().PadLeft(5, '0'); var dotNetCorePackSettings = new DotNetCorePackSettings { ArgumentCustomization = args => args.Append("/p:Version=1.0.0-" + versionSuffix), OutputDirectory = artifactsDir, NoBuild = true, Configuration = configuration, VersionSuffix = versionSuffix }; DotNetCorePack("./src/SqlStreamStore", dotNetCorePackSettings); DotNetCorePack("./src/SqlStreamStore.MsSql", dotNetCorePackSettings); }); Task("Default") .IsDependentOn("RunTests") .IsDependentOn("NuGetPack"); RunTarget(target);
mit
C#
d7ac94038a1d01e5240e0340cf15bb6890f8a6a1
Update `GetBeatmapRequest` to use `AddParameter`
NeoAdonis/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,smoogipoo/osu
osu.Game/Online/API/Requests/GetBeatmapRequest.cs
osu.Game/Online/API/Requests/GetBeatmapRequest.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.IO.Network; using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; #nullable enable namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly IBeatmapInfo beatmapInfo; private readonly string filename; public GetBeatmapRequest(IBeatmapInfo beatmapInfo) { this.beatmapInfo = beatmapInfo; filename = (beatmapInfo as BeatmapInfo)?.Path ?? string.Empty; } protected override WebRequest CreateWebRequest() { var request = base.CreateWebRequest(); request.AddParameter(@"id", beatmapInfo.OnlineID.ToString()); request.AddParameter(@"checksum", beatmapInfo.MD5Hash); request.AddParameter(@"filename", filename); return request; } protected override string Target => @"beatmaps/lookup"; } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; #nullable enable namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly IBeatmapInfo beatmapInfo; private readonly string filename; public GetBeatmapRequest(IBeatmapInfo beatmapInfo) { this.beatmapInfo = beatmapInfo; filename = (beatmapInfo as BeatmapInfo)?.Path ?? string.Empty; } protected override string Target => $@"beatmaps/lookup?id={beatmapInfo.OnlineID}&checksum={beatmapInfo.MD5Hash}&filename={System.Uri.EscapeUriString(filename)}"; } }
mit
C#
f084ec1e304541905526bf851e78ae17423917bd
Update IShellCommandContextStore.cs
tiksn/TIKSN-Framework
TIKSN.Core/Shell/IShellCommandContextStore.cs
TIKSN.Core/Shell/IShellCommandContextStore.cs
namespace TIKSN.Shell { public interface IShellCommandContextStore { void SetCommandName(string commandName); } }
namespace TIKSN.Shell { public interface IShellCommandContextStore { void SetCommandName(string commandName); } }
mit
C#
714fa6c2fc6b22cfb23f4a2ae1f43e2cebf197ed
Move log files to local application data.
GeorgeAlexandria/CoCo
CoCo/NLog.cs
CoCo/NLog.cs
using System; using System.IO; using NLog; using NLog.Config; using NLog.Targets; namespace CoCo { internal static class NLog { internal static void Initialize() { string appDataLocal = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\\CoCo"; if (!Directory.Exists(appDataLocal)) { Directory.CreateDirectory(appDataLocal); } LoggingConfiguration config = new LoggingConfiguration(); FileTarget fileTarget = new FileTarget("File"); FileTarget fileDebugTarget = new FileTarget("File debug"); fileTarget.Layout = "${date}___${level}___${message}"; fileTarget.FileName = $"{appDataLocal}\\file.log"; fileDebugTarget.Layout = "${date}___${level}___${message}${newline}${stacktrace}"; fileDebugTarget.FileName = $"{appDataLocal}\\file_debug.log"; config.AddTarget(fileTarget); config.AddTarget(fileDebugTarget); config.AddRule(LogLevel.Debug, LogLevel.Debug, fileDebugTarget, "*"); config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "*"); //LogManager.ThrowConfigExceptions = true; //LogManager.ThrowExceptions = true; LogManager.Configuration = config; } } }
using NLog; using NLog.Config; using NLog.Targets; namespace CoCo { internal static class NLog { internal static void Initialize() { LoggingConfiguration config = new LoggingConfiguration(); FileTarget fileTarget = new FileTarget("File"); FileTarget fileDebugTarget = new FileTarget("File debug"); fileTarget.Layout = "${date}___${level}___${message}"; fileTarget.FileName = @"${nlogdir}\file.log"; fileDebugTarget.Layout = "${date}___${level}___${message}${newline}${stacktrace}"; fileDebugTarget.FileName = @"${nlogdir}\file_debug.log"; config.AddTarget(fileTarget); config.AddTarget(fileDebugTarget); config.AddRule(LogLevel.Debug, LogLevel.Debug, fileDebugTarget, "*"); config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "*"); //LogManager.ThrowConfigExceptions = true; //LogManager.ThrowExceptions = true; LogManager.Configuration = config; } } }
mit
C#
6d27cea40565b452abaf672b333554e7c63e2a72
Add thumbsmall property
paralin/D2Moddin
D2MPMaster/Model/Mod.cs
D2MPMaster/Model/Mod.cs
using ClientCommon.Data; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace D2MPMaster.Model { /// <summary> /// An addon stored in the database. /// </summary> public class Mod { public string Id { get; set; } public string name { get; set; } public string fullname { get; set; } public string version { get; set; } public string author { get; set; } public string authorimage { get; set; } public string thumbsmall { get; set; } public string thumbnail { get; set; } public string spreadimage { get; set; } public string website { get; set; } public string subtitle { get; set; } public string description { get; set; } public string[] features { get; set; } public bool playable { get; set; } //requirements public string spreadvideo { get; set; } /// <summary> /// Exclude client files from the bundle. /// </summary> public string[] exclude { get; set; } public string bundle { get; set; } public string fetch { get; set; } public string user { get; set; } public bool isPublic { get; set; } /// <summary> /// Use some other static hosting off of AWS /// </summary> public string staticClientBundle { get; set; } public ClientMod ToClientMod() { return new ClientMod() { name = name, version = version }; } } }
using ClientCommon.Data; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace D2MPMaster.Model { /// <summary> /// An addon stored in the database. /// </summary> public class Mod { public string Id { get; set; } public string name { get; set; } public string fullname { get; set; } public string version { get; set; } public string author { get; set; } public string authorimage { get; set; } public string thumbnail { get; set; } public string spreadimage { get; set; } public string website { get; set; } public string subtitle { get; set; } public string description { get; set; } public string[] features { get; set; } public bool playable { get; set; } //requirements public string spreadvideo { get; set; } /// <summary> /// Exclude client files from the bundle. /// </summary> public string[] exclude { get; set; } public string bundle { get; set; } public string fetch { get; set; } public string user { get; set; } public bool isPublic { get; set; } /// <summary> /// Use some other static hosting off of AWS /// </summary> public string staticClientBundle { get; set; } public ClientMod ToClientMod() { return new ClientMod() { name = name, version = version }; } } }
apache-2.0
C#
ac1bed420a2978b620205bc8639f6f24a83d6a86
Update TransformPlus.cs
xxmon/unity
Editor/TransformPlus.cs
Editor/TransformPlus.cs
using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor (typeof(Transform))] public class TransformPlus : Editor { Transform myTarget; float inch = 2.54f / 100.0f; float foot = 30.48f / 100.0f; bool showPosition = true; bool showRotation = true; bool showScale = true; public override void OnInspectorGUI () { myTarget = (Transform)target; showPosition = EditorGUILayout.Foldout (showPosition, "Position"); if (showPosition) { myTarget.localPosition = EditorGUILayout.Vector3Field ("Meter", myTarget.localPosition); myTarget.localPosition = EditorGUILayout.Vector3Field ("Inch", myTarget.localPosition / inch) * inch; myTarget.localPosition = EditorGUILayout.Vector3Field ("Foot", myTarget.localPosition / foot) * foot; } showRotation = EditorGUILayout.Foldout (showRotation, "Rotation"); if (showRotation) { myTarget.localEulerAngles = EditorGUILayout.Vector3Field ("Rotation", myTarget.localEulerAngles); } showScale = EditorGUILayout.Foldout (showScale, "Scale"); if (showScale) { myTarget.localScale = EditorGUILayout.Vector3Field ("Meter", myTarget.localScale); myTarget.localScale = EditorGUILayout.Vector3Field ("Inch", myTarget.localScale / inch) * inch; myTarget.localScale = EditorGUILayout.Vector3Field ("Foot", myTarget.localScale / foot) * foot; } } }
using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor (typeof(Transform))] public class TransformPlus : Editor { Transform myTarget; float inch = 2.54f / 100.0f; float foot = 30.48f / 100.0f; bool showPosition = true; bool showRotation = true; bool showScale = true; public override void OnInspectorGUI () { myTarget = (Transform)target; showPosition = EditorGUILayout.Foldout (showPosition, "Position"); if (showPosition) { myTarget.localPosition = EditorGUILayout.Vector3Field ("Meter", myTarget.localPosition); myTarget.localPosition = EditorGUILayout.Vector3Field ("Inch", myTarget.localPosition / inch) * inch; myTarget.localPosition = EditorGUILayout.Vector3Field ("Foot", myTarget.localPosition / foot) * foot; } showRotation = EditorGUILayout.Foldout (showRotation, "Rotation"); if (showRotation) { myTarget.localEulerAngles = EditorGUILayout.Vector3Field ("Rotation", myTarget.localEulerAngles); } showScale = EditorGUILayout.Foldout (showScale, "Scale"); if (showScale) { myTarget.localScale = EditorGUILayout.Vector3Field ("Meter", myTarget.localScale); myTarget.localScale = EditorGUILayout.Vector3Field ("Inch", myTarget.localScale / inch) * inch; myTarget.localScale = EditorGUILayout.Vector3Field ("Foot", myTarget.localScale / foot) * foot; } } }
mit
C#
d98cd89a0ebea3d99c708095d72d478b411ee96e
implement IEquatable in ZoomItem
TakeAsh/cs-WpfUtility
ImageViewer/ZoomItem.cs
ImageViewer/ZoomItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TakeAshUtility; namespace ImageViewer { public struct ZoomItem : IEquatable<ZoomItem> { public ZoomItem(double value) : this() { Value = value; Title = value > 0 ? value + "%" : "Show All"; } public double Value { get; private set; } public string Title { get; private set; } public override string ToString() { return Title; } #region IEquatable public bool Equals(ZoomItem other) { if (ReferenceEquals(this, other)) { return true; } return this.Value == other.Value; } public override bool Equals(object other) { if (other == null || !(other is ZoomItem)) { return false; } return this.Equals((ZoomItem)other); } public override int GetHashCode() { return Value.GetHashCode(); } public static bool operator ==(ZoomItem x, ZoomItem y) { return x.Equals(y); } public static bool operator !=(ZoomItem x, ZoomItem y) { return !x.Equals(y); } #endregion } public static class ZoomItemExtensionMethods { public static List<ZoomItem> ToZoomItems(this string source) { if (String.IsNullOrEmpty(source)) { return null; } return source.SplitTrim() .Select(value => new ZoomItem(value.TryParse<double>())) .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TakeAshUtility; namespace ImageViewer { public struct ZoomItem { public ZoomItem(double value) : this() { Value = value; Title = value > 0 ? value + "%" : "Show All"; } public double Value { get; private set; } public string Title { get; private set; } public override string ToString() { return Title; } } public static class ZoomItemExtensionMethods { public static List<ZoomItem> ToZoomItems(this string source) { if (String.IsNullOrEmpty(source)) { return null; } return source.SplitTrim() .Select(value => new ZoomItem(value.TryParse<double>())) .ToList(); } } }
mit
C#
439ee14954e230d88a8950a30ae2958cccc1556f
Add debugger display for RefSpec
ethomson/libgit2sharp,Skybladev2/libgit2sharp,jeffhostetler/public_libgit2sharp,jamill/libgit2sharp,mono/libgit2sharp,OidaTiftla/libgit2sharp,github/libgit2sharp,GeertvanHorrik/libgit2sharp,psawey/libgit2sharp,AArnott/libgit2sharp,psawey/libgit2sharp,whoisj/libgit2sharp,Skybladev2/libgit2sharp,nulltoken/libgit2sharp,oliver-feng/libgit2sharp,vorou/libgit2sharp,nulltoken/libgit2sharp,github/libgit2sharp,xoofx/libgit2sharp,AMSadek/libgit2sharp,ethomson/libgit2sharp,vivekpradhanC/libgit2sharp,jorgeamado/libgit2sharp,jorgeamado/libgit2sharp,AMSadek/libgit2sharp,jamill/libgit2sharp,GeertvanHorrik/libgit2sharp,whoisj/libgit2sharp,red-gate/libgit2sharp,PKRoma/libgit2sharp,shana/libgit2sharp,xoofx/libgit2sharp,sushihangover/libgit2sharp,OidaTiftla/libgit2sharp,red-gate/libgit2sharp,sushihangover/libgit2sharp,oliver-feng/libgit2sharp,Zoxive/libgit2sharp,vivekpradhanC/libgit2sharp,mono/libgit2sharp,vorou/libgit2sharp,rcorre/libgit2sharp,jeffhostetler/public_libgit2sharp,dlsteuer/libgit2sharp,AArnott/libgit2sharp,libgit2/libgit2sharp,dlsteuer/libgit2sharp,shana/libgit2sharp,Zoxive/libgit2sharp,rcorre/libgit2sharp
LibGit2Sharp/RefSpec.cs
LibGit2Sharp/RefSpec.cs
using System; using System.Diagnostics; using System.Globalization; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// A push or fetch reference specification /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RefSpec { private RefSpec(string refSpec, RefSpecDirection direction, string source, string destination, bool forceUpdate) { Ensure.ArgumentNotNullOrEmptyString(refSpec, "refSpec"); Ensure.ArgumentNotNull(source, "source"); Ensure.ArgumentNotNull(destination, "destination"); Specification = refSpec; Direction = direction; Source = source; Destination = destination; ForceUpdate = forceUpdate; } /// <summary> /// Needed for mocking purposes. /// </summary> protected RefSpec() { } internal static RefSpec BuildFromPtr(GitRefSpecHandle handle) { Ensure.ArgumentNotNull(handle, "handle"); return new RefSpec(Proxy.git_refspec_string(handle), Proxy.git_refspec_direction(handle), Proxy.git_refspec_src(handle), Proxy.git_refspec_dst(handle), Proxy.git_refspec_force(handle)); } /// <summary> /// Gets the pattern describing the mapping between remote and local references /// </summary> public virtual string Specification { get; private set; } /// <summary> /// Indicates whether this <see cref="RefSpec"/> is intended to be used during a Push or Fetch operation /// </summary> public virtual RefSpecDirection Direction { get; private set; } /// <summary> /// The source reference specifier /// </summary> public virtual string Source { get; private set; } /// <summary> /// The target reference specifier /// </summary> public virtual string Destination { get; private set; } /// <summary> /// Indicates whether the destination will be force-updated if fast-forwarding is not possible /// </summary> public virtual bool ForceUpdate { get; private set; } private string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "{0}", Specification); } } } }
using System; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// A push or fetch reference specification /// </summary> public class RefSpec { private RefSpec(string refSpec, RefSpecDirection direction, string source, string destination, bool forceUpdate) { Ensure.ArgumentNotNullOrEmptyString(refSpec, "refSpec"); Ensure.ArgumentNotNull(source, "source"); Ensure.ArgumentNotNull(destination, "destination"); Specification = refSpec; Direction = direction; Source = source; Destination = destination; ForceUpdate = forceUpdate; } /// <summary> /// Needed for mocking purposes. /// </summary> protected RefSpec() { } internal static RefSpec BuildFromPtr(GitRefSpecHandle handle) { Ensure.ArgumentNotNull(handle, "handle"); return new RefSpec(Proxy.git_refspec_string(handle), Proxy.git_refspec_direction(handle), Proxy.git_refspec_src(handle), Proxy.git_refspec_dst(handle), Proxy.git_refspec_force(handle)); } /// <summary> /// Gets the pattern describing the mapping between remote and local references /// </summary> public virtual string Specification { get; private set; } /// <summary> /// Indicates whether this <see cref="RefSpec"/> is intended to be used during a Push or Fetch operation /// </summary> public virtual RefSpecDirection Direction { get; private set; } /// <summary> /// The source reference specifier /// </summary> public virtual string Source { get; private set; } /// <summary> /// The target reference specifier /// </summary> public virtual string Destination { get; private set; } /// <summary> /// Indicates whether the destination will be force-updated if fast-forwarding is not possible /// </summary> public virtual bool ForceUpdate { get; private set; } } }
mit
C#
381bc7d8c2ecfb5c24c75520480ad67983139e3e
Update grubconfig according to osdev.org
CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos
source/Cosmos.Build.Tasks/CreateGrubConfig.cs
source/Cosmos.Build.Tasks/CreateGrubConfig.cs
using System.Diagnostics; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Cosmos.Build.Tasks { public class CreateGrubConfig: Task { [Required] public string TargetDirectory { get; set; } [Required] public string BinName { get; set; } private string Indentation = " "; public override bool Execute() { if (!Directory.Exists(TargetDirectory)) { Log.LogError($"Invalid target directory! Target directory: '{TargetDirectory}'"); return false; } var xBinName = BinName; var xLabelName = Path.GetFileNameWithoutExtension(xBinName); using (var xWriter = File.CreateText(Path.Combine(TargetDirectory + "/boot/grub/", "grub.cfg"))) { xWriter.WriteLine("menuentry '" + xLabelName + "' {"); WriteIndentedLine(xWriter, "multiboot /boot/" + xBinName); xWriter.WriteLine("}"); } return true; } private void WriteIndentedLine(TextWriter aWriter, string aText) { aWriter.WriteLine(Indentation + aText); } } }
using System.Diagnostics; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Cosmos.Build.Tasks { public class CreateGrubConfig: Task { [Required] public string TargetDirectory { get; set; } [Required] public string BinName { get; set; } private string Indentation = " "; public override bool Execute() { if (!Directory.Exists(TargetDirectory)) { Log.LogError($"Invalid target directory! Target directory: '{TargetDirectory}'"); return false; } var xBinName = BinName; var xLabelName = Path.GetFileNameWithoutExtension(xBinName); using (var xWriter = File.CreateText(Path.Combine(TargetDirectory + "/boot/grub/", "grub.cfg"))) { xWriter.WriteLine("insmod vbe"); xWriter.WriteLine("insmod vga"); xWriter.WriteLine("insmod video_bochs"); xWriter.WriteLine("insmod video_cirrus"); xWriter.WriteLine("set root='(hd0,msdos1)'"); xWriter.WriteLine(); xWriter.WriteLine("menuentry '" + xLabelName + "' {"); WriteIndentedLine(xWriter, "multiboot /boot/" + xBinName + " vid=preset,1024,768 hdd=0"); WriteIndentedLine(xWriter, "set gfxpayload=800x600x32"); WriteIndentedLine(xWriter, "boot"); xWriter.WriteLine("}"); } return true; } private void WriteIndentedLine(TextWriter aWriter, string aText) { aWriter.WriteLine(Indentation + aText); } } }
bsd-3-clause
C#
02bcfd53c1b79e84b1eaf00fff4dcb382672fcd5
Add init method to unit tests
protyposis/Aurio,protyposis/Aurio
AudioAlign/AudioAlign.PFFFT.UnitTest/PffftTest.cs
AudioAlign/AudioAlign.PFFFT.UnitTest/PffftTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AudioAlign.PFFFT.UnitTest { [TestClass] public class PffftTest { [ClassInitialize] public static void ClassInitialize(TestContext testContext) { // Init the class before the tests run, so DLLs get loaded and test runtimes // of the first test are not wrong due to initialization new PFFFT(64, Transform.Real); } [TestMethod] public void TestSimdSize() { int size = PFFFT.SimdSize; Console.WriteLine("simd size: " + size); Assert.IsTrue(size > 0, "invalid size"); } [TestMethod] public void CreateInstanceReal() { var pffft = new PFFFT(4096, Transform.Real); } [TestMethod] public void CreateInstanceComplex() { var pffft = new PFFFT(4096, Transform.Complex); } [TestMethod] [ExpectedException(typeof(Exception))] public void CreateInstanceWithWrongAlignment() { var pffft = new PFFFT(4095, Transform.Real); } [TestMethod] [ExpectedException(typeof(Exception))] public void TransformTooSmall() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var data = new float[size - 1]; pffft.Forward(data); } [TestMethod] [ExpectedException(typeof(Exception))] public void TransformTooBig() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var data = new float[size + 1]; pffft.Forward(data); } [TestMethod] public void TransformForwardInPlace() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var data = new float[size]; pffft.Forward(data); } [TestMethod] public void TransformForward() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var dataIn = new float[size]; var dataOut = new float[size]; pffft.Forward(dataIn, dataOut); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AudioAlign.PFFFT.UnitTest { [TestClass] public class PffftTest { [TestMethod] public void TestSimdSize() { int size = PFFFT.SimdSize; Console.WriteLine("simd size: " + size); Assert.IsTrue(size > 0, "invalid size"); } [TestMethod] public void CreateInstanceReal() { var pffft = new PFFFT(4096, Transform.Real); } [TestMethod] public void CreateInstanceComplex() { var pffft = new PFFFT(4096, Transform.Complex); } [TestMethod] [ExpectedException(typeof(Exception))] public void CreateInstanceWithWrongAlignment() { var pffft = new PFFFT(4095, Transform.Real); } [TestMethod] [ExpectedException(typeof(Exception))] public void TransformTooSmall() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var data = new float[size - 1]; pffft.Forward(data); } [TestMethod] [ExpectedException(typeof(Exception))] public void TransformTooBig() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var data = new float[size + 1]; pffft.Forward(data); } [TestMethod] public void TransformForwardInPlace() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var data = new float[size]; pffft.Forward(data); } [TestMethod] public void TransformForward() { int size = 4096; var pffft = new PFFFT(size, Transform.Real); var dataIn = new float[size]; var dataOut = new float[size]; pffft.Forward(dataIn, dataOut); } } }
agpl-3.0
C#
1ce78d5523f515af19365c9b5be0b63e0c2bdea3
Add a cache to RandomWeapon containing all weapons
Davipb/GreatTextAdventures
GreatTextAdventures/Items/Weapons/RandomWeapon.cs
GreatTextAdventures/Items/Weapons/RandomWeapon.cs
using Newtonsoft.Json.Linq; using System.IO; using System.Linq; namespace GreatTextAdventures.Items.Weapons { public class RandomWeapon : Weapon { public static JObject AllWeapons { get; private set; } protected RandomWeapon(string name, string nameMod, int attack, int attackMod) { baseName = name; nameModifier = nameMod; baseAttack = attack; attackModifier = attackMod; } public static RandomWeapon Generate(int level) { if (AllWeapons == null) AllWeapons = JObject.Parse(File.ReadAllText(@"Items\Weapons\Weapons.json")); JArray names = (JArray)AllWeapons["Names"]; JArray modifiers = (JArray)AllWeapons["Modifiers"]; JArray chosenModifier = (JArray)modifiers.OrderBy(x => GameSystem.RNG.Next()).First(); string chosenName = (string)names.OrderBy(x => GameSystem.RNG.Next()).First(); return new RandomWeapon(chosenName, (string)chosenModifier[0], GameSystem.RNG.Next(level * 5, level * 10), (int)chosenModifier[1]); } } }
using Newtonsoft.Json.Linq; using System.IO; using System.Linq; namespace GreatTextAdventures.Items.Weapons { public class RandomWeapon : Weapon { public RandomWeapon(string name, string nameModifier, int attack, int attackModifier) { this.baseName = name; this.nameModifier = nameModifier; this.baseAttack = attack; this.attackModifier = attackModifier; } public static RandomWeapon Generate(int level) { JObject weapons = JObject.Parse(File.ReadAllText(@"Items\Weapons\Weapons.json")); JArray names = (JArray)weapons["Names"]; JArray modifiers = (JArray)weapons["Modifiers"]; JArray chosenModifier = (JArray)modifiers.OrderBy(x => GameSystem.RNG.Next()).First(); string chosenName = (string)names.OrderBy(x => GameSystem.RNG.Next()).First(); return new RandomWeapon(chosenName, (string)chosenModifier[0], GameSystem.RNG.Next(level * 5, level * 10), (int)chosenModifier[1]); } } }
mit
C#
c1384a6392e90e2ed3baee9a858c1057cb86a148
Fix Race.Description limit max
webSportENIProject/webSport,webSportENIProject/webSport
WUI/Models/RaceModel.cs
WUI/Models/RaceModel.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Web.Mvc; using WUI.Models.Attributes; namespace WUI.Models { /// <summary> /// Course /// </summary> public class RaceModel { [Display(Name = "Identifiant")] public int Id { get; set; } [Display(Name = "Titre")] [Required(ErrorMessage = "Le {0} est requis")] public string Title { get; set; } [Display(Name = "Description")] [StringLength(100, MinimumLength=20, ErrorMessage="La {0} doit faire au minimum 20 caractères"), ] [MaxLength("100", "La {0} doit faire au maximun 100 caractères")] [Required(ErrorMessage = "La {0} est requise")] public string Description { get; set; } [Display(Name = "Date de début")] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")] [CompareDate("DateEnd", DateBefore = true)] // Par défaut, une date est requise car le type DateTime n'est pas "Nullable" public DateTime DateStart { get; set; } [Display(Name = "Date de fin")] [DataType(DataType.Text)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")] [CompareDate("DateStart")] public DateTime DateEnd { get; set; } [Display(Name = "Ville")] [Required(ErrorMessage = "La {0} est requise")] public string Town { get; set; } [Display(Name = "Nb max Participants")] [Required(ErrorMessage = "Le {0} est requise")] public int MaxParticipants { get; set; } public bool Inscrit { get; set; } public List<ParticipantModel> Participants { get; set; } public List<PointModel> Points { get; set; } public RaceModel() { Inscrit = false; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Web.Mvc; using WUI.Models.Attributes; namespace WUI.Models { /// <summary> /// Course /// </summary> public class RaceModel { [Display(Name = "Identifiant")] public int Id { get; set; } [Display(Name = "Titre")] [Required(ErrorMessage = "Le {0} est requis")] public string Title { get; set; } [Display(Name = "Description")] [StringLength(200, MinimumLength=20, ErrorMessage="La {0} doit faire au minimum 20 caractères")] [Required(ErrorMessage = "La {0} est requise")] public string Description { get; set; } [Display(Name = "Date de début")] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")] [CompareDate("DateEnd", DateBefore = true)] // Par défaut, une date est requise car le type DateTime n'est pas "Nullable" public DateTime DateStart { get; set; } [Display(Name = "Date de fin")] [DataType(DataType.Text)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")] [CompareDate("DateStart")] public DateTime DateEnd { get; set; } [Display(Name = "Ville")] [Required(ErrorMessage = "La {0} est requise")] public string Town { get; set; } [Display(Name = "Nb max Participants")] [Required(ErrorMessage = "Le {0} est requise")] public int MaxParticipants { get; set; } public bool Inscrit { get; set; } public List<ParticipantModel> Participants { get; set; } public List<PointModel> Points { get; set; } public RaceModel() { Inscrit = false; } } }
apache-2.0
C#
6800e53b2f3bfc40ff66ea268c9a63afb380960f
Upgrade version to 0.8.0.0
Erikvl87/KNKVPlugin
KNKVPlugin/Properties/AssemblyInfo.cs
KNKVPlugin/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KNKVPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("KNKVPlugin")] [assembly: AssemblyCopyright("Copyright © 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("8744f6d4-c5e1-4fed-9d97-04922b3aab1f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KNKVPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("KNKVPlugin")] [assembly: AssemblyCopyright("Copyright © 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("8744f6d4-c5e1-4fed-9d97-04922b3aab1f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.0.0")]
mit
C#
03a48ca3e2d00d82d858ece49b54219c9475642c
fix missing namespace
volak/Aggregates.NET,volak/Aggregates.NET
src/Aggregates.NET/ContextExtensions.cs
src/Aggregates.NET/ContextExtensions.cs
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading.Tasks; using Aggregates.Contracts; namespace Aggregates { [ExcludeFromCodeCoverage] public static class ContextExtensions { public static TUnitOfWork App<TUnitOfWork>(this IServiceContext context) where TUnitOfWork : class, UnitOfWork.IApplication { return context.App as TUnitOfWork; } /// <summary> /// Easier access to uow if user implements IGeneric /// </summary> public static UnitOfWork.IGeneric App(this IServiceContext context) { return context.App as UnitOfWork.IGeneric; } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, TService service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); return processor.Process<TService, TResponse>(service, container); } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, Action<TService> service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); var factory = container.Resolve<IEventFactory>(); return processor.Process<TService, TResponse>(factory.Create(service), container); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Aggregates.Contracts; namespace Aggregates { [ExcludeFromCodeCoverage] public static class ContextExtensions { public static TUnitOfWork App<TUnitOfWork>(this IServiceContext context) where TUnitOfWork : class, UnitOfWork.IApplication { return context.App as TUnitOfWork; } /// <summary> /// Easier access to uow if user implements IGeneric /// </summary> public static UnitOfWork.IGeneric App(this IServiceContext context) { return context.App as UnitOfWork.IGeneric; } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, TService service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); return processor.Process<TService, TResponse>(service, container); } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, Action<TService> service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); var factory = container.Resolve<IEventFactory>(); return processor.Process<TService, TResponse>(factory.Create(service), container); } } }
mit
C#
6b6e92fb965691fac5b7095c5a53d926b11d62a3
Improve logging format
patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity
src/Assets/Scripts/Debug/DebugLogger.cs
src/Assets/Scripts/Debug/DebugLogger.cs
using System; namespace PatchKit.Unity.Patcher.Debug { public class DebugLogger { private readonly string _context; public DebugLogger(Type context) { _context = context.FullName; } private static string FormatMessage(string type, string message) { return string.Format("{0} {1}: {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz"), type, message); } private static string FormatExceptionMessage(Exception exception) { return string.Format("{0}: {1}\n\nStack trace:\n{2}", exception.GetType(), exception.Message, exception.StackTrace); } // [LOG ] // [WARNING ] // [ERROR ] // [EXCEPTION] public void Log(string message) { UnityEngine.Debug.Log(FormatMessage("[ Log ]", message)); } public void LogWarning(string message) { UnityEngine.Debug.LogWarning(FormatMessage("[ Warning ]", message)); } public void LogError(string message) { UnityEngine.Debug.LogError(FormatMessage("[ Error ]", message)); } public void LogException(Exception exception) { UnityEngine.Debug.LogErrorFormat(FormatMessage("[Exception]", FormatExceptionMessage(exception))); int innerExceptionCounter = 1; var innerException = exception.InnerException; while (innerException != null) { UnityEngine.Debug.LogErrorFormat("Inner Exception {0}: {1}", innerExceptionCounter, FormatExceptionMessage(innerException)); innerException = innerException.InnerException; } } public void LogConstructor() { Log(string.Format("{0} constructor.", _context)); } public void LogDispose() { Log(string.Format("{0} dispose.", _context)); } public void LogVariable(object value, string name) { Log(string.Format("{0} = {1}", name, value)); } } }
using System; namespace PatchKit.Unity.Patcher.Debug { public class DebugLogger { private readonly string _context; public DebugLogger(Type context) { _context = context.FullName; } // TODO: Unify logging format and add date time. private static string FormatExceptionLog(Exception exception) { return string.Format("{0}: {1}\n\nStack trace:\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace); } public void Log(object message) { UnityEngine.Debug.LogFormat("[{0}] {1}", _context, message); } public void LogConstructor() { UnityEngine.Debug.LogFormat("[{0}] Constructor.", _context); } public void LogDispose() { UnityEngine.Debug.LogFormat("[{0}] Disposing.", _context); } public void LogVariable(object value, string name) { UnityEngine.Debug.LogFormat("[{0}] {1} = {2}", _context, name, value); } public void LogWarning(object message) { UnityEngine.Debug.LogWarningFormat("[{0}] {1}", _context, message); } public void LogError(object message) { UnityEngine.Debug.LogErrorFormat("[{0}] {1}", _context, message); } public void LogException(Exception exception) { UnityEngine.Debug.LogErrorFormat("[{0}] {1}", _context, FormatExceptionLog(exception)); int innerExceptionCounter = 1; var innerException = exception.InnerException; while (innerException != null) { UnityEngine.Debug.LogErrorFormat("[{0}] Inner Exception {1}: {2}", _context, innerExceptionCounter, FormatExceptionLog(exception)); innerException = innerException.InnerException; } } } }
mit
C#
22301aa38601a25e6ecd64adb96fdf0cbc1c8038
Fix repl sometimes leaking values on the eval stack
SirTony/Mond,SirTony/Mond,SirTony/Mond,Rohansi/Mond,Rohansi/Mond,Rohansi/Mond
Mond/MondProgram.cs
Mond/MondProgram.cs
using System; using System.Collections.Generic; using System.Linq; using Mond.Compiler; using Mond.Compiler.Expressions; using Mond.VirtualMachine; namespace Mond { public sealed class MondProgram { internal readonly byte[] Bytecode; internal readonly List<MondValue> Numbers; internal readonly List<MondValue> Strings; internal readonly DebugInfo DebugInfo; internal MondProgram(byte[] bytecode, IEnumerable<double> numbers, IEnumerable<string> strings, DebugInfo debugInfo = null) { Bytecode = bytecode; Numbers = numbers.Select(n => new MondValue(n)).ToList(); Strings = strings.Select(s => new MondValue(s)).ToList(); DebugInfo = debugInfo; } /// <summary> /// Compile a Mond program from a string. /// </summary> /// <param name="source">Source code to compile</param> /// <param name="fileName">Optional file name to use in errors</param> /// <param name="options"></param> public static MondProgram Compile(string source, string fileName = null, MondCompilerOptions options = null) { options = options ?? new MondCompilerOptions(); var lexer = new Lexer(source, fileName); var parser = new Parser(lexer); var expression = parser.ParseAll(); return CompileImpl(expression, options); } /// <summary> /// Compiles a single statement from a stream of characters. This should /// only really be useful when implementing REPLs. /// </summary> public static MondProgram CompileStatement(IEnumerable<char> source, string fileName = null, MondCompilerOptions options = null) { options = options ?? new MondCompilerOptions(); var lexer = new Lexer(source, int.MaxValue, fileName); var parser = new Parser(lexer); var expression = new BlockExpression(new List<Expression> { parser.ParseStatement() }); return CompileImpl(expression, options); } private static MondProgram CompileImpl(Expression expression, MondCompilerOptions options) { expression.SetParent(null); expression.Simplify(); //using (var writer = new IndentTextWriter(Console.Out, " ")) // expression.Print(writer); var compiler = new ExpressionCompiler(options); return compiler.Compile(expression); } } }
using System; using System.Collections.Generic; using System.Linq; using Mond.Compiler; using Mond.Compiler.Expressions; using Mond.VirtualMachine; namespace Mond { public sealed class MondProgram { internal readonly byte[] Bytecode; internal readonly List<MondValue> Numbers; internal readonly List<MondValue> Strings; internal readonly DebugInfo DebugInfo; internal MondProgram(byte[] bytecode, IEnumerable<double> numbers, IEnumerable<string> strings, DebugInfo debugInfo = null) { Bytecode = bytecode; Numbers = numbers.Select(n => new MondValue(n)).ToList(); Strings = strings.Select(s => new MondValue(s)).ToList(); DebugInfo = debugInfo; } /// <summary> /// Compile a Mond program from a string. /// </summary> /// <param name="source">Source code to compile</param> /// <param name="fileName">Optional file name to use in errors</param> /// <param name="options"></param> public static MondProgram Compile(string source, string fileName = null, MondCompilerOptions options = null) { options = options ?? new MondCompilerOptions(); var lexer = new Lexer(source, fileName); var parser = new Parser(lexer); var expression = parser.ParseAll(); return CompileImpl(expression, options); } /// <summary> /// Compiles a single statement from a stream of characters. This should /// only really be useful when implementing REPLs. /// </summary> public static MondProgram CompileStatement(IEnumerable<char> source, string fileName = null, MondCompilerOptions options = null) { options = options ?? new MondCompilerOptions(); var lexer = new Lexer(source, int.MaxValue, fileName); var parser = new Parser(lexer); var expression = parser.ParseStatement(); return CompileImpl(expression, options); } private static MondProgram CompileImpl(Expression expression, MondCompilerOptions options) { expression.SetParent(null); expression.Simplify(); //using (var writer = new IndentTextWriter(Console.Out, " ")) // expression.Print(writer); var compiler = new ExpressionCompiler(options); return compiler.Compile(expression); } } }
mit
C#
a523cfcd2b0dc8dd89444dfe3fb105bf4b5cddc1
Revert "Removed app config code from ServiceClientAdapter"
devigned/azure-powershell,naveedaz/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,hovsepm/azure-powershell,zhencui/azure-powershell,yantang-msft/azure-powershell,shuagarw/azure-powershell,nemanja88/azure-powershell,AzureAutomationTeam/azure-powershell,nemanja88/azure-powershell,shuagarw/azure-powershell,devigned/azure-powershell,nemanja88/azure-powershell,zhencui/azure-powershell,devigned/azure-powershell,arcadiahlyy/azure-powershell,nemanja88/azure-powershell,alfantp/azure-powershell,CamSoper/azure-powershell,akurmi/azure-powershell,yoavrubin/azure-powershell,krkhan/azure-powershell,Matt-Westphal/azure-powershell,jtlibing/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,CamSoper/azure-powershell,jtlibing/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,ankurchoubeymsft/azure-powershell,Matt-Westphal/azure-powershell,yoavrubin/azure-powershell,yoavrubin/azure-powershell,ankurchoubeymsft/azure-powershell,devigned/azure-powershell,yantang-msft/azure-powershell,alfantp/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,ClogenyTechnologies/azure-powershell,hovsepm/azure-powershell,arcadiahlyy/azure-powershell,krkhan/azure-powershell,ClogenyTechnologies/azure-powershell,yoavrubin/azure-powershell,Matt-Westphal/azure-powershell,AzureRT/azure-powershell,ClogenyTechnologies/azure-powershell,nemanja88/azure-powershell,AzureRT/azure-powershell,seanbamsft/azure-powershell,zhencui/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,akurmi/azure-powershell,hovsepm/azure-powershell,akurmi/azure-powershell,shuagarw/azure-powershell,shuagarw/azure-powershell,akurmi/azure-powershell,hungmai-msft/azure-powershell,CamSoper/azure-powershell,AzureAutomationTeam/azure-powershell,hovsepm/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,rohmano/azure-powershell,AzureRT/azure-powershell,seanbamsft/azure-powershell,shuagarw/azure-powershell,ankurchoubeymsft/azure-powershell,ankurchoubeymsft/azure-powershell,hovsepm/azure-powershell,pankajsn/azure-powershell,hungmai-msft/azure-powershell,alfantp/azure-powershell,hungmai-msft/azure-powershell,AzureRT/azure-powershell,yantang-msft/azure-powershell,seanbamsft/azure-powershell,ankurchoubeymsft/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,ClogenyTechnologies/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,ClogenyTechnologies/azure-powershell,arcadiahlyy/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,krkhan/azure-powershell,arcadiahlyy/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,akurmi/azure-powershell,pankajsn/azure-powershell,CamSoper/azure-powershell,hungmai-msft/azure-powershell,jtlibing/azure-powershell,jtlibing/azure-powershell,rohmano/azure-powershell,yantang-msft/azure-powershell,jtlibing/azure-powershell,zhencui/azure-powershell,alfantp/azure-powershell,arcadiahlyy/azure-powershell,Matt-Westphal/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,zhencui/azure-powershell,zhencui/azure-powershell,rohmano/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,CamSoper/azure-powershell,yoavrubin/azure-powershell,pankajsn/azure-powershell,yantang-msft/azure-powershell,Matt-Westphal/azure-powershell,pankajsn/azure-powershell
src/ResourceManager/RecoveryServices.Backup/Commands.RecoveryServices.Backup.ServiceClientAdapter/ServiceClientAdapter.cs
src/ResourceManager/RecoveryServices.Backup/Commands.RecoveryServices.Backup.ServiceClientAdapter/ServiceClientAdapter.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RecoveryServicesModelsNS = Microsoft.Azure.Management.RecoveryServices.Backup.Models; using RecoveryServicesNS = Microsoft.Azure.Management.RecoveryServices.Backup; namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ServiceClientAdapterNS { public partial class ServiceClientAdapter { const string AppSettingsSectionName = "appSettings"; const string RecoveryServicesResourceNamespace = "Microsoft.RecoveryServices"; const string ProviderNamespaceKey = "ProviderNamespace"; const string AzureFabricName = "Azure"; ClientProxy<RecoveryServicesNS.RecoveryServicesBackupManagementClient, RecoveryServicesModelsNS.CustomRequestHeaders> BmsAdapter; public ServiceClientAdapter(SubscriptionCloudCredentials creds, Uri baseUri) { System.Configuration.Configuration exeConfiguration = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location); System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)exeConfiguration.GetSection(AppSettingsSectionName); string recoveryServicesResourceNamespace = RecoveryServicesResourceNamespace; if (appSettings.Settings[ProviderNamespaceKey] != null) { recoveryServicesResourceNamespace = appSettings.Settings[ProviderNamespaceKey].Value; } BmsAdapter = new ClientProxy<RecoveryServicesNS.RecoveryServicesBackupManagementClient, RecoveryServicesModelsNS.CustomRequestHeaders>( clientRequestId => new RecoveryServicesModelsNS.CustomRequestHeaders() { ClientRequestId = clientRequestId }, creds, baseUri); BmsAdapter.Client.ResourceNamespace = recoveryServicesResourceNamespace; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RecoveryServicesModelsNS = Microsoft.Azure.Management.RecoveryServices.Backup.Models; using RecoveryServicesNS = Microsoft.Azure.Management.RecoveryServices.Backup; namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ServiceClientAdapterNS { public partial class ServiceClientAdapter { const string RecoveryServicesResourceNamespace = "Microsoft.RecoveryServices"; const string AzureFabricName = "Azure"; ClientProxy<RecoveryServicesNS.RecoveryServicesBackupManagementClient, RecoveryServicesModelsNS.CustomRequestHeaders> BmsAdapter; public ServiceClientAdapter(SubscriptionCloudCredentials creds, Uri baseUri) { BmsAdapter = new ClientProxy<RecoveryServicesNS.RecoveryServicesBackupManagementClient, RecoveryServicesModelsNS.CustomRequestHeaders>( clientRequestId => new RecoveryServicesModelsNS.CustomRequestHeaders() { ClientRequestId = clientRequestId }, creds, baseUri); BmsAdapter.Client.ResourceNamespace = RecoveryServicesResourceNamespace; } } }
apache-2.0
C#
95b1997c14bb6fb7e2e68dd156f4feee3d139fec
Simplify Hosting's shutdown handling. Don't require a TTY on Unix.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Hosting/Program.cs
src/Microsoft.AspNet.Hosting/Program.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using Microsoft.AspNet.Hosting.Internal; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Runtime; namespace Microsoft.AspNet.Hosting { public class Program { private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini"; private readonly IServiceProvider _serviceProvider; public Program(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public void Main(string[] args) { var config = new Configuration(); if (File.Exists(HostingIniFile)) { config.AddIniFile(HostingIniFile); } config.AddEnvironmentVariables(); config.AddCommandLine(args); var host = new WebHostBuilder(_serviceProvider, config).Build(); using (host.Start()) { var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>(); Console.CancelKeyPress += delegate { appShutdownService.RequestShutdown(); }; appShutdownService.ShutdownRequested.WaitHandle.WaitOne(); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Hosting.Internal; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; using Microsoft.Framework.Runtime; namespace Microsoft.AspNet.Hosting { public class Program { private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini"; private readonly IServiceProvider _serviceProvider; public Program(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public void Main(string[] args) { var config = new Configuration(); if (File.Exists(HostingIniFile)) { config.AddIniFile(HostingIniFile); } config.AddEnvironmentVariables(); config.AddCommandLine(args); var host = new WebHostBuilder(_serviceProvider, config).Build(); var serverShutdown = host.Start(); var loggerFactory = host.ApplicationServices.GetRequiredService<ILoggerFactory>(); var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>(); var shutdownHandle = new ManualResetEvent(false); appShutdownService.ShutdownRequested.Register(() => { try { serverShutdown.Dispose(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger<Program>(); logger.LogError("Dispose threw an exception.", ex); } shutdownHandle.Set(); }); var ignored = Task.Run(() => { Console.WriteLine("Started"); Console.ReadLine(); appShutdownService.RequestShutdown(); }); shutdownHandle.WaitOne(); } } }
apache-2.0
C#
23f7710ff746c8731b2b4fed021fcffe799db1b3
Simplify ternary operation (not !)
serilog/serilog,CaioProiete/serilog,merbla/serilog,serilog/serilog,merbla/serilog
src/Serilog/Core/ForContextExtension.cs
src/Serilog/Core/ForContextExtension.cs
using System; using Serilog.Events; namespace Serilog { /// <summary> /// Extension method 'ForContext' for ILogger. /// </summary> public static class ForContextExtension { /// <summary> /// Create a logger that enriches log events with the specified property based on log event level. /// </summary> /// <typeparam name="TValue"> The type of the property value. </typeparam> /// <param name="logger">The logger</param> /// <param name="level">The log event level used to determine if log is enriched with property.</param> /// <param name="propertyName">The name of the property. Must be non-empty.</param> /// <param name="value">The property value.</param> /// <param name="destructureObjects">If true, the value will be serialized as a structured /// object if possible; if false, the object will be recorded as a scalar or simple array.</param> /// <returns>A logger that will enrich log events as specified.</returns> /// <returns></returns> public static ILogger ForContext<TValue>( this ILogger logger, LogEventLevel level, string propertyName, TValue value, bool destructureObjects = false) { if (logger == null) throw new ArgumentNullException(nameof(logger)); return logger.IsEnabled(level) ? logger.ForContext(propertyName, value, destructureObjects) : logger; } } }
using System; using Serilog.Events; namespace Serilog { /// <summary> /// Extension method 'ForContext' for ILogger. /// </summary> public static class ForContextExtension { /// <summary> /// Create a logger that enriches log events with the specified property based on log event level. /// </summary> /// <typeparam name="TValue"> The type of the property value. </typeparam> /// <param name="logger">The logger</param> /// <param name="level">The log event level used to determine if log is enriched with property.</param> /// <param name="propertyName">The name of the property. Must be non-empty.</param> /// <param name="value">The property value.</param> /// <param name="destructureObjects">If true, the value will be serialized as a structured /// object if possible; if false, the object will be recorded as a scalar or simple array.</param> /// <returns>A logger that will enrich log events as specified.</returns> /// <returns></returns> public static ILogger ForContext<TValue>( this ILogger logger, LogEventLevel level, string propertyName, TValue value, bool destructureObjects = false) { if (logger == null) throw new ArgumentNullException(nameof(logger)); return !logger.IsEnabled(level) ? logger : logger.ForContext(propertyName, value, destructureObjects); } } }
apache-2.0
C#
36e963dd4738e241cc2e123c5bcc89f51902c297
Fix inverted condition
ppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework
osu.Framework/Lists/WeakList.cs
osu.Framework/Lists/WeakList.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; namespace osu.Framework.Lists { /// <summary> /// A list maintaining weak reference of objects. /// </summary> /// <typeparam name="T">Type of items tracked by weak reference.</typeparam> public class WeakList<T> : IWeakList<T> where T : class { private readonly List<WeakReference<T>> list = new List<WeakReference<T>>(); public void Add(T obj) => Add(new WeakReference<T>(obj)); public void Add(WeakReference<T> weakReference) => list.Add(weakReference); public void Remove(T item) => list.RemoveAll(t => t.TryGetTarget(out var obj) && obj == item); public bool Remove(WeakReference<T> weakReference) => list.Remove(weakReference); public bool Contains(T item) => list.Any(t => t.TryGetTarget(out var obj) && obj == item); public bool Contains(WeakReference<T> weakReference) => list.Contains(weakReference); public void Clear() => list.Clear(); public void ForEachAlive(Action<T> action) { list.RemoveAll(item => !item.TryGetTarget(out _)); foreach (var item in list) { if (item.TryGetTarget(out T obj)) action(obj); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; namespace osu.Framework.Lists { /// <summary> /// A list maintaining weak reference of objects. /// </summary> /// <typeparam name="T">Type of items tracked by weak reference.</typeparam> public class WeakList<T> : IWeakList<T> where T : class { private readonly List<WeakReference<T>> list = new List<WeakReference<T>>(); public void Add(T obj) => Add(new WeakReference<T>(obj)); public void Add(WeakReference<T> weakReference) => list.Add(weakReference); public void Remove(T item) => list.RemoveAll(t => t.TryGetTarget(out var obj) && obj == item); public bool Remove(WeakReference<T> weakReference) => list.Remove(weakReference); public bool Contains(T item) => list.Any(t => t.TryGetTarget(out var obj) && obj == item); public bool Contains(WeakReference<T> weakReference) => list.Contains(weakReference); public void Clear() => list.Clear(); public void ForEachAlive(Action<T> action) { list.RemoveAll(item => item.TryGetTarget(out _)); foreach (var item in list) { if (item.TryGetTarget(out T obj)) action(obj); } } } }
mit
C#
451ab41583ea2b9f144939f75994281402dbd61f
Fix text input for SDL
ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework
osu.Framework/Input/GameWindowTextInput.cs
osu.Framework/Input/GameWindowTextInput.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Extensions; using osu.Framework.Platform; namespace osu.Framework.Input { public class GameWindowTextInput : ITextInputSource { private readonly IWindow window; private string pending = string.Empty; public GameWindowTextInput(IWindow window) { this.window = window; } protected virtual void HandleKeyPress(object sender, osuTK.KeyPressEventArgs e) => pending += e.KeyChar; protected virtual void HandleKeyTyped(char c) => pending += c; public bool ImeActive => false; public string GetPendingText() { try { return pending; } finally { pending = string.Empty; } } public void Deactivate(object sender) { if (window is Window win) win.KeyTyped -= HandleKeyTyped; else window.AsLegacyWindow().KeyPress -= HandleKeyPress; } public void Activate(object sender) { if (window is Window win) win.KeyTyped += HandleKeyTyped; else window.AsLegacyWindow().KeyPress += HandleKeyPress; } private void imeCompose() { //todo: implement OnNewImeComposition?.Invoke(string.Empty); } private void imeResult() { //todo: implement OnNewImeResult?.Invoke(string.Empty); } public event Action<string> OnNewImeComposition; public event Action<string> OnNewImeResult; } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Extensions; using osu.Framework.Platform; namespace osu.Framework.Input { public class GameWindowTextInput : ITextInputSource { private readonly IWindow window; private string pending = string.Empty; public GameWindowTextInput(IWindow window) { this.window = window; } protected virtual void HandleKeyPress(object sender, osuTK.KeyPressEventArgs e) => pending += e.KeyChar; public bool ImeActive => false; public string GetPendingText() { try { return pending; } finally { pending = string.Empty; } } public void Deactivate(object sender) { window.AsLegacyWindow().KeyPress -= HandleKeyPress; } public void Activate(object sender) { window.AsLegacyWindow().KeyPress += HandleKeyPress; } private void imeCompose() { //todo: implement OnNewImeComposition?.Invoke(string.Empty); } private void imeResult() { //todo: implement OnNewImeResult?.Invoke(string.Empty); } public event Action<string> OnNewImeComposition; public event Action<string> OnNewImeResult; } }
mit
C#
2aab6f8ea2a8911b4a0789a328ea10de3683e4ad
Add weapon enum
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/IWQ.cs
Battery-Commander.Web/Models/IWQ.cs
using System; using System.ComponentModel.DataAnnotations; namespace BatteryCommander.Web.Models { public partial class Soldier { //[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")] //public DateTime? IwqQualificationDate { get; set; } //public TimeSpan? IwqQualificationAge => (DateTime.Today - IwqQualificationDate); //[Display(Name = "DSCA Qualified?")] //public Boolean IwqQualified => IwqQualificationAge.HasValue && IwqQualificationAge < TimeSpan.FromDays(365); } public enum Weapon : byte { M4, M9, M240B, M249, M320 } public enum WeaponQualificationStatus : byte { Unqualified, Marksman, Sharpshooter, Expert } }
using System; using System.ComponentModel.DataAnnotations; namespace BatteryCommander.Web.Models { public partial class Soldier { //[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")] //public DateTime? IwqQualificationDate { get; set; } //public TimeSpan? IwqQualificationAge => (DateTime.Today - IwqQualificationDate); //[Display(Name = "DSCA Qualified?")] //public Boolean IwqQualified => IwqQualificationAge.HasValue && IwqQualificationAge < TimeSpan.FromDays(365); } public enum WeaponQualificationStatus : byte { Unqualified, Marksman, Sharpshooter, Expert } }
mit
C#
7f12f87e78073917594e46b5b32425ad1a863196
Fix console application window title
kappa7194/otp
Albireo.Otp.ConsoleApplication/Program.cs
Albireo.Otp.ConsoleApplication/Program.cs
namespace Albireo.Otp.ConsoleApplication { using System; public static class Program { public static void Main() { Console.Title = "C# One-Time Password"; } } }
namespace Albireo.Otp.ConsoleApplication { using System; public static class Program { public static void Main() { Console.Title = "One-Time Password Generator"; } } }
mit
C#
bb7e10e378ff0e14a1a36db7b93797f778e30246
Set Version 0.0.2
hazzik/Tail.Fody
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Tail")] [assembly: AssemblyProduct("Tail")] [assembly: AssemblyVersion("0.0.2")] [assembly: AssemblyFileVersion("0.0.2")]
using System.Reflection; [assembly: AssemblyTitle("Tail")] [assembly: AssemblyProduct("Tail")] [assembly: AssemblyVersion("0.0.1")] [assembly: AssemblyFileVersion("0.0.1")]
mit
C#
a445454d9fc3ed73aceb079676ceafbbd1146b54
Bump version to 0.10.10.
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
CactbotOverlay/Properties/AssemblyInfo.cs
CactbotOverlay/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.10.10.0")] [assembly: AssemblyFileVersion("0.10.10.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.10.9.0")] [assembly: AssemblyFileVersion("0.10.9.0")]
apache-2.0
C#
75458b313f6e4e8a874c123865c9388c9879df42
Update AlexDunn.cs
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/AlexDunn.cs
src/Firehose.Web/Authors/AlexDunn.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlexDunn : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Alex"; public string LastName => "Dunn"; public string StateOrRegion => "Boston, MA"; public string TwitterHandle => "suave_pirate"; public string EmailAddress => "[email protected]"; public string ShortBioOrTagLine => "I build robust applications and train other developers along the way."; public string GravatarHash => "bd76e4531285c3b6c423a890378c6002"; public Uri WebSite => new Uri("https://alexdunn.org"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://alexdunn.org/feed/"); } } public string GitHubHandle => "SuavePirate"; public bool Filter(SyndicationItem item) => item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")); public GeoPosition Position => new GeoPosition(42.364940, -71.068876); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlexDunn : IAmACommunityMember { public string FirstName => "Alex"; public string LastName => "Dunn"; public string StateOrRegion => "Boston, MA"; public string TwitterHandle => "suave_pirate"; public string EmailAddress => "[email protected]"; public string ShortBioOrTagLine => "I build robust applications and train other developers along the way."; public string GravatarHash => "bd76e4531285c3b6c423a890378c6002"; public Uri WebSite => new Uri("https://alexdunn.org"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://alexdunn.org/feed/"); } } public string GitHubHandle => "SuavePirate"; public bool Filter(SyndicationItem item) => item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")); public GeoPosition Position => new GeoPosition(42.364940, -71.068876); } }
mit
C#
bd4662f635217c373ca8297876887e10e10baa03
Fix the bug in the binary search
cschen1205/cs-algorithms,cschen1205/cs-algorithms
Algorithms/Search/BinarySearch.cs
Algorithms/Search/BinarySearch.cs
using System; using System.Security.Cryptography; using Algorithms.Utils; namespace Algorithms.Search { public class BinarySearch { public static int IndexOf<T>(T[] a, T v) where T: IComparable<T> { var lo = 0; var hi = a.Length - 1; int comparison(T a1, T a2) => a1.CompareTo(a2); while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (SortUtil.IsLessThan(a[mid], v, comparison)) lo = mid+1; else if (SortUtil.IsGreaterThan(a[mid], v, comparison)) hi = mid - 1; else return mid; } return -1; } } }
using System; using System.Security.Cryptography; using Algorithms.Utils; namespace Algorithms.Search { public class BinarySearch { public static int IndexOf<T>(T[] a, T v) where T: IComparable<T> { var lo = 0; var hi = a.Length - 1; int comparison(T a1, T a2) => a1.CompareTo(a2); while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (SortUtil.IsLessThan(a[mid], v, comparison)) lo = mid; else if (SortUtil.IsGreaterThan(a[mid], v, comparison)) hi = mid; } return -1; } } }
mit
C#
8b0b29717b8ba1c5cd0142c9975040260b105bac
Read reviews from the database.
otac0n/GitReview,otac0n/GitReview,otac0n/GitReview
GitReview/Controllers/ReviewController.cs
GitReview/Controllers/ReviewController.cs
// ----------------------------------------------------------------------- // <copyright file="ReviewController.cs" company="(none)"> // Copyright © 2015 John Gietzen. All Rights Reserved. // This source is subject to the MIT license. // Please see license.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace GitReview.Controllers { using System.Net; using System.Threading.Tasks; using System.Web.Http; /// <summary> /// Provides an API for working with reviews. /// </summary> public class ReviewController : ApiController { /// <summary> /// Gets the specified review. /// </summary> /// <param name="id">The ID of the review to find.</param> /// <returns>The specified review.</returns> [Route("reviews/{id}")] public async Task<object> Get(string id) { using (var ctx = new ReviewContext()) { var review = await ctx.Reviews.FindAsync(id); if (review == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return new { Reviews = new[] { review }, }; } } } }
// ----------------------------------------------------------------------- // <copyright file="ReviewController.cs" company="(none)"> // Copyright © 2015 John Gietzen. All Rights Reserved. // This source is subject to the MIT license. // Please see license.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace GitReview.Controllers { using System.Web.Http; using GitReview.Models; /// <summary> /// Provides an API for working with reviews. /// </summary> public class ReviewController : ApiController { /// <summary> /// Gets the specified review. /// </summary> /// <param name="id">The ID of the review to find.</param> /// <returns>The specified review.</returns> [Route("reviews/{id}")] public object Get(string id) { return new { Reviews = new[] { new Review { Id = id }, } }; } } }
mit
C#
06f5356ebf0ed9f5b148c71b650c79a5a4079c68
Delete unused namespaces
HiP-App/HiP-Achievements,HiP-App/HiP-Achievements,HiP-App/HiP-Achievements
HIP-Achievements.Model/Rest/ActionArgs.cs
HIP-Achievements.Model/Rest/ActionArgs.cs
using PaderbornUniversity.SILab.Hip.Achievements.Model.Entity; using System.ComponentModel.DataAnnotations; namespace PaderbornUniversity.SILab.Hip.Achievements.Model.Rest { public class ActionArgs { [Required] public ActionType Type { get; set; } /// <summary> /// Id of entity, which was completed /// </summary> [Required] public int EntityId { get; set; } } }
using PaderbornUniversity.SILab.Hip.Achievements.Model.Entity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace PaderbornUniversity.SILab.Hip.Achievements.Model.Rest { public class ActionArgs { [Required] public ActionType Type { get; set; } /// <summary> /// Id of entity, which was completed /// </summary> [Required] public int EntityId { get; set; } } }
apache-2.0
C#
14dde0dad389d8e49d360befafabdf0f6e61a8cc
add explain.
nabehiro/HttpAuthModule,nabehiro/HttpAuthModule
HttpAuthModule/Properties/AssemblyInfo.cs
HttpAuthModule/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("HttpAuthModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HttpAuthModule")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("a229e6bd-81cd-489c-9c4c-0e090e0f8c40")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.2")] [assembly: AssemblyFileVersion("1.0.0.2")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("HttpAuthModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HttpAuthModule")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("a229e6bd-81cd-489c-9c4c-0e090e0f8c40")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
apache-2.0
C#
52f68831e4c4a3a4fba85e510d1f975b949e7703
Clean code
cd01/sudo-in-windows,cd01/sudo-in-windows
sudo.cs
sudo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sudo { class Program { static void Main(string[] args) { var startInfo = new System.Diagnostics.ProcessStartInfo() { FileName = args[0], UseShellExecute = true, Verb = "runas", Arguments = new Func<IEnumerable<string>, string>((argsInShell) => { return string.Join(" ", argsInShell); })(args.Skip(1)) }; try { var proc = System.Diagnostics.Process.Start(startInfo); proc.WaitForExit(); } catch(Exception ex) { Console.Error.WriteLine(ex.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sudo { class Program { static void Main(string[] args) { var startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = args[0]; startInfo.UseShellExecute = true; startInfo.Verb = "runas"; startInfo.Arguments = new Func<IEnumerable<string>, string>((argsInShell) => { return string.Join(" ", argsInShell); })(args.Skip(1)); try { var proc = System.Diagnostics.Process.Start(startInfo); proc.WaitForExit(); } catch(Exception ex) { Console.Error.WriteLine(ex.Message); } } } }
mit
C#
8e467301c8c313d1a475a20d5f7b3068785c2909
Add IIS integration
agilepartner/SandTigerShark
GameServer/Program.cs
GameServer/Program.cs
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace SandTigerShark.GameServer { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseIISIntegration() .Build(); } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace SandTigerShark.GameServer { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
mit
C#
3dec14b89d8c36911a6f6c4e505f61c360e5f237
Fix secondary login view
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer/Views/UIAccount/SecondaryLogin.cshtml
BTCPayServer/Views/UIAccount/SecondaryLogin.cshtml
@model SecondaryLoginViewModel @{ ViewData["Title"] = "Two-factor/U2F authentication"; } @if (Model.LoginWith2FaViewModel != null && Model.LoginWithFido2ViewModel != null&& Model.LoginWithLNURLAuthViewModel != null) { <div asp-validation-summary="ModelOnly" class="text-danger"></div> } else if (Model.LoginWith2FaViewModel == null && Model.LoginWithFido2ViewModel == null && Model.LoginWithLNURLAuthViewModel == null) { <div class="row"> <div class="col-lg-12 section-heading"> <h2 class="bg-danger">2FA and U2F/FIDO2 and LNURL-Auth Authentication Methods are not available. Please go to the https endpoint.</h2> <hr class="danger"> </div> </div> } <div class="row justify-content-center"> @if (Model.LoginWith2FaViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWith2fa" model="@Model.LoginWith2FaViewModel"/> </div> } @if (Model.LoginWithFido2ViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWithFido2" model="@Model.LoginWithFido2ViewModel"/> </div> } @if (Model.LoginWithLNURLAuthViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWithLNURLAuth" model="@Model.LoginWithLNURLAuthViewModel"/> </div> } </div> @section PageFootContent { <partial name="_ValidationScriptsPartial" /> }
@model SecondaryLoginViewModel @{ ViewData["Title"] = "Two-factor/U2F authentication"; } @if (Model.LoginWith2FaViewModel != null && Model.LoginWithFido2ViewModel != null&& Model.LoginWithLNURLAuthViewModel != null) { <div asp-validation-summary="ModelOnly" class="text-danger"></div> } else if (Model.LoginWith2FaViewModel == null && Model.LoginWithFido2ViewModel == null && Model.LoginWithLNURLAuthViewModel == null) { <div class="row"> <div class="col-lg-12 section-heading"> <h2 class="bg-danger">2FA and U2F/FIDO2 and LNURL-Auth Authentication Methods are not available. Please go to the https endpoint.</h2> <hr class="danger"> </div> </div> } <div class="row justify-content-center"> @if (Model.LoginWith2FaViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWith2fa" model="@Model.LoginWith2FaViewModel"/> </div> } @if (Model.LoginWithFido2ViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWithFido2" model="@Model.LoginWithFido2ViewModel"/> </div> } @if (Model.LoginWithLNURLAuthViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWithLNURLAuth" model="@Model.LoginWithLNURLAuthViewModel"/> </div> } </div> } <div class="row justify-content-center"> @if (Model.LoginWith2FaViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWith2fa" model="@Model.LoginWith2FaViewModel"/> </div> } @if (Model.LoginWithFido2ViewModel != null) { <div class="col-sm-12 col-md-6"> <partial name="LoginWithFido2" model="@Model.LoginWithFido2ViewModel"/> </div> } </div> @section PageFootContent { <partial name="_ValidationScriptsPartial" /> }
mit
C#
195e51cf04dfff05275118567156dcc21bd66a68
Fix for batch build
theraot/Theraot
Core/Theraot/Core/NewOperationCanceledException.cs
Core/Theraot/Core/NewOperationCanceledException.cs
using System; #if NET20 || NET30 || NET35 using System.Threading; #endif #if NET40 || NET45 using System.Runtime.Serialization; #endif namespace Theraot.Core { [Serializable] public partial class NewOperationCanceledException : OperationCanceledException { public NewOperationCanceledException() { //Empty } } public partial class NewOperationCanceledException : OperationCanceledException { #if NET20 || NET30 || NET35 [NonSerialized] private CancellationToken? _token; public NewOperationCanceledException(CancellationToken token) : base() { _token = token; } public NewOperationCanceledException(string message, CancellationToken token) : base(message) { _token = token; } public NewOperationCanceledException(string message, Exception innerException, CancellationToken token) : base(message, innerException) { _token = token; } public CancellationToken CancellationToken { get { if (object.ReferenceEquals(_token, null)) { return CancellationToken.None; } else { return _token.Value; } } } #endif #if NET40 || NET45 public NewOperationCanceledException(string message) : base(message) { //Empty } public NewOperationCanceledException(string message, Exception innerException) : base(message, innerException) { //Empty } protected NewOperationCanceledException(SerializationInfo info, StreamingContext context) : base(info, context) { //Empty } #endif } }
using System; using System.Threading; namespace Theraot.Core { [Serializable] public partial class NewOperationCanceledException : OperationCanceledException { public NewOperationCanceledException() { //Empty } } public partial class NewOperationCanceledException : OperationCanceledException { #if NET20 || NET30 || NET35 [NonSerialized] private CancellationToken? _token; public NewOperationCanceledException(CancellationToken token) : base() { _token = token; } public NewOperationCanceledException(string message, CancellationToken token) : base(message) { _token = token; } public NewOperationCanceledException(string message, Exception innerException, CancellationToken token) : base(message, innerException) { _token = token; } public CancellationToken CancellationToken { get { if (object.ReferenceEquals(_token, null)) { return CancellationToken.None; } else { return _token.Value; } } } #else public NewOperationCanceledException(string message) : base(message) { //Empty } public NewOperationCanceledException(string message, Exception innerException) : base(message, innerException) { //Empty } protected NewOperationCanceledException(SerializationInfo info, StreamingContext context) : base(info, context) { //Empty } #endif } }
mit
C#
24264aabc78e0282bb12093d83a16ecd8ea5fcfa
Improve markdown (allow img) (#72)
leotsarev/joinrpg-net,kirillkos/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
JoinRpg.Helpers.Web/HtmlSanitizeHelper.cs
JoinRpg.Helpers.Web/HtmlSanitizeHelper.cs
using System; using System.Web; using Vereyon.Web; namespace JoinRpg.Helpers.Web { public static class HtmlSanitizeHelper { private static readonly Lazy<HtmlSanitizer> SimpleHtml5Sanitizer = new Lazy<HtmlSanitizer>(InitHtml5Sanitizer); private static readonly Lazy<HtmlSanitizer> RemoveAllHtmlSanitizer = new Lazy<HtmlSanitizer>(InitRemoveSanitizer); private static HtmlSanitizer InitRemoveSanitizer() { return new HtmlSanitizer() .FlattenTags("p", "h1", "h2", "h3", "h4", "h5", "strong", "b", "i", "em", "br", "p", "div", "span", "ul", "ol", "li", "a", "blockquote"); } private static void FlattenTag(this HtmlSanitizer htmlSanitizer, string tagName) { htmlSanitizer.Tag(tagName).Operation(SanitizerOperation.FlattenTag); } private static HtmlSanitizer FlattenTags(this HtmlSanitizer htmlSanitizer, params string[] tagNames) { foreach (var tagName in tagNames) { htmlSanitizer.FlattenTag(tagName); } return htmlSanitizer; } private static HtmlSanitizer InitHtml5Sanitizer() { var sanitizer = HtmlSanitizer.SimpleHtml5Sanitizer(); sanitizer.Tag("br"); sanitizer.Tag("img").AllowAttributes("src"); sanitizer.Tag("hr"); sanitizer.Tag("p"); sanitizer.Tag("blockquote"); return sanitizer; } public static string RemoveHtml(this UnSafeHtml unsafeHtml) { return RemoveAllHtmlSanitizer.Value.Sanitize(unsafeHtml.UnValidatedValue); } public static HtmlString SanitizeHtml(this UnSafeHtml unsafeHtml) { return new HtmlString(SimpleHtml5Sanitizer.Value.Sanitize(unsafeHtml.UnValidatedValue)); } } }
using System; using System.Web; using Vereyon.Web; namespace JoinRpg.Helpers.Web { public static class HtmlSanitizeHelper { private static readonly Lazy<HtmlSanitizer> SimpleHtml5Sanitizer = new Lazy<HtmlSanitizer>(InitHtml5Sanitizer); private static readonly Lazy<HtmlSanitizer> RemoveAllHtmlSanitizer = new Lazy<HtmlSanitizer>(InitRemoveSanitizer); private static HtmlSanitizer InitRemoveSanitizer() { return new HtmlSanitizer() .FlattenTags("p", "h1", "h2", "h3", "h4", "h5", "strong", "b", "i", "em", "br", "p", "div", "span", "ul", "ol", "li", "a", "blockquote"); } private static void FlattenTag(this HtmlSanitizer htmlSanitizer, string tagName) { htmlSanitizer.Tag(tagName).Operation(SanitizerOperation.FlattenTag); } private static HtmlSanitizer FlattenTags(this HtmlSanitizer htmlSanitizer, params string[] tagNames) { foreach (var tagName in tagNames) { htmlSanitizer.FlattenTag(tagName); } return htmlSanitizer; } private static HtmlSanitizer InitHtml5Sanitizer() { var sanitizer = HtmlSanitizer.SimpleHtml5Sanitizer(); sanitizer.Tag("br"); sanitizer.Tag("img"); sanitizer.Tag("hr"); sanitizer.Tag("p").RemoveEmpty(); sanitizer.Tag("blockquote"); return sanitizer; } public static string RemoveHtml(this UnSafeHtml unsafeHtml) { return RemoveAllHtmlSanitizer.Value.Sanitize(unsafeHtml.UnValidatedValue); } public static HtmlString SanitizeHtml(this UnSafeHtml unsafeHtml) { return new HtmlString(SimpleHtml5Sanitizer.Value.Sanitize(unsafeHtml.UnValidatedValue)); } } }
mit
C#
f2902508d9d3ecb2260a8fa167f8d122d039bcab
Update NativeShareTest.cs
yasirkula/UnityNativeShare
NativeShareDemo/Assets/NativeShareTest.cs
NativeShareDemo/Assets/NativeShareTest.cs
using System.Collections; using System.IO; using UnityEngine; public class NativeShareTest : MonoBehaviour { void Update() { transform.Rotate( 0, 90 * Time.deltaTime, 0 ); if( Input.GetMouseButtonDown( 0 ) ) StartCoroutine( TakeSSAndShare() ); } private IEnumerator TakeSSAndShare() { yield return new WaitForEndOfFrame(); Texture2D ss = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false ); ss.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0 ); ss.Apply(); string filePath = Path.Combine( Application.persistentDataPath, "shared img.png" ); File.WriteAllBytes( filePath, ss.EncodeToPNG() ); NativeShare.Share( filePath, true, "nativeshare.test" ); } }
using System.Collections; using System.IO; using UnityEngine; public class NativeShareTest : MonoBehaviour { void Update() { transform.Rotate( 0, 90 * Time.deltaTime, 0 ); if( Input.GetMouseButtonDown( 0 ) ) StartCoroutine( TakeSSAndShare() ); } private IEnumerator TakeSSAndShare() { yield return new WaitForEndOfFrame(); Texture2D ss = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false ); ss.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0 ); ss.Apply(); string filePath = Path.Combine( Application.persistentDataPath, "shared img.png" ); File.WriteAllBytes( filePath, ss.EncodeToPNG() ); NativeShare.Share( filePath, true, "Mi.ShareIt" ); } }
mit
C#
b0d21cdd8fd5cd4773e389e12cc0bb7c11864d8b
change gameFiled numbers to match numPad keyboard
nmarazov/Team-Sazerac
OOPTeamwork/OOPTeamwork/Core/GameField.cs
OOPTeamwork/OOPTeamwork/Core/GameField.cs
using System; namespace OOPTeamwork.Core { public struct GameField { // array on ints - the numbers indicate the position of the current player public static char[] InputSelection = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; public static void PrintFieldBorders() { Console.Clear(); Console.WriteLine(" | | "); Console.WriteLine(" {0} | {1} | {2}", InputSelection[6], InputSelection[7], InputSelection[8]); Console.WriteLine("_____|_____|_____ "); Console.WriteLine(" | | "); Console.WriteLine(" {0} | {1} | {2}", InputSelection[3], InputSelection[4], InputSelection[5]); Console.WriteLine("_____|_____|_____ "); Console.WriteLine(" | | "); Console.WriteLine(" {0} | {1} | {2}", InputSelection[0], InputSelection[1], InputSelection[2]); Console.WriteLine(" | | "); Console.WriteLine(); } } }
using System; namespace OOPTeamwork.Core { public struct GameField { // array on ints - the numbers indicate the position of the current player public static char[] InputSelection = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; public static void PrintFieldBorders() { Console.Clear(); Console.WriteLine(" | | "); Console.WriteLine(" {0} | {1} | {2}", InputSelection[0], InputSelection[1], InputSelection[2]); Console.WriteLine("_____|_____|_____ "); Console.WriteLine(" | | "); Console.WriteLine(" {0} | {1} | {2}", InputSelection[3], InputSelection[4], InputSelection[5]); Console.WriteLine("_____|_____|_____ "); Console.WriteLine(" | | "); Console.WriteLine(" {0} | {1} | {2}", InputSelection[6], InputSelection[7], InputSelection[8]); Console.WriteLine(" | | "); Console.WriteLine(); } } }
mit
C#
1408cc2b818d3c536a98a4f54953d08b5aac83d9
add .forEach() and .orBlank()
Pondidum/OctopusStore,Pondidum/OctopusStore
OctopusStore/Infrastructure/Extensions.cs
OctopusStore/Infrastructure/Extensions.cs
using System; using System.Collections.Generic; using System.Text; namespace OctopusStore.Infrastructure { public static class Extensions { public static bool EqualsIgnore(this string self, string value) { return self.Equals(value, StringComparison.OrdinalIgnoreCase); } public static void DoFirst<T>(this IEnumerable<T> self, Action<T> action) { using (var enumerator = self.GetEnumerator()) { if (enumerator.MoveNext()) { action(enumerator.Current); } } } public static void ForEach<T>(this IEnumerable<T> self, Action<T> action) { foreach (var item in self) { action(item); } } public static IEnumerable<T> OrBlank<T>(this IEnumerable<T> self, Func<T> createBlank) { var enumerator = self.GetEnumerator(); if (!enumerator.MoveNext()) { yield return createBlank(); } else { do { yield return enumerator.Current; } while (enumerator.MoveNext()); } } public static string ToBase64(this string self) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(self)); } } }
using System; using System.Collections.Generic; using System.Text; namespace OctopusStore.Infrastructure { public static class Extensions { public static bool EqualsIgnore(this string self, string value) { return self.Equals(value, StringComparison.OrdinalIgnoreCase); } public static void DoFirst<T>(this IEnumerable<T> self, Action<T> action) { using (var enumerator = self.GetEnumerator()) { if (enumerator.MoveNext()) { action(enumerator.Current); } } } public static string ToBase64(this string self) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(self)); } } }
lgpl-2.1
C#
3df103d804677206fe0669bc22b5fe5500fe9212
Remove offending and non-serializable SPContentTypeId member from BaseEntity. - Any property on an Entity should be easy to serialize, that's the whole point. - Down the road, we should implement a ContentTypeIdValue value type and its own converters so that we can expose this in an easily serializable fashion - As a compromise, for now we keep the ContentTypeName in there
AkechiNEET/Dynamite,GSoft-SharePoint/Dynamite-2010,NunoEdgarGub1/Dynamite,GSoft-SharePoint/Dynamite,NunoEdgarGub1/Dynamite,GSoft-SharePoint/Dynamite-2010,GSoft-SharePoint/Dynamite,AkechiNEET/Dynamite
Source/GSoft.Dynamite/BaseEntity.cs
Source/GSoft.Dynamite/BaseEntity.cs
using System; using GSoft.Dynamite.Binding; using Microsoft.SharePoint; namespace GSoft.Dynamite { /// <summary> /// Base class for SPListItem-mapped entities /// </summary> public class BaseEntity { /// <summary> /// Item identifier within its list /// </summary> [Property("ID", BindingType = BindingType.ReadOnly)] public int Id { get; set; } /// <summary> /// Item title /// </summary> [Property] public string Title { get; set; } /// <summary> /// Created date /// </summary> [Property(BindingType = BindingType.ReadOnly)] public DateTime Created { get; set; } /// <summary> /// Gets or sets the Content Type name associated /// </summary> /// <value> /// The Content Type name associated. /// </value> [Property(BuiltInFields.ContentTypeName, BindingType = BindingType.ReadOnly)] public string ContentTypeName { get; set; } } }
using System; using GSoft.Dynamite.Binding; using Microsoft.SharePoint; namespace GSoft.Dynamite { /// <summary> /// Base class for SPListItem-mapped entities /// </summary> public class BaseEntity { /// <summary> /// Item identifier within its list /// </summary> [Property("ID", BindingType = BindingType.ReadOnly)] public int Id { get; set; } /// <summary> /// Item title /// </summary> [Property] public string Title { get; set; } /// <summary> /// Created date /// </summary> [Property(BindingType = BindingType.ReadOnly)] public DateTime Created { get; set; } /// <summary> /// Gets or sets the Content Type Id associated /// </summary> /// <value> /// The Content Type Id associated. /// </value> [Property(BuiltInFields.ContentTypeIdName, BindingType = BindingType.ReadOnly)] public SPContentTypeId ContentTypeId { get; set; } /// <summary> /// Gets or sets the Content Type name associated /// </summary> /// <value> /// The Content Type name associated. /// </value> [Property(BuiltInFields.ContentTypeName, BindingType = BindingType.ReadOnly)] public string ContentTypeName { get; set; } } }
mit
C#
b85e0eb653041baa7693a3573fcb6c237f29f93a
Fix player aiming
grimgrimoire/projectstickman
Assets/Scripts/UI/AimPad.cs
Assets/Scripts/UI/AimPad.cs
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class AimPad : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler { static float MOVE_RANGE = 80; public GameObject player; PlayerMovement playerMove; public RectTransform joystickImage; float globalXDefault; float globalYDefault; // Use this for initialization void Start () { globalXDefault = joystickImage.position.x; globalYDefault = joystickImage.position.y; playerMove = player.GetComponent<PlayerMovement> (); } // Update is called once per frame void Update () { } public void OnDrag (PointerEventData data) { UpdateButtonPosition (data); playerMove.UpdateAim (GetAngle()); if (joystickImage.anchoredPosition.x < 0) playerMove.LookLeft (); else if(joystickImage.anchoredPosition.x > 0) playerMove.LookRight (); } public void OnPointerUp (PointerEventData data) { playerMove.RemoveTrigger (); joystickImage.anchoredPosition = Vector2.zero; playerMove.UpdateAim (90); } public void OnPointerDown (PointerEventData data) { playerMove.HoldTrigger (); UpdateButtonPosition (data); } private void UpdateButtonPosition (PointerEventData data) { Vector2 newPos = Vector2.zero; float delta = data.position.x - globalXDefault; delta = Mathf.Clamp (delta, -MOVE_RANGE, MOVE_RANGE); newPos.x = delta; delta = data.position.y - globalYDefault; delta = Mathf.Clamp (delta, -MOVE_RANGE, MOVE_RANGE); newPos.y = delta; joystickImage.anchoredPosition = newPos; } private float GetAngle () { float angle = Vector2.Angle (Vector2.down, joystickImage.anchoredPosition); //if (angle > 90) { // angle = 180 - angle; //} //if (joystickImage.anchoredPosition.y < 0) // angle = -angle; return angle; } }
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class AimPad : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler { static float MOVE_RANGE = 80; public GameObject player; PlayerMovement playerMove; public RectTransform joystickImage; float globalXDefault; float globalYDefault; // Use this for initialization void Start () { globalXDefault = joystickImage.position.x; globalYDefault = joystickImage.position.y; playerMove = player.GetComponent<PlayerMovement> (); } // Update is called once per frame void Update () { } public void OnDrag (PointerEventData data) { UpdateButtonPosition (data); playerMove.UpdateAim (GetAngle()); if (joystickImage.anchoredPosition.x < 0) playerMove.LookLeft (); else if(joystickImage.anchoredPosition.x > 0) playerMove.LookRight (); } public void OnPointerUp (PointerEventData data) { playerMove.RemoveTrigger (); joystickImage.anchoredPosition = Vector2.zero; playerMove.UpdateAim (0); } public void OnPointerDown (PointerEventData data) { playerMove.HoldTrigger (); UpdateButtonPosition (data); } private void UpdateButtonPosition (PointerEventData data) { Vector2 newPos = Vector2.zero; float delta = data.position.x - globalXDefault; delta = Mathf.Clamp (delta, -MOVE_RANGE, MOVE_RANGE); newPos.x = delta; delta = data.position.y - globalYDefault; delta = Mathf.Clamp (delta, -MOVE_RANGE, MOVE_RANGE); newPos.y = delta; joystickImage.anchoredPosition = newPos; } private float GetAngle () { float angle = Vector2.Angle (Vector2.down, joystickImage.anchoredPosition); //if (angle > 90) { // angle = 180 - angle; //} //if (joystickImage.anchoredPosition.y < 0) // angle = -angle; return angle; } }
apache-2.0
C#
a3e3b18663d62326559dd5a72a1c74921bacda3e
Set DoubleBuffered property via reflection
imasm/CSharpExtensions
CSharpEx.Forms/ControlEx.cs
CSharpEx.Forms/ControlEx.cs
using System; using System.Windows.Forms; namespace CSharpEx.Forms { /// <summary> /// Control extensions /// </summary> public static class ControlEx { /// <summary> /// Invoke action if Invoke is requiered. /// </summary> public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control { if (c.InvokeRequired) { c.Invoke(new Action(() => action(c))); } else { action(c); } } /// <summary> /// Set DoubleBuffered property using reflection. /// Call this in the constructor just after InitializeComponent(). /// </summary> public static void SetDoubleBuffered(this Control control, bool enabled) { typeof (Control).InvokeMember("DoubleBuffered", System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, control, new object[] {enabled}); } } }
using System; using System.Windows.Forms; namespace CSharpEx.Forms { /// <summary> /// Control extensions /// </summary> public static class ControlEx { /// <summary> /// Invoke action if Invoke is requiered. /// </summary> public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control { if (c.InvokeRequired) { c.Invoke(new Action(() => action(c))); } else { action(c); } } } }
apache-2.0
C#
04f61480cab638c4fb4f7087b4fa40056bbb48b5
Add remote rf enable function
Stok/EDMSuite,ColdMatter/EDMSuite,jstammers/EDMSuite,ColdMatter/EDMSuite,ColdMatter/EDMSuite,ColdMatter/EDMSuite,jstammers/EDMSuite,jstammers/EDMSuite,Stok/EDMSuite,jstammers/EDMSuite,jstammers/EDMSuite
DAQ/Gigatronics7100Synth.cs
DAQ/Gigatronics7100Synth.cs
using System; using DAQ.Environment; namespace DAQ.HAL { /// <summary> /// This class represents a GPIB controlled Gigatronics 7100 arbitrary waveform generator. It conforms to the Synth /// interface. /// </summary> public class Gigatronics7100Synth : Synth { public Gigatronics7100Synth(String visaAddress) : base(visaAddress) { } override public double Frequency { set { if (!Environs.Debug) Write("CW" + value + "MZ"); // the value is entered in MHz } } public override double Amplitude { set { if (!Environs.Debug) Write("PL" + value + "DM"); // the value is entered in dBm } // do nothing } public override double DCFM { set { } // do nothing } public override bool DCFMEnabled { set { } // do nothing } public override bool Enabled { set { if (value) { if (!Environs.Debug) Write("RF1"); } else { if (!Environs.Debug) Write("RF0"); } } } public double PulseDuration { set { if (!Environs.Debug) { Write("PM4"); Write("PW" + value + "US"); } } } } }
using System; using DAQ.Environment; namespace DAQ.HAL { /// <summary> /// This class represents a GPIB controlled Gigatronics 7100 arbitrary waveform generator. It conforms to the Synth /// interface. /// </summary> class Gigatronics7100Synth : Synth { public Gigatronics7100Synth(String visaAddress) : base(visaAddress) { } override public double Frequency { set { if (!Environs.Debug) Write("CW" + value + "MZ"); // the value is entered in MHz } } public override double Amplitude { set { if (!Environs.Debug) Write("PL" + value + "DM"); // the value is entered in MHz } // do nothing } public override double DCFM { set { } // do nothing } public override bool DCFMEnabled { set { } // do nothing } public override bool Enabled { set { } // do nothing } public double PulseDuration { set { if (!Environs.Debug) { Write("PM4"); Write("PW" + value + "US"); } } } } }
mit
C#
e29b05bce05861fc5dc36431abe8599b4d705dfc
Add constraint
sakapon/Samples-2014,sakapon/Samples-2014,sakapon/Samples-2014
VerificationSample/SortConsole/Program.cs
VerificationSample/SortConsole/Program.cs
/* * このプログラムには、架空の機能が含まれます。 */ using System; namespace SortConsole { class Program { static void Main(string[] args) { Console.WriteLine(Sort(new TwoValues(1, 1))); Console.WriteLine(Sort(new TwoValues(1, 2))); Console.WriteLine(Sort(new TwoValues(2, 1))); } // Point: 引数に対する高度な制約。 static OrderedTwoValues Sort(TwoValues v) where Sort(v).SetEquals(v) { // Point: 変数の大小関係などの高度なコンテキスト。 // コンパイルが成功すれば、このメソッドの実装も成功です。 return v.X <= v.Y ? new OrderedTwoValues(v.X, v.Y) : new OrderedTwoValues(v.Y, v.X); } } // null を代入できない型。 public class TwoValues where this != null { public int X { get; private set; } public int Y { get; private set; } public TwoValues(int x, int y) { X = x; Y = y; } public bool SetEquals(TwoValues v) { return X == v.X ? Y == v.Y : X == v.Y && Y == v.X; } public override string ToString() { return string.Format("{{{0}, {1}}}", X, Y); } } public class OrderedTwoValues : TwoValues { // Point: 引数に対する高度な制約。 public OrderedTwoValues(int x, int y) : base(x, y) where x <= y { } } }
/* * このプログラムには、架空の機能が含まれます。 */ using System; namespace SortConsole { class Program { static void Main(string[] args) { Console.WriteLine(Sort(new TwoValues(1, 1))); Console.WriteLine(Sort(new TwoValues(1, 2))); Console.WriteLine(Sort(new TwoValues(2, 1))); } // Point: 引数に対する高度な制約。 static OrderedTwoValues Sort(TwoValues v) where Sort(v).SetEquals(v) { // Point: 変数の大小関係などの高度なコンテキスト。 // コンパイルが成功すれば、このメソッドの実装も成功です。 return v.X <= v.Y ? new OrderedTwoValues(v.X, v.Y) : new OrderedTwoValues(v.Y, v.X); } } public class TwoValues { public int X { get; private set; } public int Y { get; private set; } public TwoValues(int x, int y) { X = x; Y = y; } public bool SetEquals(TwoValues v) { return X == v.X ? Y == v.Y : X == v.Y && Y == v.X; } public override string ToString() { return string.Format("{{{0}, {1}}}", X, Y); } } public class OrderedTwoValues : TwoValues { // Point: 引数に対する高度な制約。 public OrderedTwoValues(int x, int y) : base(x, y) where x <= y { } } }
mit
C#
bbc5feb07b1549fd1404534f9b758972112c6d25
Clear existing test cases before loading.
mthamil/TFSTestCaseAutomator
TestCaseAutomator/ViewModels/WorkItemsViewModel.cs
TestCaseAutomator/ViewModels/WorkItemsViewModel.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.TestManagement.Client; using TestCaseAutomator.TeamFoundation; using TestCaseAutomator.Utilities.Mvvm; using TestCaseAutomator.Utilities.PropertyNotification; namespace TestCaseAutomator.ViewModels { /// <summary> /// Represents the work items of a TFS project. /// </summary> public class WorkItemsViewModel : ViewModelBase, IWorkItems { /// <summary> /// Initializes a new <see cref="WorkItemsViewModel"/>. /// </summary> /// <param name="workItems">Used for querying for test cases</param> /// <param name="testCaseFactory">Creates test case view-models</param> /// <param name="scheduler">Used for scheduling background tasks</param> public WorkItemsViewModel(ITfsProjectWorkItemCollection workItems, Func<ITestCase, ITestCaseViewModel> testCaseFactory, TaskScheduler scheduler) { _workItems = workItems; _testCaseFactory = testCaseFactory; _scheduler = scheduler; _testCases = Property.New(this, p => p.TestCases, OnPropertyChanged); TestCases = new ObservableCollection<ITestCaseViewModel>(); } /// <summary> /// Loads test cases. /// </summary> public async Task LoadAsync() { TestCases.Clear(); var progress = new Progress<ITestCaseViewModel>(testCase => TestCases.Add(testCase)); await QueryTestCases(progress); } private Task QueryTestCases(IProgress<ITestCaseViewModel> progress) { return Task.Factory.StartNew(() => { var testCases = _workItems.TestCases().AsTestCases().Select(tc => _testCaseFactory(tc)); foreach (var testCase in testCases) progress.Report(testCase); }, CancellationToken.None, TaskCreationOptions.None, _scheduler); } /// <summary> /// The current collection of test cases. /// </summary> public ICollection<ITestCaseViewModel> TestCases { get { return _testCases.Value; } private set { _testCases.Value = value; } } private readonly Property<ICollection<ITestCaseViewModel>> _testCases; private readonly ITfsProjectWorkItemCollection _workItems; private readonly Func<ITestCase, ITestCaseViewModel> _testCaseFactory; private readonly TaskScheduler _scheduler; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.TestManagement.Client; using TestCaseAutomator.TeamFoundation; using TestCaseAutomator.Utilities.Mvvm; using TestCaseAutomator.Utilities.PropertyNotification; namespace TestCaseAutomator.ViewModels { /// <summary> /// Represents the work items of a TFS project. /// </summary> public class WorkItemsViewModel : ViewModelBase, IWorkItems { /// <summary> /// Initializes a new <see cref="WorkItemsViewModel"/>. /// </summary> /// <param name="workItems">Used for querying for test cases</param> /// <param name="testCaseFactory">Creates test case view-models</param> /// <param name="scheduler">Used for scheduling background tasks</param> public WorkItemsViewModel(ITfsProjectWorkItemCollection workItems, Func<ITestCase, ITestCaseViewModel> testCaseFactory, TaskScheduler scheduler) { _workItems = workItems; _testCaseFactory = testCaseFactory; _scheduler = scheduler; _testCases = Property.New(this, p => p.TestCases, OnPropertyChanged); TestCases = new ObservableCollection<ITestCaseViewModel>(); } /// <summary> /// Loads test cases. /// </summary> public async Task LoadAsync() { var progress = new Progress<ITestCaseViewModel>(testCase => TestCases.Add(testCase)); await QueryTestCases(progress); } private Task QueryTestCases(IProgress<ITestCaseViewModel> progress) { return Task.Factory.StartNew(() => { var testCases = _workItems.TestCases().AsTestCases().Select(tc => _testCaseFactory(tc)); foreach (var testCase in testCases) progress.Report(testCase); }, CancellationToken.None, TaskCreationOptions.None, _scheduler); } /// <summary> /// The current collection of test cases. /// </summary> public ICollection<ITestCaseViewModel> TestCases { get { return _testCases.Value; } private set { _testCases.Value = value; } } private readonly Property<ICollection<ITestCaseViewModel>> _testCases; private readonly ITfsProjectWorkItemCollection _workItems; private readonly Func<ITestCase, ITestCaseViewModel> _testCaseFactory; private readonly TaskScheduler _scheduler; } }
apache-2.0
C#
0bdcc590b384421e41c0a4ecf5fc7cc9d59e8948
fix wrong eq
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/src/Rider/UnityEditorOccurrence.cs
resharper/resharper-unity/src/Rider/UnityEditorOccurrence.cs
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using JetBrains.Annotations; using JetBrains.Application.Progress; using JetBrains.Application.UI.PopupLayout; using JetBrains.IDE; using JetBrains.Platform.RdFramework.Base; using JetBrains.Platform.Unity.EditorPluginModel; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.Occurrences; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Resolve; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Search; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Rider.Model; using JetBrains.Util; using JetBrains.Util.Extension; namespace JetBrains.ReSharper.Plugins.Unity.Rider { public class UnityEditorOccurrence : ReferenceOccurrence { private readonly IUnityYamlReference myUnityEventTargetReference; public UnityEditorOccurrence([NotNull] IUnityYamlReference unityEventTargetReference, IDeclaredElement element, OccurrenceType occurrenceType) : base(unityEventTargetReference, element, occurrenceType) { myUnityEventTargetReference = unityEventTargetReference; } public override bool Navigate(ISolution solution, PopupWindowContextSource windowContext, bool transferFocus, TabOptions tabOptions = TabOptions.Default) { if (solution.GetComponent<ConnectionTracker>().LastCheckResult == UnityEditorState.Disconnected) return base.Navigate(solution, windowContext, transferFocus, tabOptions); var findRequestCreator = solution.GetComponent<UnityEditorFindRequestCreator>(); return findRequestCreator.CreateRequestToUnity(myUnityEventTargetReference, true); } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using JetBrains.Annotations; using JetBrains.Application.Progress; using JetBrains.Application.UI.PopupLayout; using JetBrains.IDE; using JetBrains.Platform.RdFramework.Base; using JetBrains.Platform.Unity.EditorPluginModel; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.Occurrences; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Resolve; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Search; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Rider.Model; using JetBrains.Util; using JetBrains.Util.Extension; namespace JetBrains.ReSharper.Plugins.Unity.Rider { public class UnityEditorOccurrence : ReferenceOccurrence { private readonly IUnityYamlReference myUnityEventTargetReference; public UnityEditorOccurrence([NotNull] IUnityYamlReference unityEventTargetReference, IDeclaredElement element, OccurrenceType occurrenceType) : base(unityEventTargetReference, element, occurrenceType) { myUnityEventTargetReference = unityEventTargetReference; } public override bool Navigate(ISolution solution, PopupWindowContextSource windowContext, bool transferFocus, TabOptions tabOptions = TabOptions.Default) { if (solution.GetComponent<ConnectionTracker>().LastCheckResult != UnityEditorState.Disconnected) return base.Navigate(solution, windowContext, transferFocus, tabOptions); var findRequestCreator = solution.GetComponent<UnityEditorFindRequestCreator>(); return findRequestCreator.CreateRequestToUnity(myUnityEventTargetReference, true); } } }
apache-2.0
C#
9adbca26d570442b5f0c5270368c7955953c1802
Fix Console.WriteLine conflict
runnersQueue/3minutes
SubFolderTest/TestGit/Program.cs
SubFolderTest/TestGit/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Urho; using Urho.Gui; using Urho.Resources; using Urho.Shapes; namespace TestGit { class Program : SimpleApplication { Program(ApplicationOptions options = null) :base(options) { } static void Main(string[] args) { var app = new Program(new ApplicationOptions("Data") { TouchEmulation = true, WindowedMode = true }); app.Run(); } public void MyNoReturnMethod() { } static void CaseHarmfull() { //Harmfull //Harmfull2You System.Console.WriteLine("Hello"); int num = 0; for (int i = 0; i < 5; i++) { System.Console.WriteLine(i); num += i; } int newbie = ThisShouldBeHarmlessSantana(num, 7); System.Console.WriteLine(newbie); } static int ThisShouldBeHarmlessSantana(int a, int b) { return a + b; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Urho; using Urho.Gui; using Urho.Resources; using Urho.Shapes; namespace TestGit { class Program : SimpleApplication { Program(ApplicationOptions options = null) :base(options) { } static void Main(string[] args) { var app = new Program(new ApplicationOptions("Data") { TouchEmulation = true, WindowedMode = true }); app.Run(); } public void MyNoReturnMethod() { } static void CaseHarmfull() { //Harmfull //Harmfull2You Console.WriteLine("Hello"); int num = 0; for (int i = 0; i < 5; i++) { Console.WriteLine(i); num += i; } int newbie = ThisShouldBeHarmlessSantana(num, 7); Console.WriteLine(newbie); } static int ThisShouldBeHarmlessSantana(int a, int b) { return a + b; } } }
mit
C#
4570dbac797f39317f855828ebca7413db02484f
add GetResourceManager()
TakeAsh/cs-TakeAshUtility
TakeAshUtility/AssemblyHelper.cs
TakeAshUtility/AssemblyHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Resources; using System.Text; using System.Text.RegularExpressions; namespace TakeAshUtility { public static class AssemblyHelper { private static readonly Regex regPropertyResources = new Regex(@"\.Properties\."); private static readonly Regex regLastResources = new Regex(@"\.resources$"); public static T GetAttribute<T>(this Assembly assembly) where T : Attribute { if (assembly == null) { return null; } return Attribute.GetCustomAttribute(assembly, typeof(T)) as T; } /// <summary> /// Get Assembly that has specified name from CurrentDomain /// </summary> /// <param name="name">The name of Assembly</param> /// <returns> /// <list type="bullet"> /// <item>not null, if the Assembly is found.</item> /// <item>null, if the Assembly is not found.</item> /// </list> /// </returns> public static Assembly GetAssembly(string name) { return String.IsNullOrEmpty(name) ? null : AppDomain.CurrentDomain .GetAssemblies() .Where(assembly => assembly.GetName().Name == name) .FirstOrDefault(); } public static ResourceManager GetResourceManager(this Assembly assembly) { var resourceName = assembly.GetManifestResourceNames() .Where(name => regPropertyResources.IsMatch(name)) .FirstOrDefault(); return String.IsNullOrEmpty(resourceName) ? null : new ResourceManager(regLastResources.Replace(resourceName, String.Empty), assembly); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace TakeAshUtility { public static class AssemblyHelper { public static T GetAttribute<T>(this Assembly assembly) where T : Attribute { if (assembly == null) { return null; } return Attribute.GetCustomAttribute(assembly, typeof(T)) as T; } /// <summary> /// Get Assembly that has specified name from CurrentDomain /// </summary> /// <param name="name">The name of Assembly</param> /// <returns> /// <list type="bullet"> /// <item>not null, if the Assembly is found.</item> /// <item>null, if the Assembly is not found.</item> /// </list> /// </returns> public static Assembly GetAssembly(string name) { return String.IsNullOrEmpty(name) ? null : AppDomain.CurrentDomain .GetAssemblies() .Where(assembly => assembly.GetName().Name == name) .FirstOrDefault(); } } }
mit
C#
be885785d94413ddd03ce3c16d19d26c2d3a55f1
Add call to WaitForExit
chrarnoldus/VulkanRenderer,chrarnoldus/VulkanRenderer,chrarnoldus/VulkanRenderer
VulkanRendererApprovals/ApprovalTests.cs
VulkanRendererApprovals/ApprovalTests.cs
using ImageMagick; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using Xunit; namespace VulkanRendererApprovals { public class ApprovalTests { static void RenderModel(string modelPath, [CallerMemberName] string callerMemberName = null, [CallerFilePath] string callerFilePath = null) { var directoryName = Path.GetDirectoryName(callerFilePath); Process.Start(new ProcessStartInfo { FileName = Path.Combine(directoryName, "../x64/Release/VulkanRenderer.exe"), WorkingDirectory = directoryName, Arguments = $"--model \"{modelPath}\" --image \"Images\\{callerMemberName}.received.png\"" }).WaitForExit(); } static void VerifyImage([CallerMemberName] string callerMemberName = null, [CallerFilePath] string callerFilePath = null) { var directoryName = Path.GetDirectoryName(callerFilePath); using (var approved = new MagickImage(Path.Combine(directoryName, $"Images\\{callerMemberName}.approved.png"))) using (var received = new MagickImage(Path.Combine(directoryName, $"Images\\{callerMemberName}.received.png"))) { Assert.Equal(0, approved.Compare(received, ErrorMetric.Absolute)); } } [Fact] public void Bunny() { RenderModel("Models\\bun_zipper.ply"); VerifyImage(); } } }
using ImageMagick; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using Xunit; namespace VulkanRendererApprovals { public class ApprovalTests { static void RenderModel(string modelPath, [CallerMemberName] string callerMemberName = null, [CallerFilePath] string callerFilePath = null) { var directoryName = Path.GetDirectoryName(callerFilePath); Process.Start(new ProcessStartInfo { FileName = Path.Combine(directoryName, "../x64/Release/VulkanRenderer.exe"), WorkingDirectory = directoryName, Arguments = $"--model \"{modelPath}\" --image \"Images\\{callerMemberName}.received.png\"" }); } static void VerifyImage([CallerMemberName] string callerMemberName = null, [CallerFilePath] string callerFilePath = null) { var directoryName = Path.GetDirectoryName(callerFilePath); using (var approved = new MagickImage(Path.Combine(directoryName, $"Images\\{callerMemberName}.approved.png"))) using (var received = new MagickImage(Path.Combine(directoryName, $"Images\\{callerMemberName}.received.png"))) { Assert.Equal(0, approved.Compare(received, ErrorMetric.Absolute)); } } [Fact] public void Bunny() { RenderModel("Models\\bun_zipper.ply"); VerifyImage(); } } }
unlicense
C#
49adfc18f15b61c752d7889e41fc17ca0d5ae6b3
add tests for generating transform files.
jwChung/Experimentalism,jwChung/Experimentalism
test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs
test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs
using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Xunit; using Xunit.Extensions; namespace Jwc.Experiment { public class AssemblyLevelTest { const string _productDirectory = @"..\..\..\..\src\Experiment.AutoFixture\"; const string _testDirectory = @"..\..\..\..\test\Experiment.AutoFixtureUnitTest\"; [Fact] public void SutReferencesOnlySpecifiedAssemblies() { var sut = typeof(AutoFixtureAdapter).Assembly; var specifiedAssemblies = new [] { // GAC "mscorlib", "System.Core", // Direct references "xunit", "Jwc.Experiment", "Ploeh.AutoFixture", // Indirect references "Ploeh.AutoFixture.Xunit" }; var actual = sut.GetActualReferencedAssemblies(); Assert.Equal(specifiedAssemblies.OrderBy(x => x), actual.OrderBy(x => x)); } [Theory] [InlineData("Ploeh.AutoFixture.Xunit")] public void SutDoesNotExposeAnyTypesOfSpecifiedReference(string name) { // Fixture setup var sut = typeof(AutoFixtureAdapter).Assembly; var assemblyName = sut.GetActualReferencedAssemblies().Single(n => n == name); var types = Assembly.Load(assemblyName).GetExportedTypes(); // Exercise system and Verify outcome sut.VerifyDoesNotExpose(types); } [Theory] [InlineData(_productDirectory, "TheoremAttribute")] [InlineData(_productDirectory, "FirstClassTheoremAttribute")] [InlineData(_testDirectory, "Scenario")] public void SutCorrectlyGeneratesNugetTransformFiles(string directory, string originName) { var origin = directory + originName + ".cs"; var destination = directory + originName + ".cs.pp"; Assert.True(File.Exists(origin), "exists."); VerifyGeneratingFile(origin, destination); } [Conditional("CI")] private static void VerifyGeneratingFile(string origin, string destination) { var content = File.ReadAllText(origin, Encoding.UTF8) .Replace("namespace Jwc.NuGetFiles", "namespace $rootnamespace$"); File.WriteAllText(destination, content, Encoding.UTF8); Assert.True(File.Exists(destination), "exists."); } } }
using System.Linq; using System.Reflection; using Xunit; using Xunit.Extensions; namespace Jwc.Experiment { public class AssemblyLevelTest { [Fact] public void SutReferencesOnlySpecifiedAssemblies() { var sut = typeof(AutoFixtureAdapter).Assembly; var specifiedAssemblies = new [] { // GAC "mscorlib", "System.Core", // Direct references "xunit", "Jwc.Experiment", "Ploeh.AutoFixture", // Indirect references "Ploeh.AutoFixture.Xunit" }; var actual = sut.GetActualReferencedAssemblies(); Assert.Equal(specifiedAssemblies.OrderBy(x => x), actual.OrderBy(x => x)); } [Theory] [InlineData("Ploeh.AutoFixture.Xunit")] public void SutDoesNotExposeAnyTypesOfSpecifiedReference(string name) { // Fixture setup var sut = typeof(AutoFixtureAdapter).Assembly; var assemblyName = sut.GetActualReferencedAssemblies().Single(n => n == name); var types = Assembly.Load(assemblyName).GetExportedTypes(); // Exercise system and Verify outcome sut.VerifyDoesNotExpose(types); } } }
mit
C#
9a66325d3eb47a1810fcf80b20e2f35801807c93
Complete ChannelsArrangements class
Zeugma440/atldotnet
ATL/Entities/ChannelsArrangement.cs
ATL/Entities/ChannelsArrangement.cs
namespace ATL { public class ChannelsArrangements { public static ChannelsArrangement Mono = new ChannelsArrangement(1, "Mono (1/0)"); public static ChannelsArrangement DualMono = new ChannelsArrangement(2, "Dual Mono (1+1)"); public static ChannelsArrangement Stereo = new ChannelsArrangement(2, "Stereo (2/0)"); public static ChannelsArrangement StereoJoint = new ChannelsArrangement(2, "Joint Stereo"); public static ChannelsArrangement StereoSumDifference = new ChannelsArrangement(2, "Stereo - Sum & Difference"); public static ChannelsArrangement StereoLeftRightTotal = new ChannelsArrangement(2, "Stereo - Left & Right Total"); public static ChannelsArrangement CLR = new ChannelsArrangement(3, "Center - Left - Right (3/0)"); public static ChannelsArrangement LRS = new ChannelsArrangement(3, "Left - Right - Surround (3/1)"); public static ChannelsArrangement LRSLSR = new ChannelsArrangement(4, "Left - Right - Surround Left - Surround Right (2/2)"); public static ChannelsArrangement CLRSLSR = new ChannelsArrangement(5, "Center - Left - Right - Surround Left - Surround Right (3/2)"); public static ChannelsArrangement CLCRLRSLSR = new ChannelsArrangement(6, "Center Left - Center Right - Left - Right - Surround Left - Surround Right"); public static ChannelsArrangement CLRLRRRO = new ChannelsArrangement(6, "Center - Left - Right - Left Rear - Right Rear - Overhead"); public static ChannelsArrangement CFCRLFRFLRRR = new ChannelsArrangement(6, "Center Front - Center Rear - Left Front - Right Front - Left Rear - Right Rear"); public static ChannelsArrangement CLCCRLRSLSR = new ChannelsArrangement(7, "Center Left - Center - Center Right - Left - Right - Surround Left - Surround Right"); public static ChannelsArrangement CLCRLRSL1SL2SR1SR2 = new ChannelsArrangement(8, "Center Left - Center Right - Left - Right - Surround Left 1 - Surround Left 2 - Surround Right 1 - Surround Right 2"); public static ChannelsArrangement CLCCRLRSLSSR = new ChannelsArrangement(8, "Center Left - Center - Center Right - Left - Right - Surround Left - Surround - Surround Right"); public class ChannelsArrangement { public ChannelsArrangement(int nbChannels, string description) { this.NbChannels = nbChannels; this.Description = description; } public string Description { get; set; } public int NbChannels { get; set; } } } }
namespace ATL { public class ChannelsArrangements { public static ChannelsArrangement Mono = new ChannelsArrangement(1, "Mono (1/0)"); public static ChannelsArrangement Stereo = new ChannelsArrangement(2, "Stereo (2/0)"); public class ChannelsArrangement { private int nbChannels; private string description; public ChannelsArrangement(int nbChannels, string description) { this.nbChannels = nbChannels; this.description = description; } public string Description { get => description; set => description = value; } public int NbChannels { get => nbChannels; set => nbChannels = value; } } } }
mit
C#
9917423b98aba4ee9fc5babe88d7f7182c0a318c
Fix C# sample
quicktype/quicktype,quicktype/quicktype,quicktype/quicktype,quicktype/quicktype,quicktype/quicktype
test/csharp/Program.cs
test/csharp/Program.cs
using System; using System.IO; namespace test { class Program { static void Main(string[] args) { var path = args[0]; var json = File.ReadAllText(path); var qt = QuickType.Convert.FromJson(json); var output = QuickType.Convert.ToJson(qt); Console.WriteLine("{0}", output); } } }
using System; using System.IO; namespace test { class Program { static void Main(string[] args) { var path = args[0]; var json = File.ReadAllText(path); var qt = TopLevel.Convert.FromJson(json); var output = TopLevel.Convert.ToJson(qt); Console.WriteLine("{0}", output); } } }
apache-2.0
C#
6bb7231796728a62edcefe1eb29972879ece0f27
Add INotifyPropertyChanged inheritance.
cube-soft/Cube.Core,cube-soft/Cube.Core
Libraries/Sources/Interfaces.cs
Libraries/Sources/Interfaces.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.ComponentModel; using System.Windows.Input; namespace Cube.Xui { #region IElement /* --------------------------------------------------------------------- */ /// /// IElement /// /// <summary> /// Provides interface of a ViewModel element. /// </summary> /// /* --------------------------------------------------------------------- */ public interface IElement : INotifyPropertyChanged { /* ----------------------------------------------------------------- */ /// /// Text /// /// <summary> /// Gets a text to be displayed in the View. /// </summary> /// /* ----------------------------------------------------------------- */ string Text { get; } /* ----------------------------------------------------------------- */ /// /// Command /// /// <summary> /// Gets or sets a command to be executed by the View. /// </summary> /// /* ----------------------------------------------------------------- */ ICommand Command { get; } } #endregion #region IElement<T> /* --------------------------------------------------------------------- */ /// /// IElement(T) /// /// <summary> /// Provides interface of a ViewModel element with a value. /// </summary> /// /* --------------------------------------------------------------------- */ public interface IElement<T> : IElement { /* ----------------------------------------------------------------- */ /// /// Value /// /// <summary> /// Gets a value to be bound to the View. /// </summary> /// /* ----------------------------------------------------------------- */ T Value { get; set; } } #endregion #region IListItem /* --------------------------------------------------------------------- */ /// /// IListItem /// /// <summary> /// Provides interface to bind to either the ListBoxItem or the /// ListViewItem. /// </summary> /// /* --------------------------------------------------------------------- */ public interface IListItem : INotifyPropertyChanged { /* ----------------------------------------------------------------- */ /// /// IsSelected /// /// <summary> /// Gets or sets a value indicating wheter the item is selected. /// </summary> /// /* ----------------------------------------------------------------- */ bool IsSelected { get; set; } } #endregion }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Windows.Input; namespace Cube.Xui { #region IElement /* --------------------------------------------------------------------- */ /// /// IElement /// /// <summary> /// Provides interface of a ViewModel element. /// </summary> /// /* --------------------------------------------------------------------- */ public interface IElement { /* ----------------------------------------------------------------- */ /// /// Text /// /// <summary> /// Gets a text to be displayed in the View. /// </summary> /// /* ----------------------------------------------------------------- */ string Text { get; } /* ----------------------------------------------------------------- */ /// /// Command /// /// <summary> /// Gets or sets a command to be executed by the View. /// </summary> /// /* ----------------------------------------------------------------- */ ICommand Command { get; } } #endregion #region IElement<T> /* --------------------------------------------------------------------- */ /// /// IElement(T) /// /// <summary> /// Provides interface of a ViewModel element with a value. /// </summary> /// /* --------------------------------------------------------------------- */ public interface IElement<T> : IElement { /* ----------------------------------------------------------------- */ /// /// Value /// /// <summary> /// Gets a value to be bound to the View. /// </summary> /// /* ----------------------------------------------------------------- */ T Value { get; set; } } #endregion #region IListItem /* --------------------------------------------------------------------- */ /// /// IListItem /// /// <summary> /// Provides interface to bind to either the ListBoxItem or the /// ListViewItem. /// </summary> /// /* --------------------------------------------------------------------- */ public interface IListItem { /* ----------------------------------------------------------------- */ /// /// IsSelected /// /// <summary> /// Gets or sets a value indicating wheter the item is selected. /// </summary> /// /* ----------------------------------------------------------------- */ bool IsSelected { get; set; } } #endregion }
apache-2.0
C#
2c463dd94531680bb4e8068c62c97747d284f45b
fix getting folder path
yar229/Mail.Ru-.net-cloud-client
MailRuCloudApi/SplittedCloud.cs
MailRuCloudApi/SplittedCloud.cs
using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MailRuCloudApi { public class SplittedCloud : MailRuCloud { public SplittedCloud(string login, string password) : base(login, password) { } public override async Task<Entry> GetItems(string path) { Entry entry = await base.GetItems(path); var groupedFiles = entry.Files .GroupBy(f => Regex.Match(f.Name, @"(?<name>.*?)(\.wdmrc\.(crc|\d\d\d))?\Z").Groups["name"].Value, file => file) .Select(group => group.Count() == 1 ? group.First() : new SplittedFile(group.ToList())) .ToList(); var newEntry = new Entry(entry.Folders, groupedFiles, entry.FullPath); return newEntry; } } }
using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MailRuCloudApi { public class SplittedCloud : MailRuCloud { public SplittedCloud(string login, string password) : base(login, password) { } public override async Task<Entry> GetItems(string path) { Entry entry = await base.GetItems(path); var groupedFiles = entry.Files .GroupBy(f => Regex.Match(f.Name, @"(?<name>.*?)(\.wdmrc\.(crc|\d\d\d))?\Z").Groups["name"].Value, file => file) .Select(group => group.Count() == 1 ? group.First() : new SplittedFile(group.ToList())) .ToList(); var newEntry = new Entry(entry.Folders, groupedFiles, path); return newEntry; } } }
mit
C#
1aa00247bded28fb7a065fccbd65ba80b133f872
Make sure the Connection string and the OwinAutomaticAppStartup are set in the Web.config #41
SevenSpikes/api-plugin-for-nopcommerce,SevenSpikes/api-plugin-for-nopcommerce
Nop.Plugin.Api/RouteProvider.cs
Nop.Plugin.Api/RouteProvider.cs
using System.Web.Mvc; using System.Web.Routing; using Nop.Web.Framework.Mvc.Routes; using Nop.Plugin.Api.Helpers; using Nop.Core.Infrastructure; namespace Nop.Plugin.Api { public class RouteProvider : IRouteProvider { public void RegisterRoutes(RouteCollection routes) { routes.MapRoute("Plugin.Api.Settings", "Plugins/ApiAdmin/Settings", new { controller = "ApiAdmin", action = "Settings", }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.List", "Plugins/ManageClientsAdmin/List", new { controller = "ManageClientsAdmin", action = "List" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.Create", "Plugins/ManageClientsAdmin/Create", new { controller = "ManageClientsAdmin", action = "Create" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.Edit", "Plugins/ManageClientsAdmin/Edit/{id}", new { controller = "ManageClientsAdmin", action = "Edit", id = @"\d+" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.Delete", "Plugins/ManageClientsAdmin/Delete/{id}", new { controller = "ManageClientsAdmin", action = "Delete" , id = @"\d+" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); IWebConfigMangerHelper webConfigManagerHelper = EngineContext.Current.ContainerManager.Resolve<IWebConfigMangerHelper>(); // make sure the connection string is added in the Web.config webConfigManagerHelper.AddConnectionString(); // make sure the OwinAutomaticAppStartup is enabled in the Web.config webConfigManagerHelper.AddConfiguration(); } public int Priority { get { return 0; } } } }
using System.Web.Mvc; using System.Web.Routing; using Nop.Web.Framework.Mvc.Routes; namespace Nop.Plugin.Api { public class RouteProvider : IRouteProvider { public void RegisterRoutes(RouteCollection routes) { routes.MapRoute("Plugin.Api.Settings", "Plugins/ApiAdmin/Settings", new { controller = "ApiAdmin", action = "Settings", }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.List", "Plugins/ManageClientsAdmin/List", new { controller = "ManageClientsAdmin", action = "List" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.Create", "Plugins/ManageClientsAdmin/Create", new { controller = "ManageClientsAdmin", action = "Create" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.Edit", "Plugins/ManageClientsAdmin/Edit/{id}", new { controller = "ManageClientsAdmin", action = "Edit", id = @"\d+" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); routes.MapRoute("Plugin.Api.ManageClients.Delete", "Plugins/ManageClientsAdmin/Delete/{id}", new { controller = "ManageClientsAdmin", action = "Delete" , id = @"\d+" }, new[] { "Nop.Plugin.Api.Controllers.Admin" } ); } public int Priority { get { return 0; } } } }
mit
C#
2ba1ad1b17ca27220132976fe06287d678015892
Add security stamp validation
derrickcreamer/NoteFolder,derrickcreamer/NoteFolder
NoteFolder/App_Start/Startup.cs
NoteFolder/App_Start/Startup.cs
using System; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Owin; using NoteFolder.Models; namespace NoteFolder { public partial class Startup { public void Configuration(IAppBuilder app) { app.CreatePerOwinContext<AppDbContext>(AppDbContext.Create); app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Login"), ExpireTimeSpan = TimeSpan.FromDays(7), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<AppUserManager, User> ( validateInterval: TimeSpan.FromSeconds(30), regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie) ) } }); } } }
using System; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.AspNet.Identity; using Owin; using NoteFolder.Models; namespace NoteFolder { public partial class Startup { public void Configuration(IAppBuilder app) { app.CreatePerOwinContext<AppDbContext>(AppDbContext.Create); app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Login"), ExpireTimeSpan = TimeSpan.FromDays(7) }); } } }
mit
C#
08aa5f0ebf17ff22c864837919cf63b416e481e7
Update RemoveRedundantEqualityTests.cs
stephentoub/roslyn,AmadeusW/roslyn,tmat/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,tmat/roslyn,physhi/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,heejaechang/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,aelij/roslyn,ErikSchierboom/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,eriawan/roslyn,bartdesmet/roslyn,weltkante/roslyn,bartdesmet/roslyn,stephentoub/roslyn,heejaechang/roslyn,tmat/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,brettfo/roslyn,diryboy/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,aelij/roslyn,physhi/roslyn,panopticoncentral/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,gafter/roslyn,eriawan/roslyn,weltkante/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,brettfo/roslyn,aelij/roslyn,brettfo/roslyn,sharwell/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,diryboy/roslyn,AlekseyTs/roslyn
src/Analyzers/CSharp/Tests/RemoveRedundantEquality/RemoveRedundantEqualityTests.cs
src/Analyzers/CSharp/Tests/RemoveRedundantEquality/RemoveRedundantEqualityTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.RemoveRedundantEquality; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = CSharpCodeFixVerifier< CSharpRemoveRedundantEqualityDiagnosticAnalyzer, RemoveRedundantEqualityCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveRedundantEquality { public class RemoveRedundantEqualityTests { [Fact] public async Task TestSimpleCaseForEqualsTrue() { var code = @" public class C { public void M1(bool x) { return x == true; } }"; var fixedCode = @" public class C { public voi M1(bool x) { return x; } } "; await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } [Fact] public async Task TestSimpleCaseForEqualsFalse_NoDiagnostics() { var code = @" public class C { public void M1(bool x) { return x == false; } }"; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task TestSimpleCaseForNotEqualsFalse() { var code = @" public class C { public void M1(bool x) { return x != false; } }"; var fixedCode = @" public class C { public voi M1(bool x) { return x; } } "; await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } [Fact] public async Task TestSimpleCaseForNotEqualsTrue_NoDiagnostics() { var code = @" public class C { public void M1(bool x) { return x != true; } }"; await VerifyCS.VerifyAnalyzerAsync(code); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.RemoveRedundantEquality; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = CSharpCodeFixVerifier< CSharpRemoveRedundantEqualityDiagnosticAnalyzer, RemoveRedundantEqualityCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveRedundantEquality { public class RemoveRedundantEqualityTests { [Fact] public async Task TestSimpleCaseForEqualsTrue() { var code = @" public class C { public void M1(bool x) { return x == true; } }"; var fixedCode = @" public class C { public voi M1(bool x) { return x; } } "; await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } [Fact] public async Task TestSimpleCaseForEqualsFalse_NoDiagnostics() { var code = @" public class C { public void M1(bool x) { return x == false; } }"; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task TestSimpleCaseForNotEqualsFalse() { var code = @" public class C { public void M1(bool x) { return x != false; } }"; var fixedCode = @" public class C { public voi M1(bool x) { return x; } } "; await VerifyCS.VerifyCodeFixAsync(code, fixedCode); } [Fact] public async Task TestSimpleCaseForNotEqualsTrue_NoDiagnostics() { var code = @" public class C { public void M1(bool x) { return x != true; } }"; await VerifyCS.VerifyAnalyzerAsync(code); } } }
mit
C#
cde429c47f66391942b4fa939275dc72240b01aa
Validate nullable attributes are set
meziantou/Meziantou.Framework,meziantou/Meziantou.Framework,meziantou/Meziantou.Framework,meziantou/Meziantou.Framework
tests/Meziantou.Framework.ResxSourceGenerator.GeneratorTests/ResxGeneratorTests.cs
tests/Meziantou.Framework.ResxSourceGenerator.GeneratorTests/ResxGeneratorTests.cs
#pragma warning disable CA1304 #pragma warning disable MA0011 using System.Globalization; using TestUtilities; using Xunit; namespace Meziantou.Framework.ResxSourceGenerator.GeneratorTests; public class ResxGeneratorTests { [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)] public void FormatString() { CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); Assert.Equal("Hello world!", Resource1.FormatHello("world")); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr"); Assert.Equal("Bonjour le monde!", Resource1.FormatHello("le monde")); } [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)] public void StringValue() { CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); Assert.Equal("value", Resource1.Sample); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr"); Assert.Equal("valeur", Resource1.Sample); } #nullable enable [Fact] public void GetStringWithDefaultValue() { // Ensure the value is not nullable Assert.Equal(3, Resource1.GetString("UnknownValue", defaultValue: "abc").Length); } #nullable disable [Fact] public void TextFile() { Assert.Equal("test", Resource1.TextFile1); } [Fact] public void BinaryFile() { Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, Resource1.Image1![0..8]); } }
#pragma warning disable CA1304 #pragma warning disable MA0011 using System.Globalization; using TestUtilities; using Xunit; namespace Meziantou.Framework.ResxSourceGenerator.GeneratorTests; public class ResxGeneratorTests { [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)] public void FormatString() { CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); Assert.Equal("Hello world!", Resource1.FormatHello("world")); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr"); Assert.Equal("Bonjour le monde!", Resource1.FormatHello("le monde")); } [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)] public void StringValue() { CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); Assert.Equal("value", Resource1.Sample); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr"); Assert.Equal("valeur", Resource1.Sample); } [Fact] public void TextFile() { Assert.Equal("test", Resource1.TextFile1); } [Fact] public void BinaryFile() { Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, Resource1.Image1![0..8]); } }
mit
C#
e058defbc11f3a4cfb9e363ce6aaec8408fb194a
Make DataGridHelper internal
jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Perspex,Perspex/Perspex,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia
src/Avalonia.Controls.DataGrid/Utils/DataGridHelper.cs
src/Avalonia.Controls.DataGrid/Utils/DataGridHelper.cs
namespace Avalonia.Controls { internal static class DataGridHelper { internal static void SyncColumnProperty<T>(AvaloniaObject column, AvaloniaObject content, AvaloniaProperty<T> property) { SyncColumnProperty(column, content, property, property); } internal static void SyncColumnProperty<T>(AvaloniaObject column, AvaloniaObject content, AvaloniaProperty<T> contentProperty, AvaloniaProperty<T> columnProperty) { if (!column.IsSet(columnProperty)) { content.ClearValue(contentProperty); } else { content.SetValue(contentProperty, column.GetValue(columnProperty)); } } } }
namespace Avalonia.Controls { public static class DataGridHelper { internal static void SyncColumnProperty<T>(AvaloniaObject column, AvaloniaObject content, AvaloniaProperty<T> property) { SyncColumnProperty(column, content, property, property); } internal static void SyncColumnProperty<T>(AvaloniaObject column, AvaloniaObject content, AvaloniaProperty<T> contentProperty, AvaloniaProperty<T> columnProperty) { if (!column.IsSet(columnProperty)) { content.ClearValue(contentProperty); } else { content.SetValue(contentProperty, column.GetValue(columnProperty)); } } } }
mit
C#
da864799e352775e4304a5d5543d61f52a2eb111
Add possibility to add department and DepartmentAddDto
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
src/Diploms.WebUI/Controllers/DepartmentsController.cs
src/Diploms.WebUI/Controllers/DepartmentsController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Diploms.Core; namespace Diploms.WebUI.Controllers { [Route("api/[controller]")] public class DepartmentsController : Controller { private readonly IRepository<Department> _repository; public DepartmentsController(IRepository<Department> repository) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); } [HttpGet("")] public async Task<IActionResult> GetDepartments() { return Ok(await _repository.Get()); } [HttpPut("add")] public async Task<IActionResult> AddDepartment([FromBody] DepartmentAddDto model) { var department = new Department { Name = model.Name, ShortName = model.ShortName, CreateDate = DateTime.UtcNow }; try { _repository.Add(department); await _repository.SaveChanges(); return Ok(); } catch { return BadRequest(); } } } public class DepartmentAddDto { public string Name { get; set; } public string ShortName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Diploms.Core; namespace Diploms.WebUI.Controllers { [Route("api/[controller]")] public class DepartmentsController : Controller { [HttpGet("")] public IEnumerable<Department> GetDepartments() { return new List<Department>{ new Department { Id = 1, Name = "Информационных систем", ShortName = "ИС" }, new Department { Id = 2, Name = "Информационных технологий и компьютерных систем", ShortName = "ИТиКС" }, new Department { Id = 3, Name = "Управление в технических системах", ShortName = "УВТ" } }; } } }
mit
C#
eb714c777043250bb3c929669e11f49eca4459c8
Make the test data more realistic
onovotny/GitVersion,dpurge/GitVersion,dpurge/GitVersion,dazinator/GitVersion,ParticularLabs/GitVersion,GitTools/GitVersion,pascalberger/GitVersion,pascalberger/GitVersion,GitTools/GitVersion,asbjornu/GitVersion,onovotny/GitVersion,dpurge/GitVersion,Philo/GitVersion,FireHost/GitVersion,ermshiperete/GitVersion,JakeGinnivan/GitVersion,onovotny/GitVersion,DanielRose/GitVersion,JakeGinnivan/GitVersion,JakeGinnivan/GitVersion,JakeGinnivan/GitVersion,gep13/GitVersion,ermshiperete/GitVersion,ermshiperete/GitVersion,asbjornu/GitVersion,DanielRose/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,pascalberger/GitVersion,ParticularLabs/GitVersion,dpurge/GitVersion,dazinator/GitVersion,Philo/GitVersion,FireHost/GitVersion,DanielRose/GitVersion
src/GitVersionCore.Tests/BuildServers/VsoAgentTests.cs
src/GitVersionCore.Tests/BuildServers/VsoAgentTests.cs
using System; using GitVersion; using GitVersionCore.Tests; using NUnit.Framework; using Shouldly; [TestFixture] public class VsoAgentTests { string key = "BUILD_BUILDNUMBER"; [SetUp] public void SetEnvironmentVariableForTest() { Environment.SetEnvironmentVariable(key, "Some Build_Value $(GitVersion_FullSemVer) 20151310.3 $(UnknownVar) Release", EnvironmentVariableTarget.Process); } [TearDown] public void ClearEnvironmentVariableForTest() { Environment.SetEnvironmentVariable(key, null, EnvironmentVariableTarget.Process); } [Test] public void Develop_branch() { var versionBuilder = new VsoAgent(); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); var vsVersion = versionBuilder.GenerateSetVersionMessage(vars); vsVersion.ShouldBe("##vso[build.updatebuildnumber]Some Build_Value 0.0.0-Unstable4 20151310.3 $(UnknownVar) Release"); } [Test] public void EscapeValues() { var versionBuilder = new VsoAgent(); var vsVersion = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); vsVersion[0].ShouldBe("##vso[task.setvariable variable=GitVersion.Foo;]0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); } }
using System; using GitVersion; using GitVersionCore.Tests; using NUnit.Framework; using Shouldly; [TestFixture] public class VsoAgentTests { string key = "BUILD_BUILDNUMBER"; [SetUp] public void SetEnvironmentVariableForTest() { Environment.SetEnvironmentVariable(key, "Some Build_Value $(GitVersion_FullSemVer)", EnvironmentVariableTarget.Process); } [TearDown] public void ClearEnvironmentVariableForTest() { Environment.SetEnvironmentVariable(key, null, EnvironmentVariableTarget.Process); } [Test] public void Develop_branch() { var versionBuilder = new VsoAgent(); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); var vsVersion = versionBuilder.GenerateSetVersionMessage(vars); vsVersion.ShouldBe("##vso[build.updatebuildnumber]Some Build_Value 0.0.0-Unstable4"); } [Test] public void EscapeValues() { var versionBuilder = new VsoAgent(); var vsVersion = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); vsVersion[0].ShouldBe("##vso[task.setvariable variable=GitVersion.Foo;]0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); } }
mit
C#
74dbe48598b11320bc95d13905b48adf17f1c80d
fix bug in LoggerFileScope
dotnet/docfx,superyyrrzz/docfx,LordZoltan/docfx,superyyrrzz/docfx,sergey-vershinin/docfx,DuncanmaMSFT/docfx,pascalberger/docfx,superyyrrzz/docfx,LordZoltan/docfx,928PJY/docfx,dotnet/docfx,pascalberger/docfx,sergey-vershinin/docfx,sergey-vershinin/docfx,hellosnow/docfx,DuncanmaMSFT/docfx,pascalberger/docfx,LordZoltan/docfx,dotnet/docfx,hellosnow/docfx,928PJY/docfx,LordZoltan/docfx,928PJY/docfx,hellosnow/docfx
src/Microsoft.DocAsCode.EntityModel/LoggerFileScope.cs
src/Microsoft.DocAsCode.EntityModel/LoggerFileScope.cs
namespace Microsoft.DocAsCode.EntityModel { using System; using System.Runtime.Remoting.Messaging; public sealed class LoggerFileScope : IDisposable { private readonly string _originFileName; public LoggerFileScope(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("Phase name cannot be null or white space.", nameof(fileName)); } _originFileName = CallContext.LogicalGetData(nameof(LoggerFileScope)) as string; if (_originFileName == null) { CallContext.LogicalSetData(nameof(LoggerFileScope), fileName); } else { CallContext.LogicalSetData(nameof(LoggerFileScope), fileName); } } public void Dispose() { CallContext.LogicalSetData(nameof(LoggerFileScope), _originFileName); } internal static string GetFileName() { return CallContext.LogicalGetData(nameof(LoggerFileScope)) as string; } } }
namespace Microsoft.DocAsCode.EntityModel { using System; using System.Runtime.Remoting.Messaging; public sealed class LoggerFileScope : IDisposable { private readonly string _originFileName; public LoggerFileScope(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("Phase name cannot be null or white space.", nameof(fileName)); } _originFileName = CallContext.LogicalGetData(nameof(LoggerFileScope)) as string; if (_originFileName == null) { CallContext.LogicalSetData(nameof(LoggerFileScope), fileName); } else { CallContext.LogicalSetData(nameof(LoggerFileScope), fileName); } } public void Dispose() { CallContext.LogicalSetData(nameof(LoggerPhaseScope), _originFileName); } internal static string GetFileName() { return CallContext.LogicalGetData(nameof(LoggerPhaseScope)) as string; } } }
mit
C#
f6c649ef0f8504a7c13b514b8cfbdbd79a5c4211
allow to make project without .ignores file
Erdroy/MySync,Erdroy/MySync,Erdroy/MySync
src/MySync.Shared/MySync.Shared/Utilities/FileUtils.cs
src/MySync.Shared/MySync.Shared/Utilities/FileUtils.cs
// MySync © 2016-2017 Damian 'Erdroy' Korczowski namespace MySync.Shared.Utilities { /// <summary> /// File utils class. /// </summary> public static class FileUtils { /// <summary> /// Checks if file is excluded using exclusion list. /// </summary> /// <param name="fileName">The file to check.</param> /// <param name="exclusions">The exclusion list.</param> /// <returns>True when file is excluded.</returns> public static bool IsExcluded(string fileName, string[] exclusions) { fileName = fileName.Replace("\\", "/"); if (exclusions == null || exclusions.Length == 0) return false; foreach (var exclude in exclusions) { if (exclude.Length < 2) // validate continue; // check directory exclude if ((exclude.EndsWith("/") || exclude.EndsWith("*")) && fileName.StartsWith(exclude.Replace("*", ""))) return true; // check extension exclude if (exclude.StartsWith("*.") && fileName.EndsWith(exclude.Replace("*", ""))) return true; // check file exclude if (fileName == exclude) return true; } return false; } } }
// MySync © 2016-2017 Damian 'Erdroy' Korczowski namespace MySync.Shared.Utilities { /// <summary> /// File utils class. /// </summary> public static class FileUtils { /// <summary> /// Checks if file is excluded using exclusion list. /// </summary> /// <param name="fileName">The file to check.</param> /// <param name="exclusions">The exclusion list.</param> /// <returns>True when file is excluded.</returns> public static bool IsExcluded(string fileName, string[] exclusions) { fileName = fileName.Replace("\\", "/"); foreach (var exclude in exclusions) { if (exclude.Length < 2) // validate continue; // check directory exclude if ((exclude.EndsWith("/") || exclude.EndsWith("*")) && fileName.StartsWith(exclude.Replace("*", ""))) return true; // check extension exclude if (exclude.StartsWith("*.") && fileName.EndsWith(exclude.Replace("*", ""))) return true; // check file exclude if (fileName == exclude) return true; } return false; } } }
agpl-3.0
C#
beaefd3cb1f82cc5670610f0b61469b4a8a6320f
Test for large binary blobs (more than 8000 bytes), just to be sure it works.
livioc/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core
src/NHibernate.Test/TypesTest/BinaryBlobTypeFixture.cs
src/NHibernate.Test/TypesTest/BinaryBlobTypeFixture.cs
using System; using NHibernate; using NUnit.Framework; namespace NHibernate.Test.TypesTest { /// <summary> /// Summary description for BinaryBlobTypeFixture. /// </summary> [TestFixture] public class BinaryBlobTypeFixture : TypeFixtureBase { protected override string TypeName { get { return "BinaryBlob"; } } [Test] public void ReadWrite() { ISession s = OpenSession(); BinaryBlobClass b = new BinaryBlobClass(); b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz"); s.Save(b); s.Flush(); s.Close(); s = OpenSession(); b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id ); ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz") , b.BinaryBlob ); s.Delete( b ); s.Flush(); s.Close(); } [Test] public void ReadWriteLargeBlob() { ISession s = OpenSession(); BinaryBlobClass b = new BinaryBlobClass(); b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes(new string('T', 10000)); s.Save(b); s.Flush(); s.Close(); s = OpenSession(); b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id ); ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes(new string('T', 10000)) , b.BinaryBlob ); s.Delete( b ); s.Flush(); s.Close(); } } }
using System; using NHibernate; using NUnit.Framework; namespace NHibernate.Test.TypesTest { /// <summary> /// Summary description for BinaryBlobTypeFixture. /// </summary> [TestFixture] public class BinaryBlobTypeFixture : TypeFixtureBase { protected override string TypeName { get { return "BinaryBlob"; } } [Test] public void ReadWrite() { ISession s = OpenSession(); BinaryBlobClass b = new BinaryBlobClass(); b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz"); s.Save(b); s.Flush(); s.Close(); s = OpenSession(); b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id ); ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz") , b.BinaryBlob ); s.Delete( b ); s.Flush(); s.Close(); } } }
lgpl-2.1
C#
6ab4f1d9ff33788cfb15f930f2d48974cae93651
Rename status messages from Knots to Full Node
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/BitcoinCore/Monitoring/RpcStatus.cs
WalletWasabi/BitcoinCore/Monitoring/RpcStatus.cs
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.BitcoinCore.Monitoring { public class RpcStatus : IEquatable<RpcStatus> { public static RpcStatus Unresponsive = new RpcStatus(false, 0, 0, 0); private RpcStatus(bool success, ulong headers, ulong blocks, int peersCount) { Synchronized = false; if (success) { var diff = headers - blocks; if (peersCount == 0) { Status = "Full Node is connecting..."; } else if (diff == 0) { Synchronized = true; Status = "Full Node is synchronized"; } else { Status = $"Full Node is downloading {diff} blocks..."; } } else { Status = "Full Node is unresponsive"; } Success = success; Headers = headers; Blocks = blocks; PeersCount = peersCount; } public string Status { get; } public bool Success { get; } public ulong Headers { get; } public ulong Blocks { get; } public int PeersCount { get; } public bool Synchronized { get; } public static RpcStatus Responsive(ulong headers, ulong blocks, int peersCount) => new RpcStatus(true, headers, blocks, peersCount); public override string ToString() => Status; #region EqualityAndComparison public override bool Equals(object obj) => Equals(obj as RpcStatus); public bool Equals(RpcStatus other) => this == other; public override int GetHashCode() => Status.GetHashCode(); public static bool operator ==(RpcStatus x, RpcStatus y) => y?.Status == x?.Status; public static bool operator !=(RpcStatus x, RpcStatus y) => !(x == y); #endregion EqualityAndComparison } }
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.BitcoinCore.Monitoring { public class RpcStatus : IEquatable<RpcStatus> { public static RpcStatus Unresponsive = new RpcStatus(false, 0, 0, 0); private RpcStatus(bool success, ulong headers, ulong blocks, int peersCount) { Synchronized = false; if (success) { var diff = headers - blocks; if (peersCount == 0) { Status = "Bitcoin Knots is connecting..."; } else if (diff == 0) { Synchronized = true; Status = "Bitcoin Knots is synchronized"; } else { Status = $"Bitcoin Knots is downloading {diff} blocks..."; } } else { Status = "Bitcoin Knots is unresponsive"; } Success = success; Headers = headers; Blocks = blocks; PeersCount = peersCount; } public string Status { get; } public bool Success { get; } public ulong Headers { get; } public ulong Blocks { get; } public int PeersCount { get; } public bool Synchronized { get; } public static RpcStatus Responsive(ulong headers, ulong blocks, int peersCount) => new RpcStatus(true, headers, blocks, peersCount); public override string ToString() => Status; #region EqualityAndComparison public override bool Equals(object obj) => Equals(obj as RpcStatus); public bool Equals(RpcStatus other) => this == other; public override int GetHashCode() => Status.GetHashCode(); public static bool operator ==(RpcStatus x, RpcStatus y) => y?.Status == x?.Status; public static bool operator !=(RpcStatus x, RpcStatus y) => !(x == y); #endregion EqualityAndComparison } }
mit
C#
d61f4aeb8a043eca327f605075ebb732aaf2afde
Update GetCategoryResultJson.cs
jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,down4u/WeiXinMPSDK,down4u/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,down4u/WeiXinMPSDK,JeffreySu/WeiXinMPSDK
src/Senparc.Weixin.Open/Senparc.Weixin.Open/WxaAPIs/Code/CodeJson/GetCategoryResultJson.cs
src/Senparc.Weixin.Open/Senparc.Weixin.Open/WxaAPIs/Code/CodeJson/GetCategoryResultJson.cs
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2017 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2017 Senparc 文件名:GetCategoryResultJson.cs 文件功能描述:各级类目名称和ID返回结果 创建标识:Senparc - 20170726 ----------------------------------------------------------------*/ using Senparc.Weixin.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Senparc.Weixin.Open.WxaAPIs { [Serializable] public class GetCategoryResultJson : WxJsonResult { public List<CategroyInfo> category_list { get; set; } } [Serializable] public class CategroyInfo { /// <summary> /// 一级类目名称 /// </summary> public string first_class { get; set; } /// <summary> /// 二级类目名称 /// </summary> public string second_class { get; set; } /// <summary> /// 三级类目名称 /// </summary> public string third_class { get; set; } /// <summary> /// 一级类目的ID编号 /// </summary> public int first_id { get; set; } /// <summary> /// 二级类目的ID编号 /// </summary> public int second_id { get; set; } /// <summary> /// 三级类目的ID编号 /// </summary> public int third_id { get; set; } } }
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2017 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2017 Senparc 文件名:GetCategoryResultJson.cs 文件功能描述:各级类目名称和ID返回结果 创建标识:Senparc - 20170726 ----------------------------------------------------------------*/ using Senparc.Weixin.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Senparc.Weixin.Open.WxaAPIs { public class GetCategoryResultJson : WxJsonResult { public List<CategroyInfo> category_list { get; set; } } public class CategroyInfo { /// <summary> /// 一级类目名称 /// </summary> public string first_class { get; set; } /// <summary> /// 二级类目名称 /// </summary> public string second_class { get; set; } /// <summary> /// 三级类目名称 /// </summary> public string third_class { get; set; } /// <summary> /// 一级类目的ID编号 /// </summary> public int first_id { get; set; } /// <summary> /// 二级类目的ID编号 /// </summary> public int second_id { get; set; } /// <summary> /// 三级类目的ID编号 /// </summary> public int third_id { get; set; } } }
apache-2.0
C#
1f248b90ccef86e9030fe1001f085f1222b571cf
Set FTBPass to true by default
peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework
osu.Framework/Configuration/FrameworkDebugConfig.cs
osu.Framework/Configuration/FrameworkDebugConfig.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Runtime; using osu.Framework.Caching; namespace osu.Framework.Configuration { public class FrameworkDebugConfigManager : IniConfigManager<DebugSetting> { protected override string Filename => null; public FrameworkDebugConfigManager() : base(null) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(DebugSetting.ActiveGCMode, GCLatencyMode.SustainedLowLatency); Set(DebugSetting.BypassCaching, false).ValueChanged += delegate { StaticCached.BypassCache = Get<bool>(DebugSetting.BypassCaching); }; Set(DebugSetting.FTBPass, true); } } public enum DebugSetting { ActiveGCMode, BypassCaching, FTBPass } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Runtime; using osu.Framework.Caching; namespace osu.Framework.Configuration { public class FrameworkDebugConfigManager : IniConfigManager<DebugSetting> { protected override string Filename => null; public FrameworkDebugConfigManager() : base(null) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); Set(DebugSetting.ActiveGCMode, GCLatencyMode.SustainedLowLatency); Set(DebugSetting.BypassCaching, false).ValueChanged += delegate { StaticCached.BypassCache = Get<bool>(DebugSetting.BypassCaching); }; Set(DebugSetting.FTBPass, false); } } public enum DebugSetting { ActiveGCMode, BypassCaching, FTBPass } }
mit
C#
6c478a5c55f9c860376fed426fa04bd4301ca93f
Copy over default repository actions if empty on Windows
awaescher/RepoZ,awaescher/RepoZ
RepoZ.Api.Common/Git/RepositoryActions/DefaultRepositoryActionConfigurationStore.cs
RepoZ.Api.Common/Git/RepositoryActions/DefaultRepositoryActionConfigurationStore.cs
using Newtonsoft.Json; using RepoZ.Api.IO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace RepoZ.Api.Common.Git { public class DefaultRepositoryActionConfigurationStore : FileRepositoryStore, IRepositoryActionConfigurationStore { private object _lock = new object(); public DefaultRepositoryActionConfigurationStore(IErrorHandler errorHandler, IAppDataPathProvider appDataPathProvider) : base(errorHandler) { AppDataPathProvider = appDataPathProvider ?? throw new ArgumentNullException(nameof(appDataPathProvider)); } public override string GetFileName() => Path.Combine(AppDataPathProvider.GetAppDataPath(), "RepositoryActions.json"); public void Preload() { lock (_lock) { if (!File.Exists(GetFileName())) { if (!TryCopyDefaultJsonFile()) { RepositoryActionConfiguration = new RepositoryActionConfiguration(); RepositoryActionConfiguration.State = RepositoryActionConfiguration.LoadState.None; return; } } try { var lines = Get()?.ToList() ?? new List<string>(); var json = string.Join(Environment.NewLine, lines.Select(RemoveComment)); RepositoryActionConfiguration = JsonConvert.DeserializeObject<RepositoryActionConfiguration>(json) ?? new RepositoryActionConfiguration(); RepositoryActionConfiguration.State = RepositoryActionConfiguration.LoadState.Ok; } catch (Exception ex) { RepositoryActionConfiguration = new RepositoryActionConfiguration(); RepositoryActionConfiguration.State = RepositoryActionConfiguration.LoadState.Error; RepositoryActionConfiguration.LoadError = ex.Message; } } } private bool TryCopyDefaultJsonFile() { var defaultFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "RepositoryActions.json"); var targetFile = GetFileName(); try { File.Copy(defaultFile, targetFile); } catch { /* lets ignore errors here, we just want to know if if worked or not by checking the file existence */ } return File.Exists(targetFile); } private string RemoveComment(string line) { var indexOfComment = line.IndexOf('#'); return indexOfComment < 0 ? line : line.Substring(0, indexOfComment); } public RepositoryActionConfiguration RepositoryActionConfiguration { get; private set; } public IAppDataPathProvider AppDataPathProvider { get; } } }
using Newtonsoft.Json; using RepoZ.Api.IO; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RepoZ.Api.Common.Git { public class DefaultRepositoryActionConfigurationStore : FileRepositoryStore, IRepositoryActionConfigurationStore { private object _lock = new object(); public DefaultRepositoryActionConfigurationStore(IErrorHandler errorHandler, IAppDataPathProvider appDataPathProvider) : base(errorHandler) { AppDataPathProvider = appDataPathProvider ?? throw new ArgumentNullException(nameof(appDataPathProvider)); } public override string GetFileName() => Path.Combine(AppDataPathProvider.GetAppDataPath(), "RepositoryActions.json"); public void Preload() { lock (_lock) { if (!File.Exists(GetFileName())) { RepositoryActionConfiguration = new RepositoryActionConfiguration(); RepositoryActionConfiguration.State = RepositoryActionConfiguration.LoadState.None; return; } try { var lines = Get()?.ToList() ?? new List<string>(); var json = string.Join(Environment.NewLine, lines.Select(RemoveComment)); RepositoryActionConfiguration = JsonConvert.DeserializeObject<RepositoryActionConfiguration>(json); RepositoryActionConfiguration.State = RepositoryActionConfiguration.LoadState.Ok; } catch (Exception ex) { RepositoryActionConfiguration = new RepositoryActionConfiguration(); RepositoryActionConfiguration.State = RepositoryActionConfiguration.LoadState.Error; RepositoryActionConfiguration.LoadError = ex.Message; } } } private string RemoveComment(string line) { var indexOfComment = line.IndexOf('#'); return indexOfComment < 0 ? line : line.Substring(0, indexOfComment); } public RepositoryActionConfiguration RepositoryActionConfiguration { get; private set; } public IAppDataPathProvider AppDataPathProvider { get; } } }
mit
C#
14163f3276664e4d908f11886ec9bae867368968
make validator static
StanJav/language-ext,StefanBertels/language-ext,louthy/language-ext
Samples/Contoso/Contoso.Application/Departments/Commands/CreateDepartmentHandler.cs
Samples/Contoso/Contoso.Application/Departments/Commands/CreateDepartmentHandler.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Contoso.Core; using Contoso.Core.Interfaces.Repositories; using LanguageExt; using static LanguageExt.Prelude; using MediatR; using static Contoso.Validators; using Contoso.Core.Domain; namespace Contoso.Application.Departments.Commands { public class CreateDepartmentHandler : IRequestHandler<CreateDepartment, Either<Error, int>> { private readonly IDepartmentRepository _departmentRepository; private readonly IInstructorRepository _instructorRepository; public CreateDepartmentHandler(IDepartmentRepository departmentRepository, IInstructorRepository instructorRepository) { _departmentRepository = departmentRepository; _instructorRepository = instructorRepository; } public async Task<Either<Error, int>> Handle(CreateDepartment request, CancellationToken cancellationToken) => await (await Validate(request)) .Map(_departmentRepository.Add) .MatchAsync<Either<Error, int>>( SuccAsync: async d => Right(await d), Fail: errors => errors.Join()); private async Task<Validation<Error, Department>> Validate(CreateDepartment create) => (ValidateDepartmentName(create), ValidateBudget(create), MustStartInFuture(create), await InstructorIdMustExist(create)) .Apply((n, b, s, i) => new Department { Name = n, Budget = b, StartDate = s, AdministratorId = i }); private Task<Validation<Error, int>> InstructorIdMustExist(CreateDepartment createDepartment) => _instructorRepository.Get(createDepartment.AdministratorId).Match( Some: s => s.InstructorId, None: () => Fail<Error, int>($"Administrator Id {createDepartment.AdministratorId} does not exist")); private static Validation<Error, DateTime> MustStartInFuture(CreateDepartment createDepartment) => createDepartment.StartDate > DateTime.UtcNow ? Success<Error, DateTime>(createDepartment.StartDate) : Fail<Error, DateTime>($"Start date must not be in the past"); private static Validation<Error, decimal> ValidateBudget(CreateDepartment createDepartment) => AtLeast(0M)(createDepartment.Budget).Bind(AtMost(999999)); private static Validation<Error, string> ValidateDepartmentName(CreateDepartment createDepartment) => NotEmpty(createDepartment.Name).Bind(NotLongerThan(50)); } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Contoso.Core; using Contoso.Core.Interfaces.Repositories; using LanguageExt; using static LanguageExt.Prelude; using MediatR; using static Contoso.Validators; using Contoso.Core.Domain; namespace Contoso.Application.Departments.Commands { public class CreateDepartmentHandler : IRequestHandler<CreateDepartment, Either<Error, int>> { private readonly IDepartmentRepository _departmentRepository; private readonly IInstructorRepository _instructorRepository; public CreateDepartmentHandler(IDepartmentRepository departmentRepository, IInstructorRepository instructorRepository) { _departmentRepository = departmentRepository; _instructorRepository = instructorRepository; } public async Task<Either<Error, int>> Handle(CreateDepartment request, CancellationToken cancellationToken) => await (await Validate(request)) .Map(_departmentRepository.Add) .MatchAsync<Either<Error, int>>( SuccAsync: async d => Right(await d), Fail: errors => errors.Join()); private async Task<Validation<Error, Department>> Validate(CreateDepartment create) => (ValidateDepartmentName(create), ValidateBudget(create), MustStartInFuture(create), await InstructorIdMustExist(create)) .Apply((n, b, s, i) => new Department { Name = n, Budget = b, StartDate = s, AdministratorId = i }); private Task<Validation<Error, int>> InstructorIdMustExist(CreateDepartment createDepartment) => _instructorRepository.Get(createDepartment.AdministratorId).Match( Some: s => s.InstructorId, None: () => Fail<Error, int>($"Administrator Id {createDepartment.AdministratorId} does not exist")); private Validation<Error, DateTime> MustStartInFuture(CreateDepartment createDepartment) => createDepartment.StartDate > DateTime.UtcNow ? Success<Error, DateTime>(createDepartment.StartDate) : Fail<Error, DateTime>($"Start date must not be in the past"); private static Validation<Error, decimal> ValidateBudget(CreateDepartment createDepartment) => AtLeast(0M)(createDepartment.Budget).Bind(AtMost(999999)); private static Validation<Error, string> ValidateDepartmentName(CreateDepartment createDepartment) => NotEmpty(createDepartment.Name).Bind(NotLongerThan(50)); } }
mit
C#
724d872ef59662568e70cd3350790630f0883f55
Order is everything in life
Willster419/RelhaxModpack,Willster419/RelhaxModpack,Willster419/RelicModManager
RelicModManager/DatabaseObject.cs
RelicModManager/DatabaseObject.cs
using System; using System.Collections.Generic; namespace RelhaxModpack { public abstract class DatabaseObject { public string name { get; set; } //the developer's version of the mod public string version { get; set; } public string zipFile { get; set; } public long timestamp { get; set; } public List<Config> configs = new List<Config>(); //the start address of the zip file location. enabled us to use sites that //generate random filenames for ly shared files. public string startAddress { get; set; } //the end address of the zip file location. enables us to use dropbox (?dl=1) public string endAddress { get; set; } public List<LogicalDependnecy> logicalDependencies = new List<LogicalDependnecy>(); public List<Dependency> dependencies = new List<Dependency>(); public List<Media> pictureList = new List<Media>(); public List<ShortCut> shortCuts = new List<ShortCut>(); public string crc { get; set; } public bool enabled { get; set; } //a flag to determine wether or not the mod should be shown public bool visible { get; set; } //later a unique name of the config entry public string packageName { get; set; } //size of the mod zip file public Int64 size { get; set; } public string updateComment { get; set; } public string description { get; set; } public string devURL { get; set; } public List<string> userFiles = new List<string>(); public bool Checked { get; set; } public bool downloadFlag { get; set; } } }
using System; using System.Collections.Generic; namespace RelhaxModpack { public abstract class DatabaseObject { public string name { get; set; } //the developer's version of the mod public string version { get; set; } public string zipFile { get; set; } public long timestamp { get; set; } public List<Config> configs = new List<Config>(); //the start address of the zip file location. enabled us to use sites that //generate random filenames for ly shared files. public string startAddress { get; set; } public List<LogicalDependnecy> logicalDependencies = new List<LogicalDependnecy>(); public List<Dependency> dependencies = new List<Dependency>(); public List<Media> pictureList = new List<Media>(); public List<ShortCut> shortCuts = new List<ShortCut>(); //the end address of the zip file location. enables us to use dropbox (?dl=1) public string endAddress { get; set; } public string crc { get; set; } public bool enabled { get; set; } //a flag to determine wether or not the mod should be shown public bool visible { get; set; } //later a unique name of the config entry public string packageName { get; set; } //size of the mod zip file public Int64 size { get; set; } public string updateComment { get; set; } public string description { get; set; } public string devURL { get; set; } public List<string> userFiles = new List<string>(); public bool Checked { get; set; } public bool downloadFlag { get; set; } } }
apache-2.0
C#
f11245eea49a6f5152c79ec6338eb24775c9cc97
revert RuleCount fix (broken)
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Services/FilterList/MappingProfiles/ListDetailsDtoMappingProfile.cs
src/FilterLists.Services/FilterList/MappingProfiles/ListDetailsDtoMappingProfile.cs
using System.Linq; using AutoMapper; using FilterLists.Services.FilterList.Models; using JetBrains.Annotations; namespace FilterLists.Services.FilterList.MappingProfiles { [UsedImplicitly] public class ListDetailsDtoMappingProfile : Profile { //TODO: fix UpdatedDate and RuleCount public ListDetailsDtoMappingProfile() => CreateMap<Data.Entities.FilterList, ListDetailsDto>() .ForMember(d => d.Languages, c => c.MapFrom(l => l.FilterListLanguages.Select(la => la.Language.Name))) .ForMember(d => d.Maintainers, c => c.MapFrom(l => l.FilterListMaintainers.Select(m => m.Maintainer))) .ForMember(d => d.Tags, c => c.MapFrom(l => l.FilterListTags.Select(m => m.Tag))) .ForMember(d => d.RuleCount, c => c.MapFrom(l => 0)) .ForMember(d => d.UpdatedDate, c => c.MapFrom(l => l.ModifiedDateUtc)); } }
using System.Linq; using AutoMapper; using FilterLists.Services.FilterList.Models; using JetBrains.Annotations; namespace FilterLists.Services.FilterList.MappingProfiles { [UsedImplicitly] public class ListDetailsDtoMappingProfile : Profile { //TODO: fix UpdatedDate and RuleCount public ListDetailsDtoMappingProfile() => CreateMap<Data.Entities.FilterList, ListDetailsDto>() .ForMember(d => d.Languages, c => c.MapFrom(l => l.FilterListLanguages.Select(la => la.Language.Name))) .ForMember(d => d.Maintainers, c => c.MapFrom(l => l.FilterListMaintainers.Select(m => m.Maintainer))) .ForMember(d => d.Tags, c => c.MapFrom(l => l.FilterListTags.Select(m => m.Tag))) .ForMember(d => d.RuleCount, c => c.MapFrom(l => l.Snapshots .OrderByDescending(s => s.CreatedDateUtc) .FirstOrDefault() .SnapshotRules .Count)) .ForMember(d => d.UpdatedDate, c => c.MapFrom(l => l.ModifiedDateUtc)); } }
mit
C#
9296358cbe0f4718e6c352863aa77c68f4f56650
Update ImageProfilePartHandler.cs
Serlead/Orchard,TalaveraTechnologySolutions/Orchard,aaronamm/Orchard,Serlead/Orchard,hbulzy/Orchard,li0803/Orchard,hannan-azam/Orchard,ehe888/Orchard,grapto/Orchard.CloudBust,sfmskywalker/Orchard,AdvantageCS/Orchard,grapto/Orchard.CloudBust,IDeliverable/Orchard,jagraz/Orchard,Lombiq/Orchard,SzymonSel/Orchard,gcsuk/Orchard,omidnasri/Orchard,LaserSrl/Orchard,omidnasri/Orchard,johnnyqian/Orchard,brownjordaninternational/OrchardCMS,sfmskywalker/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,li0803/Orchard,brownjordaninternational/OrchardCMS,IDeliverable/Orchard,neTp9c/Orchard,aaronamm/Orchard,brownjordaninternational/OrchardCMS,Fogolan/OrchardForWork,fassetar/Orchard,OrchardCMS/Orchard,dcinzona/Orchard,jagraz/Orchard,TalaveraTechnologySolutions/Orchard,aaronamm/Orchard,tobydodds/folklife,dcinzona/Orchard,geertdoornbos/Orchard,sfmskywalker/Orchard,hbulzy/Orchard,mvarblow/Orchard,armanforghani/Orchard,geertdoornbos/Orchard,jersiovic/Orchard,vairam-svs/Orchard,jtkech/Orchard,Lombiq/Orchard,jersiovic/Orchard,vairam-svs/Orchard,TalaveraTechnologySolutions/Orchard,Dolphinsimon/Orchard,jersiovic/Orchard,phillipsj/Orchard,phillipsj/Orchard,Fogolan/OrchardForWork,hannan-azam/Orchard,tobydodds/folklife,bedegaming-aleksej/Orchard,LaserSrl/Orchard,TalaveraTechnologySolutions/Orchard,omidnasri/Orchard,SouleDesigns/SouleDesigns.Orchard,jagraz/Orchard,jchenga/Orchard,JRKelso/Orchard,Serlead/Orchard,fassetar/Orchard,jimasp/Orchard,grapto/Orchard.CloudBust,johnnyqian/Orchard,rtpHarry/Orchard,Codinlab/Orchard,fassetar/Orchard,armanforghani/Orchard,sfmskywalker/Orchard,tobydodds/folklife,dmitry-urenev/extended-orchard-cms-v10.1,Praggie/Orchard,grapto/Orchard.CloudBust,IDeliverable/Orchard,grapto/Orchard.CloudBust,JRKelso/Orchard,Dolphinsimon/Orchard,gcsuk/Orchard,jchenga/Orchard,xkproject/Orchard,Fogolan/OrchardForWork,ehe888/Orchard,ehe888/Orchard,Lombiq/Orchard,JRKelso/Orchard,sfmskywalker/Orchard,TalaveraTechnologySolutions/Orchard,johnnyqian/Orchard,sfmskywalker/Orchard,xkproject/Orchard,Dolphinsimon/Orchard,vairam-svs/Orchard,jimasp/Orchard,rtpHarry/Orchard,Dolphinsimon/Orchard,TalaveraTechnologySolutions/Orchard,sfmskywalker/Orchard,Lombiq/Orchard,hbulzy/Orchard,mvarblow/Orchard,OrchardCMS/Orchard,Fogolan/OrchardForWork,neTp9c/Orchard,vairam-svs/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,hbulzy/Orchard,mvarblow/Orchard,SzymonSel/Orchard,ehe888/Orchard,AdvantageCS/Orchard,SouleDesigns/SouleDesigns.Orchard,vairam-svs/Orchard,bedegaming-aleksej/Orchard,armanforghani/Orchard,omidnasri/Orchard,grapto/Orchard.CloudBust,hannan-azam/Orchard,SzymonSel/Orchard,gcsuk/Orchard,hbulzy/Orchard,armanforghani/Orchard,mvarblow/Orchard,rtpHarry/Orchard,li0803/Orchard,Serlead/Orchard,geertdoornbos/Orchard,Serlead/Orchard,OrchardCMS/Orchard,fassetar/Orchard,neTp9c/Orchard,LaserSrl/Orchard,gcsuk/Orchard,neTp9c/Orchard,jimasp/Orchard,li0803/Orchard,rtpHarry/Orchard,abhishekluv/Orchard,TalaveraTechnologySolutions/Orchard,brownjordaninternational/OrchardCMS,hannan-azam/Orchard,phillipsj/Orchard,aaronamm/Orchard,Codinlab/Orchard,omidnasri/Orchard,jagraz/Orchard,jagraz/Orchard,IDeliverable/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,yersans/Orchard,jtkech/Orchard,tobydodds/folklife,geertdoornbos/Orchard,jersiovic/Orchard,yersans/Orchard,Dolphinsimon/Orchard,dcinzona/Orchard,sfmskywalker/Orchard,geertdoornbos/Orchard,abhishekluv/Orchard,dcinzona/Orchard,omidnasri/Orchard,fassetar/Orchard,abhishekluv/Orchard,OrchardCMS/Orchard,IDeliverable/Orchard,mvarblow/Orchard,armanforghani/Orchard,JRKelso/Orchard,gcsuk/Orchard,neTp9c/Orchard,yersans/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,jtkech/Orchard,jchenga/Orchard,aaronamm/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,phillipsj/Orchard,abhishekluv/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,SouleDesigns/SouleDesigns.Orchard,LaserSrl/Orchard,SouleDesigns/SouleDesigns.Orchard,dcinzona/Orchard,xkproject/Orchard,yersans/Orchard,Codinlab/Orchard,SouleDesigns/SouleDesigns.Orchard,phillipsj/Orchard,hannan-azam/Orchard,ehe888/Orchard,yersans/Orchard,Codinlab/Orchard,LaserSrl/Orchard,AdvantageCS/Orchard,tobydodds/folklife,dmitry-urenev/extended-orchard-cms-v10.1,Praggie/Orchard,Lombiq/Orchard,abhishekluv/Orchard,omidnasri/Orchard,johnnyqian/Orchard,Codinlab/Orchard,jchenga/Orchard,rtpHarry/Orchard,abhishekluv/Orchard,jtkech/Orchard,jchenga/Orchard,Praggie/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,bedegaming-aleksej/Orchard,bedegaming-aleksej/Orchard,li0803/Orchard,xkproject/Orchard,SzymonSel/Orchard,jersiovic/Orchard,Praggie/Orchard,SzymonSel/Orchard,brownjordaninternational/OrchardCMS,JRKelso/Orchard,Fogolan/OrchardForWork,johnnyqian/Orchard,jimasp/Orchard,bedegaming-aleksej/Orchard,xkproject/Orchard,AdvantageCS/Orchard,TalaveraTechnologySolutions/Orchard,jimasp/Orchard,Praggie/Orchard,omidnasri/Orchard,tobydodds/folklife,jtkech/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,OrchardCMS/Orchard
src/Orchard.Web/Modules/Orchard.MediaProcessing/Handlers/ImageProfilePartHandler.cs
src/Orchard.Web/Modules/Orchard.MediaProcessing/Handlers/ImageProfilePartHandler.cs
using Orchard.Caching; using Orchard.ContentManagement; using Orchard.ContentManagement.Handlers; using Orchard.Data; using Orchard.MediaProcessing.Models; namespace Orchard.MediaProcessing.Handlers { public class ImageProfilePartHandler : ContentHandler { private readonly ISignals _signals; public ImageProfilePartHandler(IRepository<ImageProfilePartRecord> repository, ISignals signals) { _signals = signals; Filters.Add(StorageFilter.For(repository)); } protected override void Published(PublishContentContext context) { if (context.ContentItem.Has<ImageProfilePart>()) _signals.Trigger("MediaProcessing_Published_" + context.ContentItem.As<ImageProfilePart>().Name); base.Published(context); } } }
using Orchard.Caching; using Orchard.ContentManagement; using Orchard.ContentManagement.Handlers; using Orchard.Data; using Orchard.MediaProcessing.Models; namespace Orchard.MediaProcessing.Handlers { public class ImageProfilePartHandler : ContentHandler { private readonly ISignals _signals; public ImageProfilePartHandler(IRepository<ImageProfilePartRecord> repository, ISignals signals) { _signals = signals; Filters.Add(StorageFilter.For(repository)); } protected override void Published(PublishContentContext context) { _signals.Trigger("MediaProcessing_Published_" + context.ContentItem.As<ImageProfilePart>().Name); base.Published(context); } } }
bsd-3-clause
C#
a31b1095c7208754449fb6a6ffe1a2c572db84bb
Tweak the hello world test
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
tests/hello-world/hello-world.cs
tests/hello-world/hello-world.cs
public static unsafe class Program { public static extern void* malloc(ulong size); public static extern void free(void* data); public static extern int puts(byte* str); public static void FillString(byte* str) { *str = (byte)'h'; *(str + 1) = (byte)'i'; *(str + 2) = (byte)'\0'; } public static int Main() { byte* str = (byte*)malloc(3); FillString(str); puts(str); free((void*)str); return 0; } }
public static unsafe class Program { public static extern void* malloc(ulong size); public static extern void free(void* data); public static extern int puts(byte* str); public static int Main() { byte* str = (byte*)malloc(3); *str = (byte)'h'; *(str + 1) = (byte)'i'; *(str + 2) = (byte)'\0'; puts(str); free((void*)str); return 0; } }
mit
C#
228f87cf4c8fa6415bce8db85db0101fa49fa6c5
Change AssembyInfo
akormachev/gremlins.core
Source/Properties/AssemblyInfo.cs
Source/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Gremlins.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Gremlins.Core")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9365c0b9-9878-4e95-b292-bf561fdf1d65")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.20.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Alice.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Alice.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9365c0b9-9878-4e95-b292-bf561fdf1d65")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.20.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
f944126c237b726292c0900768cad6254ffab8f8
Use TLS v.1.2 for GitHub API call
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade/Util/GitHubReleaseInfoReader.cs
src/Arkivverket.Arkade/Util/GitHubReleaseInfoReader.cs
using System; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using RestSharp; using Serilog; namespace Arkivverket.Arkade.Util { public class GitHubReleaseInfoReader : IReleaseInfoReader { private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType); private readonly RestClient _restClient; private readonly GitHubReleaseInfo _latestReleaseInfo; public GitHubReleaseInfoReader() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; _restClient = new RestClient("https://api.github.com/"); _latestReleaseInfo = ReadGitHubLatestReleaseInfo(); } private GitHubReleaseInfo ReadGitHubLatestReleaseInfo() { var request = new RestRequest("repos/arkivverket/arkade5/releases/latest"); request.AddCookie("logged_in", "no"); IRestResponse<GitHubReleaseInfo> gitHubResponse = _restClient.Execute<GitHubReleaseInfo>(request); if (gitHubResponse.Data == null) Log.Error("Unable to retrieve necessary data from GitHub. Please check your internet connection."); return gitHubResponse.Data; } public Version GetLatestVersion() { if (_latestReleaseInfo?.TagName == null) throw new Exception("Missing or unexpected data from GitHub"); if (!Regex.IsMatch(_latestReleaseInfo.TagName, @"^v\d+.\d+.\d+$")) throw new Exception("Unexpected tag-name format"); string versionNumber = _latestReleaseInfo.TagName.TrimStart('v') + ".0"; return new Version(versionNumber); } private class GitHubReleaseInfo { public string TagName { get; set; } } } }
using System; using System.Reflection; using System.Text.RegularExpressions; using RestSharp; using Serilog; namespace Arkivverket.Arkade.Util { public class GitHubReleaseInfoReader : IReleaseInfoReader { private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType); private readonly RestClient _restClient; private readonly GitHubReleaseInfo _latestReleaseInfo; public GitHubReleaseInfoReader() { _restClient = new RestClient("https://api.github.com/"); _latestReleaseInfo = ReadGitHubLatestReleaseInfo(); } private GitHubReleaseInfo ReadGitHubLatestReleaseInfo() { var request = new RestRequest("repos/arkivverket/arkade5/releases/latest"); request.AddCookie("logged_in", "no"); IRestResponse<GitHubReleaseInfo> gitHubResponse = _restClient.Execute<GitHubReleaseInfo>(request); if (gitHubResponse.Data == null) Log.Error("Unable to retrieve necessary data from GitHub. Please check your internet connection."); return gitHubResponse.Data; } public Version GetLatestVersion() { if (_latestReleaseInfo?.TagName == null) throw new Exception("Missing or unexpected data from GitHub"); if (!Regex.IsMatch(_latestReleaseInfo.TagName, @"^v\d+.\d+.\d+$")) throw new Exception("Unexpected tag-name format"); string versionNumber = _latestReleaseInfo.TagName.TrimStart('v') + ".0"; return new Version(versionNumber); } private class GitHubReleaseInfo { public string TagName { get; set; } } } }
agpl-3.0
C#
387ef550ed6071d6113ffe719f50ed5e03a45e85
Disable error for invalid asmdef reference
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/src/resharper-unity/Json/Daemon/Stages/Resolve/UnresolvedReferenceErrorHandler.cs
resharper/src/resharper-unity/Json/Daemon/Stages/Resolve/UnresolvedReferenceErrorHandler.cs
using System.Collections.Generic; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Errors; using JetBrains.ReSharper.Plugins.Unity.Json.Psi.Resolve; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.JavaScript.LanguageImpl.JSon; using JetBrains.ReSharper.Psi.Resolve; namespace JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Stages.Resolve { [Language(typeof(JsonLanguage))] public class UnresolvedReferenceErrorHandler : IResolveProblemHighlighter { public IHighlighting Run(IReference reference) { // Don't show the error highlight for now - there are too many false positive hits due to references to // assembly definitions in .asmdef files that are not part of the solution. These files need to be added // into a custom PSI module to make this work properly. This is a quick fix // return new UnresolvedProjectReferenceError(reference); return null; } public IEnumerable<ResolveErrorType> ErrorTypes => new[] { AsmDefResolveErrorType.ASMDEF_UNRESOLVED_REFERENCED_PROJECT_ERROR }; } }
using System.Collections.Generic; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Errors; using JetBrains.ReSharper.Plugins.Unity.Json.Psi.Resolve; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.JavaScript.LanguageImpl.JSon; using JetBrains.ReSharper.Psi.Resolve; namespace JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Stages.Resolve { [Language(typeof(JsonLanguage))] public class UnresolvedReferenceErrorHandler : IResolveProblemHighlighter { public IHighlighting Run(IReference reference) { return new UnresolvedProjectReferenceError(reference); } public IEnumerable<ResolveErrorType> ErrorTypes => new[] { AsmDefResolveErrorType.ASMDEF_UNRESOLVED_REFERENCED_PROJECT_ERROR }; } }
apache-2.0
C#
2c4f71316f208dae8039a0f61e60eea56e867409
Add maxWidth Image API 2.1 property
digirati-co-uk/iiif-model,Riksarkivet/iiif-model
Digirati.IIIF/Model/Types/ImageApi/ImageServiceProfile.cs
Digirati.IIIF/Model/Types/ImageApi/ImageServiceProfile.cs
using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types.ImageApi { public class ImageServiceProfile : IProfile { [JsonProperty(Order = 1, PropertyName = "formats")] public string[] Formats { get; set; } [JsonProperty(Order = 2, PropertyName = "qualities")] public string[] Qualities { get; set; } [JsonProperty(Order = 3, PropertyName = "supports")] public string[] Supports { get; set; } // 2.1 [JsonProperty(Order = 4, PropertyName = "maxWidth")] public int MaxWidth { get; set; } } }
using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types.ImageApi { public class ImageServiceProfile : IProfile { [JsonProperty(Order = 1, PropertyName = "formats")] public string[] Formats { get; set; } [JsonProperty(Order = 2, PropertyName = "qualities")] public string[] Qualities { get; set; } [JsonProperty(Order = 3, PropertyName = "supports")] public string[] Supports { get; set; } } }
mit
C#
8762ae3507e4d3b4fcbd50de9803cecc19745e99
Improve ToolTips
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Converters/PrivacyLevelValueConverter.cs
WalletWasabi.Gui/Converters/PrivacyLevelValueConverter.cs
using Avalonia; using Avalonia.Data.Converters; using Avalonia.Media; using AvalonStudio.Commands; using System; using System.Collections.Generic; using System.Composition; using System.Drawing; using System.Globalization; namespace WalletWasabi.Gui.Converters { public class PrivacyLevelValueConverter : IValueConverter { private readonly static Dictionary<string, DrawingGroup> Cache = new Dictionary<string, DrawingGroup>(); public DrawingGroup GetIconByName(string icon) { if (!Cache.TryGetValue(icon, out var image)) { if (Application.Current.Styles.TryGetResource(icon.ToString(), out object resource)) { image = resource as DrawingGroup; Cache.Add(icon, image); } else { throw new InvalidOperationException($"Icon {icon} not found"); } } return image; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int integer) { var shield = string.Empty; if (integer <= 1) { shield = "Critical"; } else if (integer < 21) { shield = "Some"; } else if (integer < 49) { shield = "Fine"; } else { shield = "Strong"; } var icon = GetIconByName($"Privacy{shield}"); return new { Icon = icon, ToolTip = $"Anonymity Set: {integer}" }; } throw new InvalidOperationException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
using Avalonia; using Avalonia.Data.Converters; using Avalonia.Media; using AvalonStudio.Commands; using System; using System.Collections.Generic; using System.Composition; using System.Drawing; using System.Globalization; namespace WalletWasabi.Gui.Converters { public class PrivacyLevelValueConverter : IValueConverter { private readonly static Dictionary<string, DrawingGroup> Cache = new Dictionary<string, DrawingGroup>(); public DrawingGroup GetIconByName(string icon) { if (!Cache.TryGetValue(icon, out var image)) { if (Application.Current.Styles.TryGetResource(icon.ToString(), out object resource)) { image = resource as DrawingGroup; Cache.Add(icon, image); } else { throw new InvalidOperationException($"Icon {icon} not found"); } } return image; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int integer) { var shield = string.Empty; if (integer <= 1) { shield = "Critical"; } else if (integer < 21) { shield = "Some"; } else if (integer < 49) { shield = "Fine"; } else { shield = "Strong"; } var icon = GetIconByName($"Privacy{shield}"); return new {Icon= icon, ToolTip= $"{shield}. Coin anonymity set is {integer}"}; } throw new InvalidOperationException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
mit
C#
2247050acd4891bb9b690a43ad1ac43a2d319d2a
Revert "tabs&spaces. Oh the joy"
IdentityServer/IdentityServer3,roflkins/IdentityServer3,IdentityServer/IdentityServer3,roflkins/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,johnkors/Thinktecture.IdentityServer.v3,johnkors/Thinktecture.IdentityServer.v3,IdentityServer/IdentityServer3,roflkins/IdentityServer3
source/Core/Resources/T4resx.cs
source/Core/Resources/T4resx.cs
 #pragma warning disable 1591 namespace IdentityServer3.Core.Resources { public class EventIds { public const string ClientPermissionsRevoked = "ClientPermissionsRevoked"; public const string CspReport = "CspReport"; public const string ExternalLoginError = "ExternalLoginError"; public const string ExternalLoginFailure = "ExternalLoginFailure"; public const string ExternalLoginSuccess = "ExternalLoginSuccess"; public const string LocalLoginFailure = "LocalLoginFailure"; public const string LocalLoginSuccess = "LocalLoginSuccess"; public const string LogoutEvent = "LogoutEvent"; public const string PartialLogin = "PartialLogin"; public const string PartialLoginComplete = "PartialLoginComplete"; public const string PreLoginFailure = "PreLoginFailure"; public const string PreLoginSuccess = "PreLoginSuccess"; public const string ResourceOwnerFlowLoginFailure = "ResourceOwnerFlowLoginFailure"; public const string ResourceOwnerFlowLoginSuccess = "ResourceOwnerFlowLoginSuccess"; public const string TokenRevoked = "TokenRevoked"; } public class MessageIds { public const string ClientIdRequired = "ClientIdRequired"; public const string ExternalProviderError = "ExternalProviderError"; public const string Invalid_request = "invalid_request"; public const string Invalid_scope = "invalid_scope"; public const string InvalidUsernameOrPassword = "InvalidUsernameOrPassword"; public const string MissingClientId = "MissingClientId"; public const string MissingToken = "MissingToken"; public const string MustSelectAtLeastOnePermission = "MustSelectAtLeastOnePermission"; public const string NoExternalProvider = "NoExternalProvider"; public const string NoMatchingExternalAccount = "NoMatchingExternalAccount"; public const string NoSignInCookie = "NoSignInCookie"; public const string NoSubjectFromExternalProvider = "NoSubjectFromExternalProvider"; public const string PasswordRequired = "PasswordRequired"; public const string SslRequired = "SslRequired"; public const string Unauthorized_client = "unauthorized_client"; public const string UnexpectedError = "UnexpectedError"; public const string Unsupported_response_type = "unsupported_response_type"; public const string UnsupportedMediaType = "UnsupportedMediaType"; public const string UsernameRequired = "UsernameRequired"; } public class ScopeIds { public const string Address_DisplayName = "address_DisplayName"; public const string All_claims_DisplayName = "all_claims_DisplayName"; public const string Email_DisplayName = "email_DisplayName"; public const string Offline_access_DisplayName = "offline_access_DisplayName"; public const string Openid_DisplayName = "openid_DisplayName"; public const string Phone_DisplayName = "phone_DisplayName"; public const string Profile_Description = "profile_Description"; public const string Profile_DisplayName = "profile_DisplayName"; public const string Roles_DisplayName = "roles_DisplayName"; } }
 #pragma warning disable 1591 namespace IdentityServer3.Core.Resources { public class EventIds { public const string ClientPermissionsRevoked = "ClientPermissionsRevoked"; public const string CspReport = "CspReport"; public const string ExternalLoginError = "ExternalLoginError"; public const string ExternalLoginFailure = "ExternalLoginFailure"; public const string ExternalLoginSuccess = "ExternalLoginSuccess"; public const string LocalLoginFailure = "LocalLoginFailure"; public const string LocalLoginSuccess = "LocalLoginSuccess"; public const string LogoutEvent = "LogoutEvent"; public const string PartialLogin = "PartialLogin"; public const string PartialLoginComplete = "PartialLoginComplete"; public const string PreLoginFailure = "PreLoginFailure"; public const string PreLoginSuccess = "PreLoginSuccess"; public const string ResourceOwnerFlowLoginFailure = "ResourceOwnerFlowLoginFailure"; public const string ResourceOwnerFlowLoginSuccess = "ResourceOwnerFlowLoginSuccess"; public const string TokenRevoked = "TokenRevoked"; } public class MessageIds { public const string ClientIdRequired = "ClientIdRequired"; public const string ExternalProviderError = "ExternalProviderError"; public const string Invalid_request = "invalid_request"; public const string Invalid_scope = "invalid_scope"; public const string InvalidUsernameOrPassword = "InvalidUsernameOrPassword"; public const string MissingClientId = "MissingClientId"; public const string MissingToken = "MissingToken"; public const string MustSelectAtLeastOnePermission = "MustSelectAtLeastOnePermission"; public const string NoExternalProvider = "NoExternalProvider"; public const string NoMatchingExternalAccount = "NoMatchingExternalAccount"; public const string NoSignInCookie = "NoSignInCookie"; public const string NoSubjectFromExternalProvider = "NoSubjectFromExternalProvider"; public const string PasswordRequired = "PasswordRequired"; public const string SslRequired = "SslRequired"; public const string Unauthorized_client = "unauthorized_client"; public const string UnexpectedError = "UnexpectedError"; public const string Unsupported_response_type = "unsupported_response_type"; public const string UnsupportedMediaType = "UnsupportedMediaType"; public const string UsernameRequired = "UsernameRequired"; } public class ScopeIds { public const string Address_DisplayName = "address_DisplayName"; public const string All_claims_DisplayName = "all_claims_DisplayName"; public const string Email_DisplayName = "email_DisplayName"; public const string Offline_access_DisplayName = "offline_access_DisplayName"; public const string Openid_DisplayName = "openid_DisplayName"; public const string Phone_DisplayName = "phone_DisplayName"; public const string Profile_Description = "profile_Description"; public const string Profile_DisplayName = "profile_DisplayName"; public const string Roles_DisplayName = "roles_DisplayName"; } }
apache-2.0
C#
40805bde902bb9be9dd2fb2e20343980d0a5b782
Add SpaceNotificationTestAsync
ats124/backlog4net
src/Backlog4net.Test/SpaceMethodsTest.cs
src/Backlog4net.Test/SpaceMethodsTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Backlog4net.Test { using Api; using Api.Option; using Backlog4net.Internal.Json; using Backlog4net.Internal.Json.Activities; using Conf; using Newtonsoft.Json; using TestConfig; [TestClass] public class SpaceMethodsTest { private static BacklogClient client; private static GeneralConfig generalConfig; [ClassInitialize] public static async Task SetupClient(TestContext context) { generalConfig = GeneralConfig.Instance.Value; var conf = new BacklogJpConfigure(generalConfig.SpaceKey); conf.ApiKey = generalConfig.ApiKey; client = new BacklogClientFactory(conf).NewClient(); var users = await client.GetUsersAsync(); } [TestMethod] public async Task SpaceNotificationTestAsync() { var content = $"TestNotification{DateTime.Now}"; var spaceNotificationUpdate = await client.UpdateSpaceNotificationAsync(content); Assert.AreEqual(spaceNotificationUpdate.Content, content); var spaceNotification = await client.GetSpaceNotificationAsync(); Assert.AreEqual(spaceNotification.Content, content); } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Backlog4net.Test { using Api; using Api.Option; using Backlog4net.Internal.Json; using Backlog4net.Internal.Json.Activities; using Conf; using Newtonsoft.Json; using TestConfig; [TestClass] public class SpaceMethodsTest { private static BacklogClient client; private static GeneralConfig generalConfig; [ClassInitialize] public static async Task SetupClient(TestContext context) { generalConfig = GeneralConfig.Instance.Value; var conf = new BacklogJpConfigure(generalConfig.SpaceKey); conf.ApiKey = generalConfig.ApiKey; client = new BacklogClientFactory(conf).NewClient(); var users = await client.GetUsersAsync(); } } }
mit
C#
4de9aad469f44ebb60573881b61d1abade9b5108
Fix unity plugin after CodeCleanupModel refactoring
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/src/Unity/CSharp/Psi/CodeStyle/AdditionalFileLayoutPatternProvider.cs
resharper/resharper-unity/src/Unity/CSharp/Psi/CodeStyle/AdditionalFileLayoutPatternProvider.cs
using System; using JetBrains.Application; using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.CSharp.FileLayout; using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel; using JetBrains.ReSharper.Psi.CSharp.CodeStyle; using JetBrains.ReSharper.Psi.CSharp.Impl.CodeStyle.MemberReordering; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util.Logging; namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.CodeStyle { [ShellComponent] public class AdditionalFileLayoutPatternProvider : IAdditionalCSharpFileLayoutPatternProvider { public Patterns GetPattern(IContextBoundSettingsStore store, ICSharpTypeAndNamespaceHolderDeclaration declaration) { var solution = declaration.GetSolution(); if (!solution.HasUnityReference()) return null; // TODO: This doesn't work with ReSharper - the resources haven't been added // If we add them, how do we edit them? try { var pattern = store.GetValue((AdditionalFileLayoutSettings s) => s.Pattern); return FileLayoutUtil.ParseFileLayoutPattern(solution, pattern); } catch (Exception ex) { Logger.LogException(ex); return null; } } } }
using System; using JetBrains.Application; using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.CSharp.FileLayout; using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel; using JetBrains.ReSharper.Psi.CSharp.CodeStyle; using JetBrains.ReSharper.Psi.CSharp.Impl.CodeStyle.MemberReordering; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util.Logging; namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.CodeStyle { [ShellComponent] public class AdditionalFileLayoutPatternProvider : IAdditionalCSharpFileLayoutPatternProvider { public Patterns GetPattern(IContextBoundSettingsStore store, ICSharpTypeAndNamespaceHolderDeclaration declaration) { if (!declaration.GetSolution().HasUnityReference()) return null; // TODO: This doesn't work with ReSharper - the resources haven't been added // If we add them, how do we edit them? try { var pattern = store.GetValue((AdditionalFileLayoutSettings s) => s.Pattern); return FileLayoutUtil.ParseFileLayoutPattern(pattern); } catch (Exception ex) { Logger.LogException(ex); return null; } } } }
apache-2.0
C#
084595f5d87bca45c1ff20aa39f5364f6910ed04
change every StringTenantUrn to make its nss part to lower always
Elders/Cronus.DomainModeling,Elders/Cronus.DomainModeling
src/Elders.Cronus.DomainModeling/StringTenantUrn.cs
src/Elders.Cronus.DomainModeling/StringTenantUrn.cs
using System; namespace Elders.Cronus { public class StringTenantUrn : Urn { const string regex = @"\b(?<prefix>[urnURN]{3}):(?<tenant>[a-zA-Z0-9][a-zA-Z0-9-]{0,31}):(?<arname>[a-zA-Z][a-zA-Z_\-.]{0,100}):?(?<id>[a-zA-Z0-9()+,\-.=@;$_!:*'%\/?#]*[a-zA-Z0-9+=@$\/])"; public StringTenantUrn(string tenant, string arName, string id) : base(tenant, $"{arName}{PARTS_DELIMITER}{id}".ToLower()) { Id = id.ToLower(); Tenant = tenant.ToLower(); ArName = arName.ToLower(); } public string Tenant { get; private set; } public string ArName { get; private set; } public string Id { get; private set; } public static bool TryParse(string urn, out StringTenantUrn parsedUrn) { var match = System.Text.RegularExpressions.Regex.Match(urn, regex, System.Text.RegularExpressions.RegexOptions.None); if (match.Success) { parsedUrn = new StringTenantUrn(match.Groups["tenant"].Value, match.Groups["arname"].Value, match.Groups["id"].Value); return true; } parsedUrn = null; return false; } new public static StringTenantUrn Parse(string urn) { var match = System.Text.RegularExpressions.Regex.Match(urn, regex, System.Text.RegularExpressions.RegexOptions.None); if (match.Success) return new StringTenantUrn(match.Groups["tenant"].Value, match.Groups["arname"].Value, match.Groups["id"].Value); throw new ArgumentException($"Invalid StringTenantUrn: {urn}", nameof(urn)); } new public static StringTenantUrn Parse(string urn, IUrnFormatProvider proviver) { string plain = proviver.Parse(urn); return Parse(plain); } } }
using System; namespace Elders.Cronus { public class StringTenantUrn : Urn { const string regex = @"\b(?<prefix>[urnURN]{3}):(?<tenant>[a-zA-Z0-9][a-zA-Z0-9-]{0,31}):(?<arname>[a-zA-Z][a-zA-Z_\-.]{0,100}):?(?<id>[a-zA-Z0-9()+,\-.=@;$_!:*'%\/?#]*[a-zA-Z0-9+=@$\/])"; public StringTenantUrn(string tenant, string arName, string id) : base(tenant, arName + Delimiter + id) { Tenant = tenant.ToLower(); ArName = arName.ToLower(); Id = id.ToLower(); } public string Tenant { get; private set; } public string ArName { get; private set; } public string Id { get; private set; } public static bool TryParse(string urn, out StringTenantUrn parsedUrn) { var match = System.Text.RegularExpressions.Regex.Match(urn, regex, System.Text.RegularExpressions.RegexOptions.None); if (match.Success) { parsedUrn = new StringTenantUrn(match.Groups["tenant"].Value, match.Groups["arname"].Value, match.Groups["id"].Value); return true; } parsedUrn = null; return false; } new public static StringTenantUrn Parse(string urn) { var match = System.Text.RegularExpressions.Regex.Match(urn, regex, System.Text.RegularExpressions.RegexOptions.None); if (match.Success) return new StringTenantUrn(match.Groups["tenant"].Value, match.Groups["arname"].Value, match.Groups["id"].Value); throw new ArgumentException($"Invalid StringTenantUrn: {urn}", nameof(urn)); } new public static StringTenantUrn Parse(string urn, IUrnFormatProvider proviver) { string plain = proviver.Parse(urn); return Parse(plain); } } }
apache-2.0
C#
5fdf7fc796bb35d1a0c23c9814e984615279c8a6
Fix error when displaying ServerDistList-entity
aluxnimm/outlookcaldavsynchronizer
CalDavSynchronizer/Scheduling/ComponentCollectors/AvailableContactSynchronizerComponents.cs
CalDavSynchronizer/Scheduling/ComponentCollectors/AvailableContactSynchronizerComponents.cs
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CalDavSynchronizer.DataAccess; using CalDavSynchronizer.Implementation.Contacts; using Thought.vCards; namespace CalDavSynchronizer.Scheduling.ComponentCollectors { public class AvailableContactSynchronizerComponents : AvailableSynchronizerComponents { public ICardDavDataAccess CardDavDataAccess { get; set; } public CardDavRepository<int> CardDavEntityRepository { get; set; } public ICardDavDataAccess DistListDataAccess { get; set; } public override DataAccessComponents GetDataAccessComponents () { return new DataAccessComponents { CardDavDataAccess = CardDavDataAccess, DistListDataAccess = DistListDataAccess }; } } }
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CalDavSynchronizer.DataAccess; using CalDavSynchronizer.Implementation.Contacts; using Thought.vCards; namespace CalDavSynchronizer.Scheduling.ComponentCollectors { public class AvailableContactSynchronizerComponents : AvailableSynchronizerComponents { public ICardDavDataAccess CardDavDataAccess { get; set; } public CardDavRepository<int> CardDavEntityRepository { get; set; } public ICardDavDataAccess DistListDataAccess { get; set; } public override DataAccessComponents GetDataAccessComponents () { return new DataAccessComponents { CardDavDataAccess = CardDavDataAccess }; } } }
agpl-3.0
C#
a224d9053649dd0bdb3c31bbdeeeef848f80eb7c
Add one method
fredatgithub/UsefulFunctions
FonctionsUtiles.Fred.Csharp/functionsControls.cs
FonctionsUtiles.Fred.Csharp/functionsControls.cs
/* The MIT License(MIT) Copyright(c) 2015 Freddy Juhel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Windows.Forms; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsControls { public TextBoxBase WhatTextBoxHasFocus() { TextBoxBase result = null; //foreach (var control in Control.ControlCollection.Controls.OfType<TextBoxBase>()) //{ // if (control.Focused) // { // result = control; // break; // } //} return result; } public static void AcceptOnlyNumbers(Control textBox) { int value; if (!int.TryParse(textBox.Text, out value)) { textBox.Text = string.Empty; } } public static bool IsInlistView(ListView listView, ListViewItem lviItem, int columnNumber = 1) { // return listView.Items.Cast<ListViewItem>().All(item => item.SubItems[columnNumber].Text != lviItem.SubItems[columnNumber].Text); bool result = false; foreach (ListViewItem item in listView.Items) { if (item.SubItems[columnNumber].Text == lviItem.SubItems[columnNumber].Text) { result = true; break; } } return result; } } }
/* The MIT License(MIT) Copyright(c) 2015 Freddy Juhel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Windows.Forms; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsControls { public TextBoxBase WhatTextBoxHasFocus() { TextBoxBase result = null; //foreach (var control in Control.ControlCollection.Controls.OfType<TextBoxBase>()) //{ // if (control.Focused) // { // result = control; // break; // } //} return result; } public static void AcceptOnlyNumbers(Control textBox) { int value; if (!int.TryParse(textBox.Text, out value)) { textBox.Text = string.Empty; } } } }
mit
C#
d1ff1dc06c6c0ea6f23ce987e9da320f07ce2b24
add comment
StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis
service/DotNetApis.Storage/BatchOperation.cs
service/DotNetApis.Storage/BatchOperation.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; namespace DotNetApis.Storage { /// <summary> /// Represents an action to be taken as part of a batch. /// </summary> public interface IBatchAction { } /// <summary> /// Represents a collection of actions to execute as a batch. /// </summary> public interface IBatch { /// <summary> /// The number of actions in this batch. /// </summary> int Count { get; } /// <summary> /// Adds an action to this batch. Throws an exception if the type of the batch action is not compatible with the type of the batch. /// </summary> /// <param name="action">The action to add.</param> void Add(IBatchAction action); /// <summary> /// Executes all the actions in the batch. /// </summary> Task ExecuteAsync(); } public sealed class AzureTableBatch : IBatch { private readonly CloudTable _table; private readonly TableBatchOperation _operation; public AzureTableBatch(CloudTable table) { _table = table; _operation = new TableBatchOperation(); } public int Count => _operation.Count; public void Add(IBatchAction action) { if (action is InsertOrReplaceAction insertOrReplaceAction) { insertOrReplaceAction.Apply(this); return; } throw new InvalidOperationException($"Unknown batch action {action.GetType().Name}"); } public Task ExecuteAsync() => _table.ExecuteBatchAsync(_operation); public sealed class InsertOrReplaceAction : IBatchAction { private readonly ITableEntity _entity; public InsertOrReplaceAction(ITableEntity entity) { _entity = entity; } public void Apply(AzureTableBatch batch) => batch._operation.InsertOrReplace(_entity); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; namespace DotNetApis.Storage { /// <summary> /// Represents an action to be taken as part of a batch. /// </summary> public interface IBatchAction { } /// <summary> /// Represents a collection of actions to execute as a batch. /// </summary> public interface IBatch { /// <summary> /// The number of actions in this batch. /// </summary> int Count { get; } /// <summary> /// Adds an action to this batch. /// </summary> /// <param name="action">The action to add.</param> void Add(IBatchAction action); /// <summary> /// Executes all the actions in the batch. /// </summary> Task ExecuteAsync(); } public sealed class AzureTableBatch : IBatch { private readonly CloudTable _table; private readonly TableBatchOperation _operation; public AzureTableBatch(CloudTable table) { _table = table; _operation = new TableBatchOperation(); } public int Count => _operation.Count; public void Add(IBatchAction action) { if (action is InsertOrReplaceAction insertOrReplaceAction) { insertOrReplaceAction.Apply(this); return; } throw new InvalidOperationException($"Unknown batch action {action.GetType().Name}"); } public Task ExecuteAsync() => _table.ExecuteBatchAsync(_operation); public sealed class InsertOrReplaceAction : IBatchAction { private readonly ITableEntity _entity; public InsertOrReplaceAction(ITableEntity entity) { _entity = entity; } public void Apply(AzureTableBatch batch) => batch._operation.InsertOrReplace(_entity); } } }
mit
C#
44b31010d9393bc25e5f1926edf337004b8c5af9
Rename test dependency
DivineInject/DivineInject,DivineInject/DivineInject
DivineInject.Test/DivineInjectorTest.cs
DivineInject.Test/DivineInjectorTest.cs
using NUnit.Framework; using TestFirst.Net.Extensions.NUnit; using TestFirst.Net.Matcher; namespace DivineInject.Test { [TestFixture] public class DivineInjectorTest : AbstractNUnitScenarioTest { [Test] public void BindsInterfaceToImplementationAndInstantiates() { DivineInjector injector; IDatabaseProvider instance; Scenario() .Given(injector = new DivineInjector()) .Given(() => injector.Bind<IDatabaseProvider>().To<DatabaseProvider>()) .When(instance = injector.Get<IDatabaseProvider>()) .Then(instance, Is(AnInstance.OfType<DatabaseProvider>())) ; } [Test] public void MultipleRequestsForSameInterfaceYieldSameObject() { DivineInjector injector; IDatabaseProvider instance1, instance2; Scenario() .Given(injector = new DivineInjector()) .Given(() => injector.Bind<IDatabaseProvider>().To<DatabaseProvider>()) .When(instance1 = injector.Get<IDatabaseProvider>()) .When(instance2 = injector.Get<IDatabaseProvider>()) .Then(instance1, Is(AnInstance.SameAs(instance2))) ; } [Test] public void IsBoundReturnsWhetherABindingExistsForAType() { DivineInjector injector; Scenario() .Given(injector = new DivineInjector()) .Given(() => injector.Bind<IDatabaseProvider>().To<DatabaseProvider>()) .Then(injector.IsBound(typeof(IDatabaseProvider)), IsTrue()) .Then(injector.IsBound(typeof(string)), IsFalse()) ; } } public interface IDatabaseProvider { } public class DatabaseProvider : IDatabaseProvider { } }
using NUnit.Framework; using TestFirst.Net.Extensions.NUnit; using TestFirst.Net.Matcher; namespace DivineInject.Test { [TestFixture] public class DivineInjectorTest : AbstractNUnitScenarioTest { [Test] public void BindsInterfaceToImplementationAndInstantiates() { DivineInjector injector; IOrderService instance; Scenario() .Given(injector = new DivineInjector()) .Given(() => injector.Bind<IOrderService>().To<OrderService>()) .When(instance = injector.Get<IOrderService>()) .Then(instance, Is(AnInstance.OfType<OrderService>())) ; } [Test] public void MultipleRequestsForSameInterfaceYieldSameObject() { DivineInjector injector; IOrderService instance1, instance2; Scenario() .Given(injector = new DivineInjector()) .Given(() => injector.Bind<IOrderService>().To<OrderService>()) .When(instance1 = injector.Get<IOrderService>()) .When(instance2 = injector.Get<IOrderService>()) .Then(instance1, Is(AnInstance.SameAs(instance2))) ; } [Test] public void IsBoundReturnsWhetherABindingExistsForAType() { DivineInjector injector; Scenario() .Given(injector = new DivineInjector()) .Given(() => injector.Bind<IOrderService>().To<OrderService>()) .Then(injector.IsBound(typeof(IOrderService)), IsTrue()) .Then(injector.IsBound(typeof(string)), IsFalse()) ; } } public interface IOrderService { } public class OrderService : IOrderService { } }
mit
C#
fad9e7399940946d90f4314f9344d8871af68df6
Add null check in disposal clause
johnneijzen/osu,peppy/osu,peppy/osu,EVAST9919/osu,2yangk23/osu,ZLima12/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,UselessToucan/osu
osu.Game/Overlays/FullscreenOverlay.cs
osu.Game/Overlays/FullscreenOverlay.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Effects; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API; using osuTK.Graphics; namespace osu.Game.Overlays { public abstract class FullscreenOverlay : WaveOverlayContainer, IOnlineComponent { [Resolved] protected IAPIProvider API { get; private set; } protected FullscreenOverlay() { Waves.FirstWaveColour = OsuColour.Gray(0.4f); Waves.SecondWaveColour = OsuColour.Gray(0.3f); Waves.ThirdWaveColour = OsuColour.Gray(0.2f); Waves.FourthWaveColour = OsuColour.Gray(0.1f); RelativeSizeAxes = Axes.Both; RelativePositionAxes = Axes.Both; Width = 0.85f; Anchor = Anchor.TopCentre; Origin = Anchor.TopCentre; Masking = true; EdgeEffect = new EdgeEffectParameters { Colour = Color4.Black.Opacity(0), Type = EdgeEffectType.Shadow, Radius = 10 }; } protected override void PopIn() { base.PopIn(); FadeEdgeEffectTo(0.4f, WaveContainer.APPEAR_DURATION, Easing.Out); } protected override void PopOut() { base.PopOut(); FadeEdgeEffectTo(0, WaveContainer.DISAPPEAR_DURATION, Easing.In).OnComplete(_ => PopOutComplete()); } protected virtual void PopOutComplete() { } protected override void LoadComplete() { base.LoadComplete(); API.Register(this); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); API?.Unregister(this); } public virtual void APIStateChanged(IAPIProvider api, APIState state) { } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Effects; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API; using osuTK.Graphics; namespace osu.Game.Overlays { public abstract class FullscreenOverlay : WaveOverlayContainer, IOnlineComponent { [Resolved] protected IAPIProvider API { get; private set; } protected FullscreenOverlay() { Waves.FirstWaveColour = OsuColour.Gray(0.4f); Waves.SecondWaveColour = OsuColour.Gray(0.3f); Waves.ThirdWaveColour = OsuColour.Gray(0.2f); Waves.FourthWaveColour = OsuColour.Gray(0.1f); RelativeSizeAxes = Axes.Both; RelativePositionAxes = Axes.Both; Width = 0.85f; Anchor = Anchor.TopCentre; Origin = Anchor.TopCentre; Masking = true; EdgeEffect = new EdgeEffectParameters { Colour = Color4.Black.Opacity(0), Type = EdgeEffectType.Shadow, Radius = 10 }; } protected override void PopIn() { base.PopIn(); FadeEdgeEffectTo(0.4f, WaveContainer.APPEAR_DURATION, Easing.Out); } protected override void PopOut() { base.PopOut(); FadeEdgeEffectTo(0, WaveContainer.DISAPPEAR_DURATION, Easing.In).OnComplete(_ => PopOutComplete()); } protected virtual void PopOutComplete() { } protected override void LoadComplete() { base.LoadComplete(); API.Register(this); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); API.Unregister(this); } public virtual void APIStateChanged(IAPIProvider api, APIState state) { } } }
mit
C#
fe90e194e37b977ebcd2232f0af0b5177efef571
Remove redundant qualifier
smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,ZLima12/osu,peppy/osu-new,2yangk23/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,ppy/osu,ppy/osu,johnneijzen/osu,2yangk23/osu,peppy/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu
osu.Game/Skinning/PlaySkinComponent.cs
osu.Game/Skinning/PlaySkinComponent.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; namespace osu.Game.Skinning { public class PlaySkinComponent<T> : ISkinComponent where T : struct { public readonly T Component; public PlaySkinComponent(T component) { Component = component; } protected virtual string RulesetPrefix => string.Empty; protected virtual string ComponentName => Component.ToString(); public string LookupName => string.Join("/", new[] { "Play", RulesetPrefix, ComponentName }.Where(s => !string.IsNullOrEmpty(s))); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; namespace osu.Game.Skinning { public class PlaySkinComponent<T> : ISkinComponent where T : struct { public readonly T Component; public PlaySkinComponent(T component) { this.Component = component; } protected virtual string RulesetPrefix => string.Empty; protected virtual string ComponentName => Component.ToString(); public string LookupName => string.Join("/", new[] { "Play", RulesetPrefix, ComponentName }.Where(s => !string.IsNullOrEmpty(s))); } }
mit
C#
043f1cdb3c44eb594ecb4a31594557e152953f01
Bump version number.
kangkot/ArangoDB-NET,yojimbo87/ArangoDB-NET
src/Arango/Arango.Client/API/ArangoClient.cs
src/Arango/Arango.Client/API/ArangoClient.cs
using System.Collections.Generic; using System.Linq; using Arango.Client.Protocol; namespace Arango.Client { public static class ArangoClient { private static List<Connection> _connections = new List<Connection>(); public static string DriverName { get { return "ArangoDB-NET"; } } public static string DriverVersion { get { return "0.3.0"; } } public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias) { var connection = new Connection(hostname, port, isSecured, userName, password, alias); _connections.Add(connection); } internal static Connection GetConnection(string alias) { return _connections.Where(connection => connection.Alias == alias).FirstOrDefault(); } } }
using System.Collections.Generic; using System.Linq; using Arango.Client.Protocol; namespace Arango.Client { public static class ArangoClient { private static List<Connection> _connections = new List<Connection>(); public static string DriverName { get { return "ArangoDB-NET"; } } public static string DriverVersion { get { return "0.2.1"; } } public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias) { var connection = new Connection(hostname, port, isSecured, userName, password, alias); _connections.Add(connection); } internal static Connection GetConnection(string alias) { return _connections.Where(connection => connection.Alias == alias).FirstOrDefault(); } } }
mit
C#
5abae917327223e788af8c305400837fc9dc325d
Bump lib version to 2.2.4
rickyah/ini-parser,rickyah/ini-parser
src/IniFileParser/Properties/AssemblyInfo.cs
src/IniFileParser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("INIParser")] [assembly: AssemblyDescription("A simple INI file processing library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("INIParser")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")] // 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("2.2.4")] [assembly: AssemblyFileVersion("2.2.4")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("INIParser")] [assembly: AssemblyDescription("A simple INI file processing library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("INIParser")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")] // 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("2.2.2")] [assembly: AssemblyFileVersion("2.2.2")]
mit
C#
4b31aad22df608a7cd8682ba8a137042132a60b0
Remove unnecessary dynamic typing
malcolmr/nodatime,jskeet/nodatime,nodatime/nodatime,malcolmr/nodatime,jskeet/nodatime,malcolmr/nodatime,nodatime/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,malcolmr/nodatime
src/NodaTime.Test/Annotations/TrustedTest.cs
src/NodaTime.Test/Annotations/TrustedTest.cs
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Collections.Generic; using System.Linq; using System.Reflection; using NodaTime.Annotations; using NUnit.Framework; namespace NodaTime.Test.Annotations { public class TrustedTest { [Test] public void MembersWithTrustedParametersAreNotPublic() { var types = typeof(Instant).GetTypeInfo().Assembly.DefinedTypes; var invalidMembers = types.SelectMany(t => t.DeclaredMembers) .Where(m => GetParameters(m).Any(p => p.IsDefined(typeof(TrustedAttribute), false))) .Where(InvalidForTrustedParameters); TestHelper.AssertNoFailures(invalidMembers, FormatMemberDebugName); } private static string FormatMemberDebugName(MemberInfo m) => string.Format("{0}.{1}({2})", m.DeclaringType.Name, m.Name, string.Join(", ", GetParameters(m).Select(p => p.ParameterType))); private static bool InvalidForTrustedParameters(dynamic member) => // We'll need to be more specific at some point, but this will do to start with... member.IsPublic && (member.DeclaringType.IsPublic || member.DeclaringType.IsNestedPublic); private static IEnumerable<ParameterInfo> GetParameters(MemberInfo member) { switch (member) { case MethodBase method: return method.GetParameters(); case PropertyInfo property: return property.GetIndexParameters(); default: return Enumerable.Empty<ParameterInfo>(); } } } }
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Collections.Generic; using System.Linq; using System.Reflection; using NodaTime.Annotations; using NUnit.Framework; namespace NodaTime.Test.Annotations { public class TrustedTest { [Test] public void MembersWithTrustedParametersAreNotPublic() { var types = typeof(Instant).GetTypeInfo().Assembly.DefinedTypes; var invalidMembers = types.SelectMany(t => t.DeclaredMembers) .Where(m => GetParameters(m).Any(p => p.IsDefined(typeof(TrustedAttribute), false))) .Where(InvalidForTrustedParameters); TestHelper.AssertNoFailures(invalidMembers, FormatMemberDebugName); } private static string FormatMemberDebugName(MemberInfo m) => string.Format("{0}.{1}({2})", m.DeclaringType.Name, m.Name, string.Join(", ", GetParameters(m).Select(p => p.ParameterType))); private static bool InvalidForTrustedParameters(dynamic member) => // We'll need to be more specific at some point, but this will do to start with... member.IsPublic && (member.DeclaringType.IsPublic || member.DeclaringType.IsNestedPublic); private static IEnumerable<ParameterInfo> GetParameters(MemberInfo member) { if (member is MethodInfo || member is ConstructorInfo) { return ((dynamic) member).GetParameters(); } if (member is PropertyInfo) { return ((PropertyInfo) member).GetIndexParameters(); } return Enumerable.Empty<ParameterInfo>(); } } }
apache-2.0
C#
eec1de8fc5a4e915052955416d0d9995cf06d889
Add test coverage of double disposal crashing
peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework.Tests/Threading/ThreadedTaskSchedulerTest.cs
osu.Framework.Tests/Threading/ThreadedTaskSchedulerTest.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Threading; namespace osu.Framework.Tests.Threading { [TestFixture] public class ThreadedTaskSchedulerTest { /// <summary> /// On disposal, <see cref="ThreadedTaskScheduler"/> does a blocking shutdown sequence. /// This asserts all outstanding tasks are run before the shutdown completes. /// </summary> [Test] public void EnsureThreadedTaskSchedulerProcessesBeforeDispose() { int runCount = 0; const int target_count = 128; using var taskScheduler = new ThreadedTaskScheduler(4, "test"); for (int i = 0; i < target_count; i++) { Task.Factory.StartNew(() => { Interlocked.Increment(ref runCount); Thread.Sleep(100); }, default, TaskCreationOptions.HideScheduler, taskScheduler); } taskScheduler.Dispose(); // test against double disposal crashes. taskScheduler.Dispose(); Assert.AreEqual(target_count, runCount); } [Test] public void EnsureEventualDisposalWithStuckTasks() { ManualResetEventSlim exited = new ManualResetEventSlim(); Task.Run(() => { using (var taskScheduler = new ThreadedTaskScheduler(4, "test")) { Task.Factory.StartNew(() => { while (!exited.IsSet) Thread.Sleep(100); }, default, TaskCreationOptions.HideScheduler, taskScheduler); } exited.Set(); }); Assert.That(exited.Wait(30000)); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Threading; namespace osu.Framework.Tests.Threading { [TestFixture] public class ThreadedTaskSchedulerTest { /// <summary> /// On disposal, <see cref="ThreadedTaskScheduler"/> does a blocking shutdown sequence. /// This asserts all outstanding tasks are run before the shutdown completes. /// </summary> [Test] public void EnsureThreadedTaskSchedulerProcessesBeforeDispose() { int runCount = 0; const int target_count = 128; using (var taskScheduler = new ThreadedTaskScheduler(4, "test")) { for (int i = 0; i < target_count; i++) { Task.Factory.StartNew(() => { Interlocked.Increment(ref runCount); Thread.Sleep(100); }, default, TaskCreationOptions.HideScheduler, taskScheduler); } } Assert.AreEqual(target_count, runCount); } [Test] public void EnsureEventualDisposalWithStuckTasks() { ManualResetEventSlim exited = new ManualResetEventSlim(); Task.Run(() => { using (var taskScheduler = new ThreadedTaskScheduler(4, "test")) { Task.Factory.StartNew(() => { while (!exited.IsSet) Thread.Sleep(100); }, default, TaskCreationOptions.HideScheduler, taskScheduler); } exited.Set(); }); Assert.That(exited.Wait(30000)); } } }
mit
C#
c9cac33c0d2f490076e530c2c98f170aca080cb0
create ScriptableObjectWindowCollection by menu
shinji-yoshida/Ebis
Assets/Plugins/Ebis/ScriptableObjectWindowCollection.cs
Assets/Plugins/Ebis/ScriptableObjectWindowCollection.cs
using UnityEngine; using System.Linq; using System.Collections.Generic; namespace Ebis { [CreateAssetMenu] public class ScriptableObjectWindowCollection : ScriptableObject, WindowCollection { [SerializeField] List<Window> windows; public T FindPrefab<T> (string variation) where T : Window { if(variation == null) return windows.Select (w => w.GetComponent<T> ()).FirstOrDefault (w => w != null); else return windows.Select (w => w.GetComponent<T> ()) .Where (w => w != null) .FirstOrDefault (w => w.gameObject.name.Equals (variation + typeof(T).Name)); } } }
using UnityEngine; using System.Linq; using System.Collections.Generic; namespace Ebis { public class ScriptableObjectWindowCollection : ScriptableObject, WindowCollection { [SerializeField] List<Window> windows; public T FindPrefab<T> (string variation) where T : Window { if(variation == null) return windows.Select (w => w.GetComponent<T> ()).FirstOrDefault (w => w != null); else return windows.Select (w => w.GetComponent<T> ()) .Where (w => w != null) .FirstOrDefault (w => w.gameObject.name.Equals (variation + typeof(T).Name)); } } }
mit
C#
5d1ad1fe034eda0206917377afaeddcdeb259e30
Update Android
larsbrubaker/MatterControl,mmoening/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,jlewin/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl
SetupWizard/AndroidNetworkTroubleshootingPage.cs
SetupWizard/AndroidNetworkTroubleshootingPage.cs
/* Copyright (c) 2017, Kevin Pope, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; namespace MatterHackers.MatterControl { public class NetworkTroubleshooting : DialogPage { public NetworkTroubleshooting() { contentRow.AddChild( new TextWidget( "MatterControl was unable to connect to the Internet. Please check your Wifi connection and try again".Localize() + "...", textColor: ActiveTheme.Instance.PrimaryTextColor)); Button configureButton = theme.WhiteButtonFactory.Generate("Configure Wifi".Localize()); configureButton.Margin = new BorderDouble(0, 0, 10, 0); configureButton.Click += (s, e) => { MatterControl.AppContext.Platform.ConfigureWifi(); UiThread.RunOnIdle(WizardWindow.Close, 1); // We could clear the failure count allowing the user to toggle wifi, then retry sign-in //ApplicationController.WebRequestSucceeded(); }; //Add buttons to buttonContainer AddPageAction(configureButton); } } }
/* Copyright (c) 2017, Kevin Pope, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; namespace MatterHackers.MatterControl { public class NetworkTroubleshooting : DialogPage { public NetworkTroubleshooting() { contentRow.AddChild( new TextWidget( "MatterControl was unable to connect to the Internet. Please check your Wifi connection and try again".Localize() + "...", textColor: ActiveTheme.Instance.PrimaryTextColor)); Button configureButton = whiteImageButtonFactory.Generate("Configure Wifi".Localize()); configureButton.Margin = new BorderDouble(0, 0, 10, 0); configureButton.Click += (s, e) => { MatterControl.AppContext.Platform.ConfigureWifi(); UiThread.RunOnIdle(WizardWindow.Close, 1); // We could clear the failure count allowing the user to toggle wifi, then retry sign-in //ApplicationController.WebRequestSucceeded(); }; //Add buttons to buttonContainer AddPageAction(configureButton); } } }
bsd-2-clause
C#