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
8866529177343c90796e8b79c3995be9b029c14e
Make it parallel
chitoku-k/StopAll
StopAll/MediaPlayersManager.cs
StopAll/MediaPlayersManager.cs
using NowPlayingLib; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace StopAll { public class MediaPlayersManager { private static readonly Dictionary<string, Func<MediaPlayerBase>> PlayerConstructors = new Dictionary<string, Func<MediaPlayerBase>> { { "wmplayer", () => new WindowsMediaPlayer() }, { "iTunes", () => new iTunes() }, { "x-APPLICATION", () => new XApplication() }, { "x-APPLISMO", () => new LismoPort() }, { "foobar2000", () => new NowPlayingLib.Foobar2000() } }; public static void PauseAll() { Parallel.ForEach(Process.GetProcesses().Select(x => x.ProcessName).Intersect(PlayerConstructors.Keys), processName => { try { using (var player = PlayerConstructors[processName]()) { player.Pause(); } } catch { } }); } } }
using NowPlayingLib; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace StopAll { public class MediaPlayersManager { private static readonly Dictionary<string, Func<MediaPlayerBase>> PlayerConstructors = new Dictionary<string, Func<MediaPlayerBase>> { { "wmplayer", () => new WindowsMediaPlayer() }, { "iTunes", () => new iTunes() }, { "x-APPLICATION", () => new XApplication() }, { "x-APPLISMO", () => new LismoPort() }, { "foobar2000", () => new NowPlayingLib.Foobar2000() } }; public static void PauseAll() { foreach (var func in Process.GetProcesses().Select(x => x.ProcessName).Intersect(PlayerConstructors.Keys).Select(x => PlayerConstructors[x])) { try { using (var player = func()) { player.Pause(); } } catch { } } } } }
mit
C#
ab61bcc36e28a0f07f640bc2b8af80ddbd74daf8
Fix compilation after sdk api changes
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-yaml/src/Psi/Parsing/YamlTokenBase.cs
resharper/resharper-yaml/src/Psi/Parsing/YamlTokenBase.cs
using System; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Text; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Yaml.Psi.Parsing { public abstract class YamlTokenBase : BoundToBufferLeafElement, IYamlTreeNode, ITokenNode { protected YamlTokenBase(NodeType nodeType, IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset) : base(nodeType, buffer, startOffset, endOffset) { } public override PsiLanguageType Language => LanguageFromParent; public virtual void Accept(TreeNodeVisitor visitor) { visitor.VisitNode(this); } public virtual void Accept<TContext>(TreeNodeVisitor<TContext> visitor, TContext context) { visitor.VisitNode(this, context); } public virtual TResult Accept<TContext, TResult>(TreeNodeVisitor<TContext, TResult> visitor, TContext context) { return visitor.VisitNode(this, context); } public TokenNodeType GetTokenType() => (TokenNodeType) NodeType; public override string ToString() { var text = GetTextAsBuffer().GetText(new TextRange(0, Math.Min(100, Length))); return $"{base.ToString()}(type:{NodeType}, text:{text})"; } } }
using System; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Text; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Yaml.Psi.Parsing { public abstract class YamlTokenBase : BindedToBufferLeafElement, IYamlTreeNode, ITokenNode { protected YamlTokenBase(NodeType nodeType, IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset) : base(nodeType, buffer, startOffset, endOffset) { } public override PsiLanguageType Language => LanguageFromParent; public virtual void Accept(TreeNodeVisitor visitor) { visitor.VisitNode(this); } public virtual void Accept<TContext>(TreeNodeVisitor<TContext> visitor, TContext context) { visitor.VisitNode(this, context); } public virtual TResult Accept<TContext, TResult>(TreeNodeVisitor<TContext, TResult> visitor, TContext context) { return visitor.VisitNode(this, context); } public TokenNodeType GetTokenType() => (TokenNodeType) NodeType; public override string ToString() { var text = GetTextAsBuffer().GetText(new TextRange(0, Math.Min(100, Length))); return $"{base.ToString()}(type:{NodeType}, text:{text})"; } } }
apache-2.0
C#
1efa8de55f75d88003fb672e078181e3b5a05bd2
Add Google+ href.
bigfont/sweet-water-revolver
mvcWebApp/Views/Home/_ExternalLinks.cshtml
mvcWebApp/Views/Home/_ExternalLinks.cshtml
<section class="container"> <div id="our-external-links"> @*href="https://myspace.com/sweetwaterrevolver" href="https://www.facebook.com/pages/Sweet-Water-Revolver/390852040983091" href="http://www.reverbnation.com/sweetwaterrevolver"*@ <a href="https://www.facebook.com/pages/Sweet-Water-Revolver/390852040983091"><i class="fa fa-facebook fa-5x"></i></a> <a href=""><i class="fa fa-flickr fa-5x"></i></a> <a href="https://plus.google.com/104298774585996996040/posts"><i class="fa fa-google-plus fa-5x"></i></a> <a href=""><i class="fa fa-pinterest fa-5x"></i></a> <a href=""><i class="fa fa-tumblr fa-5x"></i></a> <a href=""><i class="fa fa-twitter fa-5x"></i></a> <a href=""><i class="fa fa-vimeo fa-5x"></i></a> <a href=""><i class="fa fa-youtube fa-5x"></i></a> </div> </section>
<section class="container"> <div id="our-external-links"> @*href="https://myspace.com/sweetwaterrevolver" href="https://www.facebook.com/pages/Sweet-Water-Revolver/390852040983091" href="http://www.reverbnation.com/sweetwaterrevolver"*@ <a href="https://www.facebook.com/pages/Sweet-Water-Revolver/390852040983091"><i class="fa fa-facebook fa-5x"></i></a> <a href=""><i class="fa fa-flickr fa-5x"></i></a> <a href=""><i class="fa fa-google-plus fa-5x"></i></a> <a href=""><i class="fa fa-pinterest fa-5x"></i></a> <a href=""><i class="fa fa-tumblr fa-5x"></i></a> <a href=""><i class="fa fa-twitter fa-5x"></i></a> <a href=""><i class="fa fa-vimeo fa-5x"></i></a> <a href=""><i class="fa fa-youtube fa-5x"></i></a> </div> </section>
mit
C#
1ad4d93c17e0ed83c2e882f891d5c517d96e74ed
add validation for auth settings
nmklotas/GitLabCLI
src/GitlabCmd.Console/App/AppSettingsValidationHandler.cs
src/GitlabCmd.Console/App/AppSettingsValidationHandler.cs
using System; using GitlabCmd.Console.Configuration; using GitlabCmd.Console.Utilities; namespace GitlabCmd.Console.App { public class AppSettingsValidationHandler { private readonly AppSettings _settings; private readonly OutputPresenter _outputPresenter; public AppSettingsValidationHandler( AppSettings settings, OutputPresenter outputPresenter) { _settings = settings; _outputPresenter = outputPresenter; } public bool Validate() { if (!ValidateHostUrl()) return false; if (!ValidateAuthorizationSettings()) return false; return true; } private bool ValidateHostUrl() { if (string.IsNullOrEmpty(_settings.GitLabHostUrl)) { _outputPresenter.Info("GitLab host url is not set"); return false; } return true; } private bool ValidateAuthorizationSettings() { bool tokenExits = _settings.GitLabAccessToken.IsNotEmpty(); bool credentialsExits = _settings.GitLabUserName.IsNotEmpty() || _settings.GitLabPassword.IsNotEmpty(); if (tokenExits || credentialsExits) { return true; } else { _outputPresenter.Info("GitLab authorization options are not set"); return false; } } } }
using GitlabCmd.Console.Configuration; namespace GitlabCmd.Console.App { public class AppSettingsValidationHandler { private readonly AppSettings _settings; private readonly OutputPresenter _outputPresenter; public AppSettingsValidationHandler( AppSettings settings, OutputPresenter outputPresenter) { _settings = settings; _outputPresenter = outputPresenter; } public bool Validate() { if (string.IsNullOrEmpty(_settings.GitLabHostUrl)) { _outputPresenter.Info("GitLabHostUrl is not set"); return false; } return true; } } }
mit
C#
8128cad3d18a75e25dbd4b38dcb4118f408c601e
fix test that i just pushed that should use inmemory connection
LeoYao/elasticsearch-net,wawrzyn/elasticsearch-net,junlapong/elasticsearch-net,robrich/elasticsearch-net,robrich/elasticsearch-net,abibell/elasticsearch-net,SeanKilleen/elasticsearch-net,wawrzyn/elasticsearch-net,robertlyson/elasticsearch-net,robertlyson/elasticsearch-net,junlapong/elasticsearch-net,faisal00813/elasticsearch-net,mac2000/elasticsearch-net,faisal00813/elasticsearch-net,robertlyson/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,DavidSSL/elasticsearch-net,starckgates/elasticsearch-net,DavidSSL/elasticsearch-net,joehmchan/elasticsearch-net,starckgates/elasticsearch-net,LeoYao/elasticsearch-net,gayancc/elasticsearch-net,DavidSSL/elasticsearch-net,joehmchan/elasticsearch-net,SeanKilleen/elasticsearch-net,junlapong/elasticsearch-net,LeoYao/elasticsearch-net,robrich/elasticsearch-net,faisal00813/elasticsearch-net,wawrzyn/elasticsearch-net,gayancc/elasticsearch-net,abibell/elasticsearch-net,starckgates/elasticsearch-net,SeanKilleen/elasticsearch-net,gayancc/elasticsearch-net,joehmchan/elasticsearch-net,mac2000/elasticsearch-net
src/Tests/Nest.Tests.Unit/Reproduce/Reproduce1440Tests.cs
src/Tests/Nest.Tests.Unit/Reproduce/Reproduce1440Tests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Elasticsearch.Net.Connection; using FluentAssertions; using Nest.Tests.MockData.Domain; using NUnit.Framework; namespace Nest.Tests.Unit.Reproduce { /// <summary> /// tests to reproduce reported errors /// </summary> [TestFixture] public class Reproduce1440Tests : BaseJsonTests { [Test] public void CountShouldNotThrowWhenNoDefaultIndexSpecified() { var client = new ElasticClient(connection: new InMemoryConnection(new ConnectionSettings())); var request = client.Count<ElasticsearchProject>(); var path = new Uri(request.ConnectionStatus.RequestUrl).AbsolutePath; path.Should().Be("/_all/elasticsearchprojects/_count"); request = client.Count<ElasticsearchProject>(c=>c.Index("x")); path = new Uri(request.ConnectionStatus.RequestUrl).AbsolutePath; path.Should().Be("/x/elasticsearchprojects/_count"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using FluentAssertions; using Nest.Tests.MockData.Domain; using NUnit.Framework; namespace Nest.Tests.Unit.Reproduce { /// <summary> /// tests to reproduce reported errors /// </summary> [TestFixture] public class Reproduce1440Tests : BaseJsonTests { [Test] public void CountShouldNotThrowWhenNoDefaultIndexSpecified() { var client = new ElasticClient(); var request = client.Count<ElasticsearchProject>(); var path = new Uri(request.ConnectionStatus.RequestUrl).AbsolutePath; path.Should().Be("/_all/elasticsearchprojects/_count"); request = client.Count<ElasticsearchProject>(c=>c.Index("x")); path = new Uri(request.ConnectionStatus.RequestUrl).AbsolutePath; path.Should().Be("/x/elasticsearchprojects/_count"); } } }
apache-2.0
C#
9874da29ef51e69be088186179c9ed69ed6bd8d8
debug tags
DMagic1/KSP_Contract_Window,Kerbas-ad-astra/KSP_Contract_Window
QuickStart.cs
QuickStart.cs
#if DEBUG using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace QuickStart { //This will kick us into the save called default and set the first vessel active [KSPAddon(KSPAddon.Startup.MainMenu, false)] public class Debug_AutoLoadPersistentSaveOnStartup : MonoBehaviour { public static bool first = true; public static int vId = 0; public void Start () { if (first) { first = false; HighLogic.SaveFolder = "Contracts Ahoy"; var game = GamePersistence.LoadGame ("persistent" , HighLogic.SaveFolder , true , false); if (game != null && game.flightState != null && game.compatible) { List<ProtoVessel> allVessels = game.flightState.protoVessels; int suitableVessel = 0; for (vId = 0; vId < allVessels.Count; vId++) { switch (allVessels [vId].vesselType) { case VesselType.SpaceObject: continue; // asteroids case VesselType.Unknown: continue; // asteroids in facepaint case VesselType.EVA: continue; default: suitableVessel = vId; break; // this one will do } /* If you want a more stringent filter than * "vessel is not inert ball of space dirt", then you * will want to do it here. */ } HighLogic.LoadScene(GameScenes.SPACECENTER); //FlightDriver.StartAndFocusVessel (game , suitableVessel); } CheatOptions.InfiniteFuel = true; } } } } #endif
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace QuickStart { //This will kick us into the save called default and set the first vessel active [KSPAddon(KSPAddon.Startup.MainMenu, false)] public class Debug_AutoLoadPersistentSaveOnStartup : MonoBehaviour { public static bool first = true; public static int vId = 0; public void Start () { if (first) { first = false; HighLogic.SaveFolder = "Contracts Ahoy"; var game = GamePersistence.LoadGame ("persistent" , HighLogic.SaveFolder , true , false); if (game != null && game.flightState != null && game.compatible) { List<ProtoVessel> allVessels = game.flightState.protoVessels; int suitableVessel = 0; for (vId = 0; vId < allVessels.Count; vId++) { switch (allVessels [vId].vesselType) { case VesselType.SpaceObject: continue; // asteroids case VesselType.Unknown: continue; // asteroids in facepaint case VesselType.EVA: continue; default: suitableVessel = vId; break; // this one will do } /* If you want a more stringent filter than * "vessel is not inert ball of space dirt", then you * will want to do it here. */ } HighLogic.LoadScene(GameScenes.SPACECENTER); //FlightDriver.StartAndFocusVessel (game , suitableVessel); } CheatOptions.InfiniteFuel = true; } } } }
mit
C#
19e693fe8f0f5932fbb527f6d6f12b8bb328a569
チェックする変数を間違えていたので修正。
SunriseDigital/cs-sdx
Sdx/Config.cs
Sdx/Config.cs
using System.Collections.Generic; using Sdx.Data; using System.Text; using System.IO; using System; namespace Sdx { public class Config<T> where T : Tree, new() { private static Dictionary<string, Tree> memoryCache; static Config() { memoryCache = new Dictionary<string, Tree>(); } public string BaseDir { get; set; } public Tree Get(string fileName) { return this.CreateTree(fileName, null, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, string extension) { return this.CreateTree(fileName, extension, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, Encoding encoding) { return this.CreateTree(fileName, null, encoding); } public Tree Get(string fileName, string extension, Encoding encoding) { return this.CreateTree(fileName, extension, encoding); } public void ClearCache() { memoryCache.Clear(); } private Tree CreateTree(string fileName, string extension, Encoding encoding) { //置換しないとBaseを`/path/to/foo`まで含めたGet("bar")と、`/path/to`の時のGet("foo/bar")が //同じファイルを指しているのに別のキャッシュになる fileName = fileName.Replace('/', Path.DirectorySeparatorChar); Tree tree = new T(); var path = BaseDir + Path.DirectorySeparatorChar + fileName; if (extension != null) { path += "." + extension; } if(memoryCache.ContainsKey(path)) { return memoryCache[path]; } using (var fs = new FileStream(path, FileMode.Open)) { var input = new StreamReader(fs, encoding); tree.Load(input); } memoryCache[path] = tree; return tree; } } }
using System.Collections.Generic; using Sdx.Data; using System.Text; using System.IO; namespace Sdx { public class Config<T> where T : Tree, new() { private static Dictionary<string, Tree> memoryCache; static Config() { memoryCache = new Dictionary<string, Tree>(); } public string BaseDir { get; set; } public Tree Get(string fileName) { return this.CreateTree(fileName, null, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, string extension) { return this.CreateTree(fileName, extension, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, Encoding encoding) { return this.CreateTree(fileName, null, encoding); } public Tree Get(string fileName, string extension, Encoding encoding) { return this.CreateTree(fileName, extension, encoding); } public void ClearCache() { memoryCache.Clear(); } private Tree CreateTree(string fileName, string extension, Encoding encoding) { //置換しないとBaseを`/path/to/foo`まで含めたGet("bar")と、`/path/to`の時のGet("foo/bar")が //同じファイルを指しているのに別のキャッシュになる fileName = fileName.Replace('/', Path.DirectorySeparatorChar); Tree tree = new T(); var path = BaseDir + Path.DirectorySeparatorChar + fileName; if (encoding != null) { path += "." + extension; } if(memoryCache.ContainsKey(path)) { return memoryCache[path]; } using (var fs = new FileStream(path, FileMode.Open)) { var input = new StreamReader(fs, encoding); tree.Load(input); } memoryCache[path] = tree; return tree; } } }
mit
C#
130b999a58632cd1a17947cb00f2cb2cda75d18a
Remove RegexOptions.Compiled per review.
chocolatey/nuget-chocolatey,zskullz/nuget,jholovacs/NuGet,antiufo/NuGet2,mrward/NuGet.V2,dolkensp/node.net,chester89/nugetApi,indsoft/NuGet2,jholovacs/NuGet,rikoe/nuget,indsoft/NuGet2,jmezach/NuGet2,zskullz/nuget,oliver-feng/nuget,mono/nuget,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,GearedToWar/NuGet2,jholovacs/NuGet,themotleyfool/NuGet,akrisiun/NuGet,chocolatey/nuget-chocolatey,alluran/node.net,ctaggart/nuget,mrward/nuget,alluran/node.net,mrward/NuGet.V2,mrward/nuget,pratikkagda/nuget,antiufo/NuGet2,jholovacs/NuGet,xero-github/Nuget,RichiCoder1/nuget-chocolatey,GearedToWar/NuGet2,antiufo/NuGet2,ctaggart/nuget,mrward/nuget,mrward/nuget,oliver-feng/nuget,jmezach/NuGet2,akrisiun/NuGet,antiufo/NuGet2,xoofx/NuGet,rikoe/nuget,OneGet/nuget,jmezach/NuGet2,mrward/NuGet.V2,alluran/node.net,chocolatey/nuget-chocolatey,kumavis/NuGet,pratikkagda/nuget,GearedToWar/NuGet2,oliver-feng/nuget,zskullz/nuget,dolkensp/node.net,xoofx/NuGet,jmezach/NuGet2,indsoft/NuGet2,xoofx/NuGet,ctaggart/nuget,jholovacs/NuGet,chocolatey/nuget-chocolatey,indsoft/NuGet2,ctaggart/nuget,themotleyfool/NuGet,mrward/NuGet.V2,mono/nuget,indsoft/NuGet2,jholovacs/NuGet,anurse/NuGet,RichiCoder1/nuget-chocolatey,kumavis/NuGet,GearedToWar/NuGet2,GearedToWar/NuGet2,dolkensp/node.net,xoofx/NuGet,pratikkagda/nuget,mrward/nuget,jmezach/NuGet2,mrward/NuGet.V2,zskullz/nuget,mono/nuget,indsoft/NuGet2,GearedToWar/NuGet2,pratikkagda/nuget,chocolatey/nuget-chocolatey,mrward/NuGet.V2,OneGet/nuget,atheken/nuget,chocolatey/nuget-chocolatey,dolkensp/node.net,OneGet/nuget,oliver-feng/nuget,antiufo/NuGet2,anurse/NuGet,xoofx/NuGet,xoofx/NuGet,oliver-feng/nuget,pratikkagda/nuget,rikoe/nuget,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,alluran/node.net,oliver-feng/nuget,rikoe/nuget,atheken/nuget,mrward/nuget,jmezach/NuGet2,themotleyfool/NuGet,pratikkagda/nuget,chester89/nugetApi,OneGet/nuget,mono/nuget
src/Core/Utility/PackageIdValidator.cs
src/Core/Utility/PackageIdValidator.cs
using System; using System.Globalization; using System.Text.RegularExpressions; using NuGet.Resources; namespace NuGet { public static class PackageIdValidator { private static readonly Regex _idRegex = new Regex(@"^\w+([_.-]\w+)*$", RegexOptions.IgnoreCase); public static bool IsValidPackageId(string packageId) { if (packageId == null) { throw new ArgumentNullException("packageId"); } return _idRegex.IsMatch(packageId); } public static void ValidatePackageId(string packageId) { if (!IsValidPackageId(packageId)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InvalidPackageId, packageId)); } } } }
using System; using System.Globalization; using System.Text.RegularExpressions; using NuGet.Resources; namespace NuGet { public static class PackageIdValidator { private static readonly Regex _idRegex = new Regex(@"^\w+([_.-]\w+)*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static bool IsValidPackageId(string packageId) { if (packageId == null) { throw new ArgumentNullException("packageId"); } return _idRegex.IsMatch(packageId); } public static void ValidatePackageId(string packageId) { if (!IsValidPackageId(packageId)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InvalidPackageId, packageId)); } } } }
apache-2.0
C#
ec0beb5a515e9189615d9fb6c23b956ecf1645ae
Allow logger and serializer to be set to null
exceptionless/Foundatio,FoundatioFx/Foundatio
src/Foundatio/Utility/SharedOptions.cs
src/Foundatio/Utility/SharedOptions.cs
using System; using Foundatio.Serializer; using Microsoft.Extensions.Logging; namespace Foundatio { public class SharedOptions { public ISerializer Serializer { get; set; } public ILoggerFactory LoggerFactory { get; set; } } public class SharedOptionsBuilder<TOption, TBuilder> : OptionsBuilder<TOption> where TOption : SharedOptions, new() where TBuilder : SharedOptionsBuilder<TOption, TBuilder> { public TBuilder Serializer(ISerializer serializer) { Target.Serializer = serializer; return (TBuilder)this; } public TBuilder LoggerFactory(ILoggerFactory loggerFactory) { Target.LoggerFactory = loggerFactory; return (TBuilder)this; } } }
using System; using Foundatio.Serializer; using Microsoft.Extensions.Logging; namespace Foundatio { public class SharedOptions { public ISerializer Serializer { get; set; } public ILoggerFactory LoggerFactory { get; set; } } public class SharedOptionsBuilder<TOption, TBuilder> : OptionsBuilder<TOption> where TOption : SharedOptions, new() where TBuilder : SharedOptionsBuilder<TOption, TBuilder> { public TBuilder Serializer(ISerializer serializer) { Target.Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); ; return (TBuilder)this; } public TBuilder LoggerFactory(ILoggerFactory loggerFactory) { Target.LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); ; return (TBuilder)this; } } }
apache-2.0
C#
01fdd30d515cdc8ef9442dc2c715569f450162fd
add missing textfield types #2217 (#2218)
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/Client/Web/Bit.Client.Web.BlazorUI/Components/TextField/BitTextFieldType.cs
src/Client/Web/Bit.Client.Web.BlazorUI/Components/TextField/BitTextFieldType.cs
namespace Bit.Client.Web.BlazorUI { public enum BitTextFieldType { /// <summary> /// The TextField characters are shown as text /// </summary> Text, /// <summary> /// The TextField characters are masked /// </summary> Password, /// <summary> /// The TextField characters are number /// </summary> Number, /// <summary> /// The TextField act as an email input /// </summary> Email, /// <summary> /// The TextField act as a tel input /// </summary> Tel, /// <summary> /// The TextField act as a url input /// </summary> Url } }
namespace Bit.Client.Web.BlazorUI { public enum BitTextFieldType { /// <summary> /// The TextField characters are shown as text /// </summary> Text, /// <summary> /// The TextField characters are masked /// </summary> Password, /// <summary> /// The TextField characters are number /// </summary> Number } }
mit
C#
e6e9c0ea1be5ad3fe1137f6accff1c7bcd7989ed
Fix Staffer.cs compile error
VernacularHam/macolastand
Assets/Scripts/Staffer.cs
Assets/Scripts/Staffer.cs
using System.Collections; using System.Collections.Generic; public class Staffer { public Staffer() { } private string[] names = { "Aniket", "Joe", "Mike", "Claudia", "Mathew", "Ben", "Stephanie", "Pratap", "Derek", "Connor", "Greta", "John DM", "Debra", "Scott", "Rex" }; }
using System.Collections; using System.Collections.Generic; public class Staffer { public Staffer() { } private string[] names = ["Aniket", "Joe", "Mike", "Claudia", "Mathew", "Ben", "Stephanie", "Pratap", "Derek", "Connor", "Greta", "John DM", "Debra", "Scott", "Rex"]; }
mit
C#
dab4eac3de0b8366ebc29284fc8c8c8a93f3c88b
fix error in reading file version
lexruster/NAppUpdate
FeedBuilder/FileInfoEx.cs
FeedBuilder/FileInfoEx.cs
using System.Diagnostics; using System.IO; using NAppUpdate.Framework.Utils; namespace FeedBuilder { public class FileInfoEx { private readonly FileInfo myFileInfo; private readonly string myFileVersion; private readonly string myHash; public FileInfo FileInfo { get { return myFileInfo; } } public string FileVersion { get { return myFileVersion; } } public string Hash { get { return myHash; } } public string RelativeName { get; private set; } public FileInfoEx(string fileName, int rootDirLength) { myFileInfo = new FileInfo(fileName); var verInfo = FileVersionInfo.GetVersionInfo(fileName); if (verInfo.FileVersion != null) myFileVersion = new System.Version(verInfo.FileMajorPart, verInfo.FileMinorPart, verInfo.FileBuildPart, verInfo.FilePrivatePart).ToString(); myHash = FileChecksum.GetSHA256Checksum(fileName); RelativeName = fileName.Substring(rootDirLength + 1); } } }
using System.Diagnostics; using System.IO; using NAppUpdate.Framework.Utils; namespace FeedBuilder { public class FileInfoEx { private readonly FileInfo myFileInfo; private readonly string myFileVersion; private readonly string myHash; public FileInfo FileInfo { get { return myFileInfo; } } public string FileVersion { get { return myFileVersion; } } public string Hash { get { return myHash; } } public string RelativeName { get; private set; } public FileInfoEx(string fileName, int rootDirLength) { myFileInfo = new FileInfo(fileName); var verInfo = FileVersionInfo.GetVersionInfo(fileName); if (myFileVersion != null) myFileVersion = new System.Version(verInfo.FileMajorPart, verInfo.FileMinorPart, verInfo.FileBuildPart, verInfo.FilePrivatePart).ToString(); myHash = NAppUpdate.Framework.Utils.FileChecksum.GetSHA256Checksum(fileName); RelativeName = fileName.Substring(rootDirLength + 1); } } }
apache-2.0
C#
5674cfaab40158e3e69fb5cd63ca006e84e78b16
Change recieve method
witoong623/TirkxDownloader,witoong623/TirkxDownloader
Models/MessageReciever.cs
Models/MessageReciever.cs
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading; using Caliburn.Micro; using Newtonsoft.Json; using TirkxDownloader.ViewModels; using TirkxDownloader.Framework; namespace TirkxDownloader.Models { public class MessageReciever { private readonly DownloadEngine Engine; private readonly IEventAggregator EventAggregator; private readonly IWindowManager WindowManager; private Thread BackgroundThread; public MessageReciever(IWindowManager windowManager, IEventAggregator eventAggregator, DownloadEngine engine) { WindowManager = windowManager; EventAggregator = eventAggregator; Engine = engine; BackgroundThread = new Thread(StartReciever); } private void StartReciever() { while (true) { var fileInfo = GetFileInfo(); Execute.OnUIThread(() => WindowManager.ShowDialog( new NewDownloadViewModel(WindowManager, EventAggregator, fileInfo, Engine))); } } private TirkxFileInfo GetFileInfo() { using (var listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:6230/"); listener.Start(); var requestContext = listener.GetContext(); var streamReader = new StreamReader(requestContext.Request.InputStream, requestContext.Request.ContentEncoding); string jsonString = streamReader.ReadToEnd(); return JsonConvert.DeserializeObject<TirkxFileInfo>(jsonString); } } public void Start() { BackgroundThread.Start(); } public void Stop() { BackgroundThread.Abort(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Caliburn.Micro; using Newtonsoft.Json; using TirkxDownloader.ViewModels; using TirkxDownloader.Framework; namespace TirkxDownloader.Models { public class MessageReciever { private readonly IEventAggregator EventAggregator; private readonly IWindowManager WindowManager; private Thread BackgroundThread; public MessageReciever(IWindowManager windowManager, IEventAggregator eventAggregator) { WindowManager = windowManager; EventAggregator = eventAggregator; BackgroundThread = new Thread(StartReciever); } private void StartReciever() { while (true) { var fileInfo = GetFileInfo(); Execute.OnUIThread(() => WindowManager.ShowDialog( new NewDownloadViewModel(WindowManager, EventAggregator, fileInfo))); } } private TirkxFileInfo GetFileInfo() { using (var stdin = Console.OpenStandardInput()) { int msgLength = 0; while (true) { byte[] sizeBuffer = new byte[4]; stdin.Read(sizeBuffer, 0, 4); msgLength = BitConverter.ToInt32(sizeBuffer, 0); if (msgLength > 0) { break; } } byte[] msgBuffer = new byte[msgLength]; stdin.Read(msgBuffer, 0, msgLength); var jsonText = Encoding.UTF8.GetString(msgBuffer); return JsonConvert.DeserializeObject<TirkxFileInfo>(jsonText); } } public void Start() { BackgroundThread.Start(); } public void Stop() { BackgroundThread.Abort(); } } }
mit
C#
8e979ffdd6a2b0564704b358bda5dba3d279f06b
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.23.8")] [assembly: AssemblyInformationalVersion("0.23.8")] /* * Version 0.23.8 * * - [FIX] fixed the type name 'TestFixtureFactory' to * 'DefaultFixtureFactory' in the message of the exception thrown by * NotSupportedFixtureFactory.Create. * * - [FIX] fixed that test attributes do not handle exception thrown by the * Setup method of TestAssemblyConfigurationAttribute. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.23.7")] [assembly: AssemblyInformationalVersion("0.23.7")] /* * Version 0.23.8 * * - [FIX] fixed the type name 'TestFixtureFactory' to * 'DefaultFixtureFactory' in the message of the exception thrown by * NotSupportedFixtureFactory.Create. * * - [FIX] fixed that test attributes do not handle exception thrown by the * Setup method of TestAssemblyConfigurationAttribute. */
mit
C#
8fcc89add04b96655663eaac75b56c5d6f2591c8
remove ReFit from IInSkillProductApi
stoiveyp/Alexa.NET.Management
Alexa.NET.Management/IInSkillProductApi.cs
Alexa.NET.Management/IInSkillProductApi.cs
using System.Net.Http; using System.Threading.Tasks; using Alexa.NET.Management.Api; using Alexa.NET.Management.InSkillProduct; using Refit; namespace Alexa.NET.Management { public interface IInSkillProductApi { Task<Product> Get(string productId, SkillStage stage); Task<CreateInSkillProductResponse> Create(Product product); Task<ProductSummary> GetSummary(string productId, SkillStage stage); Task<Product> Update(string productId, SkillStage stage,Product product); Task<bool> Delete(string productId, SkillStage stage); Task<ProductListResponse> Get(); Task<ProductListResponse> Get(int maxResults, GetInSkillProductFilters filters = null); Task<ProductListResponse> Get(int maxResults, string nextToken, GetInSkillProductFilters filters = null); Task<ProductListResponse> GetSkillProducts(string skillId, SkillStage stage); Task<ProductListResponse> GetSkillProducts(string skillId, SkillStage stage, int maxResults); Task<ProductListResponse> GetSkillProducts(string skillId, SkillStage stage, int maxResults, string nextToken); Task<RelatedSkillResponse> GetProductSkills(string productId, SkillStage stage); Task<RelatedSkillResponse> GetProductSkills(string productId, SkillStage stage, int maxResults); Task<RelatedSkillResponse> GetProductSkills(string productId, SkillStage stage, int maxResults, string nextToken); Task<bool> Associate(string productId, string skillId); Task<bool> Disassociate(string productId, string skillId); Task<bool> ResetDeveloperEntitlement(string productId); } }
using System.Net.Http; using System.Threading.Tasks; using Alexa.NET.Management.Api; using Alexa.NET.Management.InSkillProduct; using Refit; namespace Alexa.NET.Management { public interface IInSkillProductApi { [Get("inSkillProducts/{productId}/stages/{stage}")] Task<Product> Get(string productId, SkillStage stage); [Post("inSkillProducts")] Task<CreateInSkillProductResponse> Create([Body]Product product); [Get("inSkillProducts/{productId}/stages/{stage}/summary")] Task<ProductSummary> GetSummary(string productId, SkillStage stage); [Put("inSkillProducts/{productId}/stages/{stage}")] Task<Product> Update(string productId, SkillStage stage, [Body]Product product); [Delete("inSkillProducts/{productId}/stages/{stage}")] Task<bool> Delete(string productId, SkillStage stage); [Get("inSkillProducts")] Task<ProductListResponse> Get(); [Get("inSkillProducts")] Task<ProductListResponse> Get(int maxResults, GetInSkillProductFilters filters = null); [Get("inSkillProducts")] Task<ProductListResponse> Get(int maxResults, string nextToken, GetInSkillProductFilters filters = null); [Get("skills/{skillId}/stages/{stage}/inSkillProducts")] Task<ProductListResponse> GetSkillProducts(string skillId, SkillStage stage); [Get("skills/{skillId}/stages/{stage}/inSkillProducts")] Task<ProductListResponse> GetSkillProducts(string skillId, SkillStage stage, int maxResults); [Get("skills/{skillId}/stages/{stage}/inSkillProducts")] Task<ProductListResponse> GetSkillProducts(string skillId, SkillStage stage, int maxResults, string nextToken); [Get("inSkillProducts/{productId}/stages/{stage}/skills")] Task<RelatedSkillResponse> GetProductSkills(string productId, SkillStage stage); [Get("inSkillProducts/{productId}/stages/{stage}/skills")] Task<RelatedSkillResponse> GetProductSkills(string productId, SkillStage stage, int maxResults); [Get("inSkillProducts/{productId}/stages/{stage}/skills")] Task<RelatedSkillResponse> GetProductSkills(string productId, SkillStage stage, int maxResults, string nextToken); [Get("inSkillProducts/{productId}/skills/{skillId}")] Task<bool> Associate(string productId, string skillId); [Put("inSkillProducts/{productId}/skills/{skillId}")] Task<bool> Disassociate(string productId, string skillId); [Delete("inSkillProducts/{productId}/stages/development/entitlement")] Task<bool> ResetDeveloperEntitlement(string productId); } }
mit
C#
9d3a954f50d1360b3e56cb7ffa6968ed2530bafb
make HelloWorld simpler
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Samples/Common/01_HelloWorld/HelloWorld.cs
Samples/Common/01_HelloWorld/HelloWorld.cs
using Urho; public class _01_HelloWorld : Application { public _01_HelloWorld(Context c) : base(c) { } public override void Start() { var cache = ResourceCache; var helloText = new Text(Context) { Value = "Hello World from Urho3D + Mono", HorizontalAlignment = HorizontalAlignment.HA_CENTER, VerticalAlignment = VerticalAlignment.VA_CENTER }; helloText.SetColor(new Color(0f, 1f, 0f)); helloText.SetFont(cache.GetFont("Fonts/Anonymous Pro.ttf"), 30); UI.Root.AddChild(helloText); } }
using Urho; public class _01_HelloWorld : Sample { void CreateText() { var cache = ResourceCache; var helloText = new Text(Context) { Value = "Hello World from Urho3D + Mono", //Color = new Color (0, 1, 0), HorizontalAlignment = HorizontalAlignment.HA_CENTER, VerticalAlignment = VerticalAlignment.VA_CENTER }; helloText.SetColor(new Color(0f, 1f, 0f)); helloText.SetFont(cache.GetFont("Fonts/Anonymous Pro.ttf"), 30); UI.Root.AddChild(helloText); } public override void Start() { // Execute base class startup base.Start(); // Create "Hello World" Text CreateText(); } public _01_HelloWorld(Context c) : base(c) { } }
mit
C#
a260afa58e7b0e5434d8498e03bf44d29b59c0b1
Throw exceptions if CallbackContext ctor arguments are null
Miruken-DotNet/Miruken
Source/Miruken/Callback/CallbackContext.cs
Source/Miruken/Callback/CallbackContext.cs
namespace Miruken.Callback { using System; using Policy.Bindings; public class CallbackContext { public CallbackContext( object callback, IHandler composer, MemberBinding binding) { Callback = callback ?? throw new ArgumentNullException(nameof(callback)); Composer = composer ?? throw new ArgumentNullException(nameof(composer)); Binding = binding ?? throw new ArgumentNullException(nameof(binding)); } public object Callback { get; } public IHandler Composer { get; } public MemberBinding Binding { get; } public bool Unhandled { get; private set; } public void NotHandled() { Unhandled = true; } public TRet NotHandled<TRet>(TRet result = default) { Unhandled = true; return result; } } }
namespace Miruken.Callback { using Policy.Bindings; public class CallbackContext { public CallbackContext( object callback, IHandler composer, MemberBinding binding) { Callback = callback; Composer = composer; Binding = binding; } public object Callback { get; } public IHandler Composer { get; } public MemberBinding Binding { get; } public bool Unhandled { get; private set; } public void NotHandled() { Unhandled = true; } public TRet NotHandled<TRet>(TRet result = default) { Unhandled = true; return result; } } }
mit
C#
2e0ca4e959a1c5c0312aba0e2993dc3fb4284402
add a string test
TestFirstNet/TestFirst.Net,activelylazy/TestFirst.Net,TestFirstNet/TestFirst.Net,activelylazy/TestFirst.Net
TestFirst.Net.Tests/Matcher/AnArrayTest.cs
TestFirst.Net.Tests/Matcher/AnArrayTest.cs
using NUnit.Framework; using TestFirst.Net.Matcher; using System; namespace TestFirst.Net.Test.Matcher { [TestFixture] public class AnArrayTest : BaseMatcherTest { [Test] public void EqualTo() { AssertPasses((byte[])null, AnArray.EqualTo((byte[])null)); AssertPasses(new byte[]{}, AnArray.EqualTo(new byte[]{})); AssertFails(new byte[] { }, AnArray.EqualTo((byte[])null)); AssertFails(null, AByteArray.EqualTo(new byte[] { })); AssertFails(new byte[] { 1 }, AnArray.EqualTo(new byte[] { })); AssertFails(new byte[] { }, AnArray.EqualTo(new byte[] { 1 })); AssertPasses(new byte[] { 1, 2, 3 }, AnArray.EqualTo(new byte[] { 1, 2, 3 })); AssertPasses(new String[] { "Alice","Bob","Tim" }, AnArray.EqualTo(new String[] { "Alice", "Bob", "Tim" })); var b = RandomBytes(); AssertPasses(b, AnArray.EqualTo(b)); } [Test] public void Null() { AssertPasses(null, AnArray.Null<string>()); AssertPasses(null, AnArray.Null<int?>()); AssertFails(new string[] { }, AnArray.Null<string>()); AssertFails(new int?[] { }, AnArray.Null<int?>()); } [Test] public void NotNull() { AssertPasses(new string[] { }, AnArray.NotNull<string>()); AssertPasses(new int?[] { }, AnArray.NotNull<int?>()); AssertFails(null, AnArray.NotNull<string>()); AssertFails(null, AnArray.NotNull<int?>()); } private static byte[] RandomBytes() { return new TestFirst.Net.Random.Random().Bytes(); } } }
using NUnit.Framework; using TestFirst.Net.Matcher; namespace TestFirst.Net.Test.Matcher { [TestFixture] public class AnArrayTest : BaseMatcherTest { [Test] public void EqualTo() { AssertPasses((byte[])null, AnArray.EqualTo((byte[])null)); AssertPasses(new byte[]{}, AnArray.EqualTo(new byte[]{})); AssertFails(new byte[] { }, AnArray.EqualTo((byte[])null)); AssertFails(null, AByteArray.EqualTo(new byte[] { })); AssertFails(new byte[] { 1 }, AnArray.EqualTo(new byte[] { })); AssertFails(new byte[] { }, AnArray.EqualTo(new byte[] { 1 })); AssertPasses(new byte[] { 1, 2, 3 }, AnArray.EqualTo(new byte[] { 1, 2, 3 })); var b = RandomBytes(); AssertPasses(b, AnArray.EqualTo(b)); } [Test] public void Null() { AssertPasses(null, AnArray.Null<string>()); AssertPasses(null, AnArray.Null<int?>()); AssertFails(new string[] { }, AnArray.Null<string>()); AssertFails(new int?[] { }, AnArray.Null<int?>()); } [Test] public void NotNull() { AssertPasses(new string[] { }, AnArray.NotNull<string>()); AssertPasses(new int?[] { }, AnArray.NotNull<int?>()); AssertFails(null, AnArray.NotNull<string>()); AssertFails(null, AnArray.NotNull<int?>()); } private static byte[] RandomBytes() { return new TestFirst.Net.Random.Random().Bytes(); } } }
bsd-2-clause
C#
ac5ac697599a524914222ec0940adca3d2ece422
Allow overriding ReadFile.Name
nano-byte/common,nano-byte/common
src/Common/Storage/ReadFile.cs
src/Common/Storage/ReadFile.cs
// Copyright Bastian Eicher // Licensed under the MIT License using System; using System.ComponentModel; using System.IO; using NanoByte.Common.Properties; using NanoByte.Common.Streams; using NanoByte.Common.Tasks; using NanoByte.Common.Threading; namespace NanoByte.Common.Storage { /// <summary> /// Reads a file from disk to a stream. /// </summary> public sealed class ReadFile : TaskBase { private readonly string _path; private readonly Action<Stream> _callback; /// <summary> /// Creates a new file read task. /// </summary> /// <param name="path">The path of the file to read.</param> /// <param name="callback">Called with a stream providing the file content.</param> /// <param name="name">A name describing the task in human-readable form.</param> public ReadFile([Localizable(false)] string path, Action<Stream> callback, [Localizable(true)] string? name = null) { _path = path ?? throw new ArgumentNullException(nameof(path)); _callback = callback ?? throw new ArgumentNullException(nameof(callback)); Name = name ?? string.Format(Resources.ReadingFile, _path); } /// <inheritdoc/> public override string Name { get; } /// <inheritdoc/> protected override bool UnitsByte => true; /// <inheritdoc/> protected override void Execute() { State = TaskState.Header; UnitsTotal = new FileInfo(_path).Length; State = TaskState.Data; using var stream = new ProgressStream( File.OpenRead(_path), new SynchronousProgress<long>(bytes => UnitsProcessed = bytes), CancellationToken); _callback(stream); } } }
// Copyright Bastian Eicher // Licensed under the MIT License using System; using System.ComponentModel; using System.IO; using NanoByte.Common.Properties; using NanoByte.Common.Streams; using NanoByte.Common.Tasks; using NanoByte.Common.Threading; namespace NanoByte.Common.Storage { /// <summary> /// Reads a file from disk to a stream. /// </summary> public sealed class ReadFile : TaskBase { private readonly string _path; private readonly Action<Stream> _callback; /// <summary> /// Creates a new file read task. /// </summary> /// <param name="path">The path of the file to read.</param> /// <param name="callback">Called with a stream providing the file content.</param> public ReadFile([Localizable(false)] string path, Action<Stream> callback) { _path = path ?? throw new ArgumentNullException(nameof(path)); _callback = callback ?? throw new ArgumentNullException(nameof(callback)); } /// <inheritdoc/> public override string Name => string.Format(Resources.ReadingFile, _path); /// <inheritdoc/> protected override bool UnitsByte => true; /// <inheritdoc/> protected override void Execute() { State = TaskState.Header; UnitsTotal = new FileInfo(_path).Length; State = TaskState.Data; using var stream = new ProgressStream( File.OpenRead(_path), new SynchronousProgress<long>(bytes => UnitsProcessed = bytes), CancellationToken); _callback(stream); } } }
mit
C#
63e3c3eb82c5ae7b28c372c9518331606413ec55
add AllowPartiallyTrustedCallersAttribute to assembly (#110)
Microsoft/Microsoft.IO.RecyclableMemoryStream,maxwellb/Microsoft.IO.RecyclableMemoryStream
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("Microsoft.IO.RecyclableMemoryStream")] [assembly: AssemblyDescription("Pooled memory allocator.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft.IO.RecyclableMemoryStream")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("9ca0730b-3653-4fc4-b722-9e59fa70ea0b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.5.0")] [assembly: AssemblyFileVersion("1.3.5.0")] [assembly: CLSCompliant(true)] #if !NOFRIENDASSEMBLY [assembly: InternalsVisibleTo("Microsoft.IO.RecyclableMemoryStream.UnitTests")] #endif [assembly: AllowPartiallyTrustedCallers]
using System; 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("Microsoft.IO.RecyclableMemoryStream")] [assembly: AssemblyDescription("Pooled memory allocator.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft.IO.RecyclableMemoryStream")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("9ca0730b-3653-4fc4-b722-9e59fa70ea0b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.5.0")] [assembly: AssemblyFileVersion("1.3.5.0")] [assembly: CLSCompliant(true)] #if !NOFRIENDASSEMBLY [assembly: InternalsVisibleTo("Microsoft.IO.RecyclableMemoryStream.UnitTests")] #endif
mit
C#
31f6ebdf1dc92b3dba34bef4640839cb6c3fd5e2
Copy dummy dll to x86 directories
bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity
build.cake
build.cake
#tool "nuget:?package=NUnit.ConsoleRunner" var target = Argument("target", "Default"); var solution = File("./Bugsnag.Unity.sln"); var configuration = Argument("configuration", "Release"); var outputPath = Argument<string>("output", "C:/Users/marti/Documents/bugsnag-unity-test"); Task("Restore-NuGet-Packages") .Does(() => NuGetRestore(solution)); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild(solution, settings => settings .SetVerbosity(Verbosity.Minimal) .SetConfiguration(configuration)); }); Task("Test") .IsDependentOn("Build") .Does(() => { var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll"); NUnit3(assemblies); }); Task("CopyToUnity") .WithCriteria(() => outputPath != null) .IsDependentOn("Build") .Does(() => { CopyFileToDirectory($"./src/Bugsnag.Native/bin/{configuration}/net35/Bugsnag.Native.dll", $"{outputPath}/Assets/Plugins/x86"); CopyFileToDirectory($"./src/Bugsnag.Native/bin/{configuration}/net35/Bugsnag.Native.dll", $"{outputPath}/Assets/Plugins/x86_64"); CopyFileToDirectory($"./src/Bugsnag.Native.Android/bin/{configuration}/net35/Bugsnag.Native.dll", $"{outputPath}/Assets/Plugins/Android"); CopyFileToDirectory($"./src/Bugsnag.Unity/bin/{configuration}/net35/Bugsnag.Unity.dll", $"{outputPath}/Assets/Standard Assets/Bugsnag"); CopyFileToDirectory($"./src/Assets/Standard Assets/Bugsnag/Bugsnag.cs", $"{outputPath}/Assets/Standard Assets/Bugsnag"); }); Task("Default") .IsDependentOn("Test") .IsDependentOn("CopyToUnity"); RunTarget(target);
#tool "nuget:?package=NUnit.ConsoleRunner" var target = Argument("target", "Default"); var solution = File("./Bugsnag.Unity.sln"); var configuration = Argument("configuration", "Release"); var outputPath = Argument<string>("output", "C:/Users/marti/Documents/bugsnag-unity-test"); Task("Restore-NuGet-Packages") .Does(() => NuGetRestore(solution)); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild(solution, settings => settings .SetVerbosity(Verbosity.Minimal) .SetConfiguration(configuration)); }); Task("Test") .IsDependentOn("Build") .Does(() => { var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll"); NUnit3(assemblies); }); Task("CopyToUnity") .WithCriteria(() => outputPath != null) .IsDependentOn("Build") .Does(() => { CopyFileToDirectory($"./src/Bugsnag.Native.Android/bin/{configuration}/net35/Bugsnag.Native.dll", $"{outputPath}/Assets/Plugins/Android/"); CopyFileToDirectory($"./src/Bugsnag.Unity/bin/{configuration}/net35/Bugsnag.Unity.dll", $"{outputPath}/Assets/Standard Assets/Bugsnag"); CopyFileToDirectory($"./src/Assets/Standard Assets/Bugsnag/Bugsnag.cs", $"{outputPath}/Assets/Standard Assets/Bugsnag"); }); Task("Default") .IsDependentOn("Test") .IsDependentOn("CopyToUnity"); RunTarget(target);
mit
C#
3a4efce010c1d27c55e0454ecfb2601a87c88974
add codecover
rmterra/NesZord
build.cake
build.cake
#addin Cake.Coveralls #tool "xunit.runner.console" #tool "nuget:?package=OpenCover" #tool coveralls.io var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var outDir = "./artifacts"; var solution = "./src/NesZord.sln"; var testProjects = $"./src/**/bin/{configuration}/*.Tests.New.dll"; Task("Restore-NuGet-Packages") .Does(() => { NuGetRestore(solution); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild(solution, new MSBuildSettings { Configuration = configuration, Verbosity = Verbosity.Minimal, ToolVersion = MSBuildToolVersion.VS2017 }); }); Task("RunTests") .IsDependentOn("Build") .Does(() => { OpenCover(tool => { tool.XUnit2(testProjects, new XUnit2Settings { ShadowCopy = false, XmlReport = true, OutputDirectory = outDir }); }, new FilePath("./coverage.xml"), new OpenCoverSettings() .WithFilter("+[NesZord.*]*") .WithFilter("-[NesZord.Tests.*]*")); }); Task("Upload-Coverage-Report") .IsDependentOn("RunTests") .Does(() => { CoverallsIo("./coverage.xml"); }); Task("Default") .IsDependentOn("RunTests"); Task("AppVeyor") .IsDependentOn("Upload-Coverage-Report"); RunTarget(target);
#addin Cake.Coveralls #tool "xunit.runner.console" #tool coveralls.io var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var outDir = "./artifacts"; var solution = "./src/NesZord.sln"; var testProjects = $"./src/**/bin/{configuration}/*.Tests.New.dll"; Task("Restore-NuGet-Packages") .Does(() => { NuGetRestore(solution); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild(solution, new MSBuildSettings { Configuration = configuration, Verbosity = Verbosity.Minimal, ToolVersion = MSBuildToolVersion.VS2017 }); }); Task("RunTests") .IsDependentOn("Build") .Does(() => { XUnit2(testProjects, new XUnit2Settings { XmlReport = true, OutputDirectory = outDir }); }); Task("Upload-Coverage-Report") .IsDependentOn("RunTests") .Does(() => { CoverallsIo("coverage.xml"); }); Task("Default") .IsDependentOn("RunTests"); Task("AppVeyor") .IsDependentOn("Upload-Coverage-Report"); RunTarget(target);
apache-2.0
C#
6cfdc2a1b5f40476931d4178d6cb578a55fc2652
Add configuration arg
Redth/Cake.Android.Adb
build.cake
build.cake
#tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0 var sln = "./Cake.Android.Adb.sln"; var nuspec = "./Cake.Android.Adb.nuspec"; var target = Argument ("target", "all"); var configuration = Argument ("configuration", "Release"); var NUGET_VERSION = Argument("nugetversion", "0.9999"); var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip"; var SDK_VERSION = "25.2.3"; Task ("externals") .WithCriteria (!FileExists ("./android-sdk/android-sdk.zip")) .Does (() => { var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx"); if (IsRunningOnWindows ()) url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows"); EnsureDirectoryExists ("./android-sdk/"); DownloadFile (url, "./android-sdk/android-sdk.zip"); Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/"); // Install platform-tools so we get adb StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" }); }); Task ("libs").Does (() => { NuGetRestore (sln); DotNetBuild (sln, c => c.Configuration = configuration); }); Task ("nuget").IsDependentOn ("libs").Does (() => { CreateDirectory ("./nupkg/"); NuGetPack (nuspec, new NuGetPackSettings { Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./nupkg/", Version = NUGET_VERSION, // NuGet messes up path on mac, so let's add ./ in front again BasePath = "././", }); }); Task("tests").IsDependentOn("libs").Does(() => { NUnit3("./**/bin/" + configuration + "/*.Tests.dll"); }); Task ("clean").Does (() => { CleanDirectories ("./**/bin"); CleanDirectories ("./**/obj"); CleanDirectories ("./**/Components"); CleanDirectories ("./**/tools"); DeleteFiles ("./**/*.apk"); }); Task ("all").IsDependentOn("nuget").IsDependentOn ("tests"); RunTarget (target);
#tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0 var sln = "./Cake.Android.Adb.sln"; var nuspec = "./Cake.Android.Adb.nuspec"; var target = Argument ("target", "all"); var NUGET_VERSION = Argument("nugetversion", "0.9999"); var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip"; var SDK_VERSION = "25.2.3"; Task ("externals") .WithCriteria (!FileExists ("./android-sdk/android-sdk.zip")) .Does (() => { var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx"); if (IsRunningOnWindows ()) url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows"); EnsureDirectoryExists ("./android-sdk/"); DownloadFile (url, "./android-sdk/android-sdk.zip"); Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/"); // Install platform-tools so we get adb StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" }); }); Task ("libs").Does (() => { NuGetRestore (sln); DotNetBuild (sln, c => c.Configuration = "Release"); }); Task ("nuget").IsDependentOn ("libs").Does (() => { CreateDirectory ("./nupkg/"); NuGetPack (nuspec, new NuGetPackSettings { Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./nupkg/", Version = NUGET_VERSION, // NuGet messes up path on mac, so let's add ./ in front again BasePath = "././", }); }); Task("tests").IsDependentOn("libs").Does(() => { NUnit3("./**/bin/"+ configuration + "/*.Tests.dll"); }); Task ("clean").Does (() => { CleanDirectories ("./**/bin"); CleanDirectories ("./**/obj"); CleanDirectories ("./**/Components"); CleanDirectories ("./**/tools"); DeleteFiles ("./**/*.apk"); }); Task ("all").IsDependentOn("nuget").IsDependentOn ("tests"); RunTarget (target);
mit
C#
5d033f123bb6b94ac00d17b09a2612cfe706f8e0
optimize imports
invisiblecloud/InvoiceCaptureLib
test/Model/FindDebtsTest.cs
test/Model/FindDebtsTest.cs
using System; using InvisibleCollectorLib.Model; using NUnit.Framework; using test.Utils; namespace test.Model { [TestFixture] public class FindDebtsTest { [Test] public void GetSendableStringDictionary_correct() { var findDebts = new FindDebts { Number = "123", ToDate = new DateTime(2010, 1, 1), FromDate = null }; var dictionary = findDebts.SendableStringDictionary; TestingUtils.AssertDictionaryContainsItems(dictionary, ("number", "123"), ("to_date", "2010-01-01"), ("from_date", "") ); } } }
using System; using System.Collections.Generic; using InvisibleCollectorLib.Model; using NUnit.Framework; using test.Utils; using InvisibleCollectorLib.Utils; namespace test.Model { [TestFixture] public class FindDebtsTest { [Test] public void GetSendableStringDictionary_correct() { var findDebts = new FindDebts { Number = "123", ToDate = new DateTime(2010, 1, 1), FromDate = null }; var dictionary = findDebts.SendableStringDictionary; TestingUtils.AssertDictionaryContainsItems(dictionary, ("number", "123"), ("to_date", "2010-01-01"), ("from_date", "") ); } } }
mit
C#
435f0cf2bbc0c83ba8073bd086887e696a05c007
Make IsExternalInit internal (#2513)
joemcbride/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet
src/GraphQL.Tests/IsExternalInit.cs
src/GraphQL.Tests/IsExternalInit.cs
#if !NET5 using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } } #endif
#if !NET5 using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class IsExternalInit { } } #endif
mit
C#
db1b82e2dc0dbdd946ba186e6f5a5085ad06811d
Fix for Issue #8
CaptiveAire/Seq.App.YouTrack
src/Helpers/UriBuilderExtensions.cs
src/Helpers/UriBuilderExtensions.cs
// Copyright 2014-2017 CaptiveAire Systems // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Seq.App.YouTrack.Helpers { using System; public static class UriBuilderExtensions { public static string GetPathOrEmptyAsNull(this UriBuilder uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); return uri.Path == @"/" ? null : uri.Path; } public static bool IsSSL(this UriBuilder uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); return uri.Scheme == "https"; } public static string ToFormattedUrl(this UriBuilder uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); string url; if (uri.Uri.IsDefaultPort && uri.Port != -1) { uri.Port = -1; url = uri.ToString(); } else { url = uri.ToString(); } if (url.EndsWith("/")) { return url.Substring(0, url.Length - 1); } return url; } } }
// Copyright 2014-2017 CaptiveAire Systems // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Seq.App.YouTrack.Helpers { using System; public static class UriBuilderExtensions { public static string GetPathOrEmptyAsNull(this UriBuilder uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); return uri.Path == @"/" ? null : uri.Path; } public static bool IsSSL(this UriBuilder uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); return uri.Scheme == "https"; } public static string ToFormattedUrl(this UriBuilder uri) { if (uri == null) throw new ArgumentNullException(nameof(uri)); var url = uri.ToString().Replace(":80", string.Empty); if (url.EndsWith("/")) { return url.Substring(0, url.Length - 1); } return url; } } }
apache-2.0
C#
679dba7531d3be10b387203c9a9f350f39ea3a8a
Add guard for runtimes that support large arrays (#36883)
ericstj/corefx,BrennanConroy/corefx,shimingsg/corefx,shimingsg/corefx,ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,ViktorHofer/corefx,wtgodbe/corefx,wtgodbe/corefx,wtgodbe/corefx,shimingsg/corefx,wtgodbe/corefx,BrennanConroy/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,BrennanConroy/corefx,ericstj/corefx
src/System.IO/tests/MemoryStream/MemoryStream.ConstructorTests.cs
src/System.IO/tests/MemoryStream/MemoryStream.ConstructorTests.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 Xunit; namespace System.IO.Tests { public class MemoryStream_ConstructorTests { [Theory] [InlineData(10, -1, int.MaxValue)] [InlineData(10, 6, -1)] public static void MemoryStream_Ctor_NegativeIndeces(int arraySize, int index, int count) { Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryStream(new byte[arraySize], index, count)); } [Theory] [InlineData(1, 2, 1)] [InlineData(7, 8, 2)] public static void MemoryStream_Ctor_OutOfRangeIndeces(int arraySize, int index, int count) { AssertExtensions.Throws<ArgumentException>(null, () => new MemoryStream(new byte[arraySize], index, count)); } [Fact] public static void MemoryStream_Ctor_NullArray() { Assert.Throws<ArgumentNullException>(() => new MemoryStream(null, 5, 2)); } [Fact] public static void MemoryStream_Ctor_InvalidCapacities() { Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryStream(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryStream(-1)); if (PlatformDetection.IsNotIntMaxValueArrayIndexSupported) { Assert.Throws<OutOfMemoryException>(() => new MemoryStream(int.MaxValue)); } } } }
// 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 Xunit; namespace System.IO.Tests { public class MemoryStream_ConstructorTests { [Theory] [InlineData(10, -1, int.MaxValue)] [InlineData(10, 6, -1)] public static void MemoryStream_Ctor_NegativeIndeces(int arraySize, int index, int count) { Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryStream(new byte[arraySize], index, count)); } [Theory] [InlineData(1, 2, 1)] [InlineData(7, 8, 2)] public static void MemoryStream_Ctor_OutOfRangeIndeces(int arraySize, int index, int count) { AssertExtensions.Throws<ArgumentException>(null, () => new MemoryStream(new byte[arraySize], index, count)); } [Fact] public static void MemoryStream_Ctor_NullArray() { Assert.Throws<ArgumentNullException>(() => new MemoryStream(null, 5, 2)); } [Fact] public static void MemoryStream_Ctor_InvalidCapacities() { Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryStream(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryStream(-1)); Assert.Throws<OutOfMemoryException>(() => new MemoryStream(int.MaxValue)); } } }
mit
C#
3db43c9edd110596f0790cf5549271445ae99002
Add external_id to customer
open-pay/openpay-dotnet
Openpay/Entities/Customer.cs
Openpay/Entities/Customer.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Openpay.Entities { public class Customer : OpenpayResourceObject { [JsonProperty(PropertyName = "name")] public String Name { get; set; } [JsonProperty(PropertyName = "email")] public String Email { get; set; } [JsonProperty(PropertyName = "last_name")] public String LastName { get; set; } [JsonProperty(PropertyName = "phone_number")] public String PhoneNumber { get; set; } [JsonProperty(PropertyName = "address")] public Address Address { get; set; } [JsonProperty(PropertyName = "status")] public String Status { get; set; } [JsonProperty(PropertyName = "clabe")] public String CLABE { get; set; } [JsonProperty(PropertyName = "balance")] public Decimal Balance { get; set; } [JsonProperty(PropertyName = "creation_date")] public DateTime? CreationDate { get; set; } [JsonProperty(PropertyName = "requires_account")] public Boolean RequiresAccount { get; set; } [JsonProperty(PropertyName = "external_id")] public String ExternalId { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Openpay.Entities { public class Customer : OpenpayResourceObject { [JsonProperty(PropertyName = "name")] public String Name { get; set; } [JsonProperty(PropertyName = "email")] public String Email { get; set; } [JsonProperty(PropertyName = "last_name")] public String LastName { get; set; } [JsonProperty(PropertyName = "phone_number")] public String PhoneNumber { get; set; } [JsonProperty(PropertyName = "address")] public Address Address { get; set; } [JsonProperty(PropertyName = "status")] public String Status { get; set; } [JsonProperty(PropertyName = "clabe")] public String CLABE { get; set; } [JsonProperty(PropertyName = "balance")] public Decimal Balance { get; set; } [JsonProperty(PropertyName = "creation_date")] public DateTime? CreationDate { get; set; } [JsonProperty(PropertyName = "requires_account")] public Boolean RequiresAccount { get; set; } } }
apache-2.0
C#
213ca3bc11793f16eeec621e8f683de08ca4387c
Update SymbolicLinkReparseData.cs
michaelmelancon/symboliclinksupport
SymbolicLinkSupport/SymbolicLinkReparseData.cs
SymbolicLinkSupport/SymbolicLinkReparseData.cs
using System.Runtime.InteropServices; namespace SymbolicLinkSupport { /// <remarks> /// Refer to http://msdn.microsoft.com/en-us/library/windows/hardware/ff552012%28v=vs.85%29.aspx /// </remarks> [StructLayout(LayoutKind.Sequential)] internal struct SymbolicLinkReparseData { private const int maxUnicodePathLength = 32767 * 2; public uint ReparseTag; public ushort ReparseDataLength; public ushort Reserved; public ushort SubstituteNameOffset; public ushort SubstituteNameLength; public ushort PrintNameOffset; public ushort PrintNameLength; public uint Flags; [MarshalAs(UnmanagedType.ByValArray, SizeConst = maxUnicodePathLength)] public byte[] PathBuffer; } }
using System.Runtime.InteropServices; namespace SymbolicLinkSupport { /// <remarks> /// Refer to http://msdn.microsoft.com/en-us/library/windows/hardware/ff552012%28v=vs.85%29.aspx /// </remarks> [StructLayout(LayoutKind.Sequential)] internal struct SymbolicLinkReparseData { // Not certain about this! private const int maxUnicodePathLength = 260 * 2; public uint ReparseTag; public ushort ReparseDataLength; public ushort Reserved; public ushort SubstituteNameOffset; public ushort SubstituteNameLength; public ushort PrintNameOffset; public ushort PrintNameLength; public uint Flags; [MarshalAs(UnmanagedType.ByValArray, SizeConst = maxUnicodePathLength)] public byte[] PathBuffer; } }
mit
C#
396c03af43753691600bc8e5f0712c39c44f79eb
Test now can run with Mongodb password protected
selganor74/Jarvis.Framework,selganor74/Jarvis.Framework,ProximoSrl/Jarvis.Framework,selganor74/Jarvis.Framework
Jarvis.Framework.Tests/GlobalTestInit.cs
Jarvis.Framework.Tests/GlobalTestInit.cs
using NUnit.Framework; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; [SetUpFixture] public class GlobalSetup { [SetUp] public void Global_initialization_of_all_tests() { var overrideTestDb = Environment.GetEnvironmentVariable("TEST_MONGODB"); if (String.IsNullOrEmpty(overrideTestDb)) return; var overrideTestDbQueryString = Environment.GetEnvironmentVariable("TEST_MONGODB_QUERYSTRING"); var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings"); connectionStringsSection.ConnectionStrings["eventstore"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-es-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["saga"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-saga-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["readmodel"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-readmodel-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["system"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-system-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["engine"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-engine-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["rebus"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-rebus-test" + overrideTestDbQueryString; config.Save(); ConfigurationManager.RefreshSection("connectionStrings"); } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; [SetUpFixture] public class GlobalSetup { [SetUp] public void ShowSomeTrace() { var overrideTestDb = Environment.GetEnvironmentVariable("TEST_MONGODB"); if (String.IsNullOrEmpty(overrideTestDb)) return; var overrideTestDbQueryString = Environment.GetEnvironmentVariable("TEST_MONGODB_QUERYSTRING"); var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings"); connectionStringsSection.ConnectionStrings["eventstore"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-es-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["saga"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-saga-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["readmodel"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-readmodel-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["system"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-system-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["engine"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-engine-test" + overrideTestDbQueryString; connectionStringsSection.ConnectionStrings["rebus"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-rebus-test" + overrideTestDbQueryString; config.Save(); ConfigurationManager.RefreshSection("connectionStrings"); } }
mit
C#
276f5eba60fe42b936301e380b77f0a99a2d3469
Update Run.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
LoginPasswordUtil/C-Sharp-Version/Run.cs
LoginPasswordUtil/C-Sharp-Version/Run.cs
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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. */ /* -> ACLoginPasswordUtil.exe This is my first draft of this (C# version), it may not pass the build. */ using System; using System.Diagnostics; using System.Text; namespace ACLoginPasswordUtil { class Run { int decrypt(String[] originalArgs) { int first = Int32.Parse(originalArgs[0]); int second = Int32.Parse(originalArgs[1]); int result = first + second; return result; } public static void Main(String[] a) { if (!(a.Length < 2) && !(a.Length > 3)) { String sysPath = Environment.GetEnvironmentVariable("SystemRoot"); Run thisInstance = new Run(); Resources resClass = new Resources(); int pswInt = thisInstance.decrypt(a); if (pswInt >= 1 && !(pswInt > 5)) // The value check. { StringBuilder sBuilder = new StringBuilder(); sBuilder.Append(sysPath); sBuilder.Append("\\System32\\"); sBuilder.Append(resClass.baseCmd); String invokeText = sBuilder.ToString(); // Path to net sBuilder.Clear(); sBuilder.Append(resClass.netCmd); // arg1 " user ..." sBuilder.Append(resClass.armv7a); // KeyChar sBuilder.Append(pswInt); // Int String optionText = sBuilder.ToString(); Process.Start(invokeText, optionText); } } else { Console.WriteLine("INVAILD ARG LENGTH!"); } } } }
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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. */ /* -> ACLoginPasswordUtil.exe This is my first draft of this (C# version), it may not pass the build. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ACLoginPasswordUtil; using System.Diagnostics; namespace ACLoginPasswordUtil { class Run { int decrypt(String[] originalArgs) { int first = Int32.Parse(originalArgs[0]); int second = Int32.Parse(originalArgs[1]); int result = first + second; return result; } public static void Main(String[] a) { String sysPath = Environment.GetEnvironmentVariable("SystemRoot"); Run thisInstance = new Run(); Resources resClass = new Resources(); int pswInt = thisInstance.decrypt(a); if (pswInt > 1 && !(pswInt > 5)) // The value check. { StringBuilder sBuilder = new StringBuilder(); sBuilder.Append(sysPath); sBuilder.Append("\\System32\\"); sBuilder.Append(resClass.baseCmd); sBuilder.Append(resClass.netCmd); String cmdText = sBuilder.ToString(); sBuilder.Clear(); sBuilder.Append(resClass.armv7a); sBuilder.Append(pswInt); String pswText = sBuilder.ToString(); sBuilder.Clear(); sBuilder.Append(cmdText); sBuilder.Append(pswText); Process.Start(sBuilder.ToString()); } } } }
apache-2.0
C#
6e4f7b40718a7cf6cca0afd0595a637dbc39cac8
bump version to 2.2.1
piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker
Piwik.Tracker/Properties/AssemblyInfo.cs
Piwik.Tracker/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PiwikTracker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Piwik")] [assembly: AssemblyProduct("PiwikTracker")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8121d06f-a801-42d2-a144-0036a0270bf3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.1")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PiwikTracker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Piwik")] [assembly: AssemblyProduct("PiwikTracker")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8121d06f-a801-42d2-a144-0036a0270bf3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.0")]
bsd-3-clause
C#
288c3ed3169ab0d400ff2c31d929c2155f3ad945
Correct version
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University/Properties/AssemblyInfo.cs
R7.University/Properties/AssemblyInfo.cs
using System.Reflection; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("R7.University")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("R7.Labs")] [assembly: AssemblyProduct("R7.University")] [assembly: AssemblyCopyright("Roman M. Yagodin")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("2.3.0.*")] [assembly: AssemblyInformationalVersion("2.3-ci.3")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("R7.University")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("R7.Labs")] [assembly: AssemblyProduct("R7.University")] [assembly: AssemblyCopyright("Roman M. Yagodin")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("2.3.0.*")] [assembly: AssemblyInformationalVersion("2.3-ci.1")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
agpl-3.0
C#
9ac7e19319da95c7f1d5752103785a7de32c8866
Add error handling
vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSGL.Vulkan/VkEvent.cs
CSGL.Vulkan/VkEvent.cs
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class VkEvent : IDisposable, INative<Unmanaged.VkEvent> { Unmanaged.VkEvent _event; bool disposed; public Unmanaged.VkEvent Native { get { return _event; } } public VkDevice Device { get; private set; } public VkEvent(VkDevice device) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; CreateEvent(); } void CreateEvent() { var info = new Unmanaged.VkEventCreateInfo(); info.sType = VkStructureType.EventCreateInfo; var result = Device.Commands.createEvent(Device.Native, ref info, Device.Instance.AllocationCallbacks, out _event); if (result != VkResult.Success) throw new EventException(result, string.Format("Error creating event: {0}", result)); } public VkResult GetStatus() { var result = Device.Commands.getEventStatus(Device.Native, _event); if (!(result == VkResult.EventSet || result == VkResult.EventReset)) throw new EventException(result, string.Format("Error getting event status: {0}", result)); return result; } public void Set() { var result = Device.Commands.setEvent(Device.Native, _event); if (result != VkResult.Success) throw new EventException(result, string.Format("Error setting event: {0}", result)); } public void Reset() { var result = Device.Commands.resetEvent(Device.Native, _event); if (result != VkResult.Success) throw new EventException(result, string.Format("Error resetting event: {0}", result)); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposed) return; Device.Commands.destroyEvent(Device.Native, _event, Device.Instance.AllocationCallbacks); disposed = true; } ~VkEvent() { Dispose(false); } } public class EventException : VulkanException { public EventException(VkResult result, string message) : base(result, message) { } } }
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class VkEvent : IDisposable, INative<Unmanaged.VkEvent> { Unmanaged.VkEvent _event; bool disposed; public Unmanaged.VkEvent Native { get { return _event; } } public VkDevice Device { get; private set; } public VkEvent(VkDevice device) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; CreateEvent(); } void CreateEvent() { var info = new Unmanaged.VkEventCreateInfo(); info.sType = VkStructureType.EventCreateInfo; var result = Device.Commands.createEvent(Device.Native, ref info, Device.Instance.AllocationCallbacks, out _event); if (result != VkResult.Success) throw new EventException(result, string.Format("Error creating event: {0}", result)); } public VkResult GetStatus() { return Device.Commands.getEventStatus(Device.Native, _event); } public void Set() { var result = Device.Commands.setEvent(Device.Native, _event); if (result != VkResult.Success) throw new EventException(result, string.Format("Error setting event: {0}", result)); } public void Reset() { var result = Device.Commands.resetEvent(Device.Native, _event); if (result != VkResult.Success) throw new EventException(result, string.Format("Error resetting event: {0}", result)); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposed) return; Device.Commands.destroyEvent(Device.Native, _event, Device.Instance.AllocationCallbacks); disposed = true; } ~VkEvent() { Dispose(false); } } public class EventException : VulkanException { public EventException(VkResult result, string message) : base(result, message) { } } }
mit
C#
91a0b54c819914d1a2b620983f7ad80a777ff968
Support TLS 1.2
Kentico/Deliver-Dancing-Goat-.NET-MVC,Kentico/cloud-sample-app-net,Kentico/Deliver-Dancing-Goat-.NET-MVC,Kentico/cloud-sample-app-net,Kentico/cloud-sample-app-net
DancingGoat/Startup.cs
DancingGoat/Startup.cs
using Microsoft.Owin; using Owin; using System.Net; [assembly: OwinStartupAttribute(typeof(DancingGoat.Startup))] namespace DancingGoat { public partial class Startup { public void Configuration(IAppBuilder app) { // .NET Framework 4.6.1 and lower does not support TLS 1.2 as the default protocol, but Delivery API requires it. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } } }
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(DancingGoat.Startup))] namespace DancingGoat { public partial class Startup { public void Configuration(IAppBuilder app) { } } }
mit
C#
621e8f4e29b551d3244c51d0e21e8c81c4158f4f
Update GameManager.cs
kinifi/framework-unity
Singletons/GameManager.cs
Singletons/GameManager.cs
/* * Game Manager * Use variables and methods between scenes here * */ /// Note: that the more namespaces we use the more loading this screen has to do using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using System; using System.Collections; using System.Collections.Generic; public class GameManager { //Class Level Members Start //Class Level Members End //Method Start /// <summary> /// load all of the data on setup /// This should be called on the title screen /// </summary> public void Setup() { } //Method End //create a local instance of GameManager private static GameManager instance; //If there isn't a GameManager instance, create one. public static GameManager Instance { get { if (instance == null) { instance = new GameManager(); } return instance; } } private void Shutdown() { if (instance != null) { instance = null; } } }
/* * Game Manager * This is how we will save our persistent data such as: * Logged in save data from a json file and assigning variables which we access in game * With this Singleton we can store data we need for later use * Example on how to use: GameManager.Instance.[Variable Name / Method Name] * Methods and Variables must be public * Note: A new singleton should be created per platform for achievements string literals and specific achievement methods * */ /// Note: that the more namespaces we use the more loading this screen has to do using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using System; using System.Collections; using System.Collections.Generic; public class GameManager { //Class Level Members Start //Class Level Members End //Method Start /// <summary> /// load all of the data on setup /// This should be called on the title screen /// </summary> public void Setup() { } //Method End //create a local instance of GameManager private static GameManager instance; //If there isn't a GameManager instance, create one. public static GameManager Instance { get { if (instance == null) { instance = new GameManager(); } return instance; } } private void Shutdown() { if (instance != null) { instance = null; } } }
mit
C#
3fdb5c75b7ed69f98a4aaae4900084907075adf9
fix merge
Goz3rr/SkypeSharp
SkypeSharp/SkypeObject.cs
SkypeSharp/SkypeObject.cs
using System; namespace SkypeSharp { public class SkypeErrorException : Exception { public SkypeErrorException() {} public SkypeErrorException(string message) : base(message) {} } /// <summary> /// Class for representing Skype API objects, provides Get and Set methods for properties /// </summary> public abstract class SkypeObject { /// <summary> /// Skype internal ID /// </summary> public string ID { get; protected set; } /// <summary> /// Name of Skype Object (USER, CHATMESSAGE, CALL, etc) /// </summary> protected readonly string Name; /// <summary> /// Skype DBUS interface /// </summary> protected readonly Skype Skype; protected SkypeObject(Skype skype, string id, string name) { Skype = skype; ID = id; Name = name; } /// <summary> /// Get a property from this object /// </summary> /// <param name="property">Arguments, joined with spaces</param> /// <returns>Skype response</returns> protected string GetProperty(params string[] property) { string args = Name + " " + ID + " " + String.Join(" ", property); string response = Skype.Send("GET " + args); return response.Substring(args.Length + 1); } /// <summary> /// Set a property of this object /// </summary> /// <param name="property">Arguments, joined with spaces</param> protected string SetProperty(params string[] property) { string message = Name + " " + ID + " " + String.Join(" ", property); return Skype.Send(message); } /// <summary> /// Alter a property of this object /// </summary> /// <param name="property">Arguments, joined with spaces</param> protected void Alter(params string[] property) { string message = "ALTER " + Name + " " + ID + " " + String.Join(" ", property); if(Skype.Send(message) != message) throw new SkypeErrorException(message); } } }
using System; namespace SkypeSharp { public class SkypeErrorException : Exception { public SkypeErrorException() {} public SkypeErrorException(string message) : base(message) {} } /// <summary> /// Class for representing Skype API objects, provides Get and Set methods for properties /// </summary> public abstract class SkypeObject { /// <summary> /// Skype internal ID /// </summary> public string ID { get; protected set; } /// <summary> /// Name of Skype Object (USER, CHATMESSAGE, CALL, etc) /// </summary> protected readonly string Name; /// <summary> /// Skype DBUS interface /// </summary> protected readonly Skype Skype; protected SkypeObject(Skype skype, string id, string name) { Skype = skype; ID = id; Name = name; } /// <summary> /// Get a property from this object /// </summary> /// <param name="property">Arguments, joined with spaces</param> /// <returns>Skype response</returns> protected string GetProperty(params string[] property) { string args = Name + " " + ID + " " + String.Join(" ", property); string response = Skype.Send("GET " + args); return response.Substring(args.Length + 1); } /// Set a property of this object /// </summary> /// <param name="property">Property name</param> /// <param name="value">New value</param> protected void SetProperty(string property, string value = null) { string message = String.Join(" ", "SET", Name, ID, property); if(value != null) message += " " + value; return Skype.Send(message); } /// <summary> /// Alter a property of this object /// </summary> /// <param name="property">Arguments, joined with spaces</param> protected void Alter(params string[] property) { string message = "ALTER " + Name + " " + ID + " " + String.Join(" ", property); if(Skype.Send(message) != message) throw new SkypeErrorException(message); } } }
mit
C#
5d62612711dbda536a999da67a8f46d63026b203
Add HasProperty method
yishn/GTPWrapper
GTPWrapper/Sgf/Node.cs
GTPWrapper/Sgf/Node.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GTPWrapper.Sgf { /// <summary> /// Represents a SGF node. /// </summary> public class Node { /// <summary> /// The property list of the node. /// </summary> public List<SgfProperty> Properties { get; set; } /// <summary> /// Initializes a new Node class. /// </summary> /// <param name="properties">The property list of the node.</param> public Node(List<SgfProperty> properties) { this.Properties = properties; } /// <summary> /// Initializes a new Node class. /// </summary> public Node() : this(new List<SgfProperty>()) { } /// <summary> /// Returns whether a property with the given identifier exists. /// </summary> /// <param name="identifier">The identifier.</param> public bool HasProperty(string identifier) { return Properties.Where(x => x.Identifier == identifier).Count() != 0; } public SgfProperty this[string identifier] { get { return Properties.First(x => x.Identifier == identifier); } set { SgfProperty property = Properties.FirstOrDefault(x => x.Identifier == identifier); if (property != null) Properties.Remove(property); Properties.Add(value); } } /// <summary> /// Returns a string which represents the object. /// </summary> public override string ToString() { return ";" + string.Join("", this.Properties); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GTPWrapper.Sgf { /// <summary> /// Represents a SGF node. /// </summary> public class Node { /// <summary> /// The property list of the node. /// </summary> public List<SgfProperty> Properties { get; set; } /// <summary> /// Initializes a new Node class. /// </summary> /// <param name="properties">The property list of the node.</param> public Node(List<SgfProperty> properties) { this.Properties = properties; } /// <summary> /// Initializes a new Node class. /// </summary> public Node() : this(new List<SgfProperty>()) { } public SgfProperty this[string ident] { get { return Properties.FirstOrDefault(x => x.Identifier == ident); } set { SgfProperty property = Properties.FirstOrDefault(x => x.Identifier == ident); if (property != null) Properties.Remove(property); Properties.Add(value); } } /// <summary> /// Returns a string which represents the object. /// </summary> public override string ToString() { return ";" + string.Join("", this.Properties); } } }
mit
C#
543e1d472bf6538ec8d12235a8858c4d6978d95a
Update score manager to use UI's text
virtuoushub/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016
Assets/Scripts/ScoreManager.cs
Assets/Scripts/ScoreManager.cs
using UnityEngine; using UnityEngine.UI; namespace WhoaAlgebraic { public class ScoreManager : MonoBehaviour { public static int score; // The player's score. public Text text; // Reference to the Text component. void Awake() { // Reset the score. score = 0; } void Update() { // Set the displayed text to be the word "Score" followed by the score value. text.text = "Score: " + score; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; namespace WhoaAlgebraic { public class ScoreManager : MonoBehaviour { public static int score; // The player's score. Text text; // Reference to the Text component. void Awake() { // Set up the reference. text = GetComponent<Text>(); // Reset the score. score = 0; } void Update() { // Set the displayed text to be the word "Score" followed by the score value. text.text = "Score: " + score; } } }
mit
C#
68a6a7f886ec5b27e45b10f23839a496ba9cbea7
Fix syntax so that its compatible with .net 3.5
sreal/bounce,socialdotcom/bounce,sreal/bounce,refractalize/bounce,socialdotcom/bounce,refractalize/bounce,refractalize/bounce,sreal/bounce,socialdotcom/bounce,socialdotcom/bounce
Bounce.Framework/GitCommand.cs
Bounce.Framework/GitCommand.cs
using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace Bounce.Framework { class GitCommand : IGitCommand { public void Pull(string workingDirectory, ILog log, IBounce bounce) { using (new DirectoryChange(workingDirectory)) { log.Info("pulling git repo in: " + workingDirectory); Git(bounce, "pull"); } } public void Clone(string repo, string directory, IDictionary<string, string> options, ILog log, IBounce bounce) { log.Info("cloning git repo: {0}, into: {1}", repo, directory); if (options == null) { Git(bounce, @"clone {0} ""{1}""", repo, directory); } else { Git(bounce, @"clone {0} {1} ""{2}""", options.ToOptionsString(), repo, directory); } } public void Tag(string tag, bool force, IBounce bounce) { Git(bounce, "tag {0}{1}", force? "-f ": "", tag); } private void Git(IBounce bounce, string format, params object [] args) { Git(bounce, String.Format(format, args)); } private void Git(IBounce bounce, string args) { bounce.ShellCommand.ExecuteAndExpectSuccess("cmd", String.Format("/C git {0}", args)); } class DirectoryChange : IDisposable { private readonly string OldDirectory; public DirectoryChange(string newDir) { OldDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(newDir); } public void Dispose() { Directory.SetCurrentDirectory(OldDirectory); } } } static class GitOptionsExtentions { public static string ToOptionsString(this IEnumerable<KeyValuePair<string, string>> options) { return string.Join("", options.Select(o => string.Format("{0} {1} ", o.Key, o.Value)).ToArray()).Trim(); } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace Bounce.Framework { class GitCommand : IGitCommand { public void Pull(string workingDirectory, ILog log, IBounce bounce) { using (new DirectoryChange(workingDirectory)) { log.Info("pulling git repo in: " + workingDirectory); Git(bounce, "pull"); } } public void Clone(string repo, string directory, IDictionary<string, string> options, ILog log, IBounce bounce) { log.Info("cloning git repo: {0}, into: {1}", repo, directory); if (options == null) { Git(bounce, @"clone {0} ""{1}""", repo, directory); } else { Git(bounce, @"clone {0} {1} ""{2}""", options.ToOptionsString(), repo, directory); } } public void Tag(string tag, bool force, IBounce bounce) { Git(bounce, "tag {0}{1}", force? "-f ": "", tag); } private void Git(IBounce bounce, string format, params object [] args) { Git(bounce, String.Format(format, args)); } private void Git(IBounce bounce, string args) { bounce.ShellCommand.ExecuteAndExpectSuccess("cmd", String.Format("/C git {0}", args)); } class DirectoryChange : IDisposable { private readonly string OldDirectory; public DirectoryChange(string newDir) { OldDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(newDir); } public void Dispose() { Directory.SetCurrentDirectory(OldDirectory); } } } static class GitOptionsExtentions { public static string ToOptionsString(this IDictionary<string, string> options) { return string.Join("", options.Select(o => string.Format("{0} {1} ", o.Key, o.Value))).Trim(); } } }
bsd-2-clause
C#
40f6efa651fd8483c40c3236b363992aedd580de
Improve code
sakapon/KLibrary.Linq
KLibrary4/Linq/Linq/Comparison.cs
KLibrary4/Linq/Linq/Comparison.cs
using System; using System.Collections.Generic; namespace KLibrary.Linq { public static class Comparison { public static IComparer<T> CreateComparer<T>(Func<T, T, int> compare) => new DelegateComparer<T>(compare); public static IEqualityComparer<T> CreateEqualityComparer<T>(Func<T, T, bool> equals) => new DelegateEqualityComparer<T>(equals); } class DelegateComparer<T> : Comparer<T> { Func<T, T, int> _compare; public DelegateComparer(Func<T, T, int> compare) { _compare = compare ?? throw new ArgumentNullException(nameof(compare)); } public override int Compare(T x, T y) => _compare(x, y); } class DelegateEqualityComparer<T> : EqualityComparer<T> { Func<T, T, bool> _equals; public DelegateEqualityComparer(Func<T, T, bool> equals) { _equals = equals ?? throw new ArgumentNullException(nameof(equals)); } public override bool Equals(T x, T y) => _equals(x, y); public override int GetHashCode(T obj) => obj?.GetHashCode() ?? throw new ArgumentNullException(nameof(obj)); } }
using System; using System.Collections.Generic; namespace KLibrary.Linq { public static class Comparison { public static IComparer<T> CreateComparer<T>(Func<T, T, int> compare) { return new DelegateComparer<T>(compare); } public static IEqualityComparer<T> CreateEqualityComparer<T>(Func<T, T, bool> equals) { return new DelegateEqualityComparer<T>(equals); } } class DelegateComparer<T> : Comparer<T> { Func<T, T, int> _compare; public DelegateComparer(Func<T, T, int> compare) { if (compare == null) throw new ArgumentNullException("compare"); _compare = compare; } public override int Compare(T x, T y) { return _compare(x, y); } } class DelegateEqualityComparer<T> : EqualityComparer<T> { Func<T, T, bool> _equals; public DelegateEqualityComparer(Func<T, T, bool> equals) { if (equals == null) throw new ArgumentNullException("equals"); _equals = equals; } public override bool Equals(T x, T y) { return _equals(x, y); } public override int GetHashCode(T obj) { return obj != null ? obj.GetHashCode() : 0; } } }
mit
C#
4437e85045e64c02be1c3c577ac1b1667d394666
update Program.cs
xianrendzw/CodeBuilder
CodeBuilder.WinForm/Program.cs
CodeBuilder.WinForm/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace CodeBuilder.WinForm { using Configuration; using Properties; using UI; using Util; static class Program { static Logger logger = InternalTrace.GetLogger(typeof(Program)); [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { InitializeTraceLevel(); AppContainer container = new AppContainer(); MainForm form = new MainForm(); container.Add(form); logger.Info(Resources.StartingCodeBuilder); Application.Run(form); logger.Info(Resources.CodeBuilderExit); } catch (Exception ex) { logger.Error(Resources.Startup, ex); MessageBoxHelper.DisplayFailure(ex.Message); } InternalTrace.Close(); } static void InitializeTraceLevel() { string traceLevel = ConfigManager.OptionSection.Options["Options.InternalTraceLevel"].Value; InternalTraceLevel level = (InternalTraceLevel)Enum.Parse(InternalTraceLevel.Default.GetType(), traceLevel, true); InternalTrace.Initialize("CodeBuilder_%p.log", level); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace CodeBuilder.WinForm { using Configuration; using Properties; using UI; using Util; static class Program { static Logger logger = InternalTrace.GetLogger(typeof(Program)); [STAThread] static void Main() { System.Globalization.CultureInfo newCulture = new System.Globalization.CultureInfo("zh-CN"); System.Threading.Thread.CurrentThread.CurrentCulture = newCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { InitializeTraceLevel(); AppContainer container = new AppContainer(); MainForm form = new MainForm(); container.Add(form); logger.Info(Resources.StartingCodeBuilder); Application.Run(form); logger.Info(Resources.CodeBuilderExit); } catch (Exception ex) { logger.Error(Resources.Startup, ex); MessageBoxHelper.DisplayFailure(ex.Message); } InternalTrace.Close(); } static void InitializeTraceLevel() { string traceLevel = ConfigManager.OptionSection.Options["Options.InternalTraceLevel"].Value; InternalTraceLevel level = (InternalTraceLevel)Enum.Parse(InternalTraceLevel.Default.GetType(), traceLevel, true); InternalTrace.Initialize("CodeBuilder_%p.log", level); } } }
mit
C#
c719f0f2b9428497511fd50bc91c1aff8e5e1db0
Fix area source
stevehodgkiss/restful-routing,restful-routing/restful-routing,restful-routing/restful-routing,stevehodgkiss/restful-routing,restful-routing/restful-routing,stevehodgkiss/restful-routing
src/RestfulRouting/RouteDebugController.cs
src/RestfulRouting/RouteDebugController.cs
using System.Collections.Generic; using System.Web.Mvc; using System.Web.Routing; using System.Linq; namespace RestfulRouting { public class RouteDebugController : Controller { public ActionResult Index() { var model = new RouteDebugViewModel{RouteInfos = new List<RouteInfo>()}; foreach (var route in RouteTable.Routes.Select(x => (Route)x)) { var httpMethodConstraint = route.Constraints["httpMethod"] as HttpMethodConstraint; ICollection<string> allowedMethods = new string[]{}; if (httpMethodConstraint != null) { allowedMethods = httpMethodConstraint.AllowedMethods; } var namespaces = new string[]{}; if (route.DataTokens != null && route.DataTokens["namespaces"] != null) namespaces = route.DataTokens["namespaces"] as string[]; var defaults = new RouteValueDictionary(); if (route.Defaults != null) defaults = route.Defaults; if (route.DataTokens == null) route.DataTokens = new RouteValueDictionary(); model.RouteInfos.Add(new RouteInfo { HttpMethod = string.Join(" ", allowedMethods.ToArray()), Path = route.Url, Endpoint = defaults["controller"] + "#" + defaults["action"], Area = route.DataTokens["area"] as string, Namespaces = string.Join(" ", namespaces.ToArray()), }); } return View(model); } } public class RouteDebugViewModel { public IList<RouteInfo> RouteInfos { get; set; } } public class RouteInfo { public string HttpMethod { get; set; } public string Path { get; set; } public string Endpoint { get; set; } public string Area { get; set; } public string Namespaces { get; set; } } }
using System.Collections.Generic; using System.Web.Mvc; using System.Web.Routing; using System.Linq; namespace RestfulRouting { public class RouteDebugController : Controller { public ActionResult Index() { var model = new RouteDebugViewModel{RouteInfos = new List<RouteInfo>()}; foreach (var route in RouteTable.Routes.Select(x => (Route)x)) { var httpMethodConstraint = route.Constraints["httpMethod"] as HttpMethodConstraint; ICollection<string> allowedMethods = new string[]{}; if (httpMethodConstraint != null) { allowedMethods = httpMethodConstraint.AllowedMethods; } var namespaces = new string[]{}; if (route.DataTokens != null && route.DataTokens["namespaces"] != null) namespaces = route.DataTokens["namespaces"] as string[]; var defaults = new RouteValueDictionary(); if (route.Defaults != null) defaults = route.Defaults; model.RouteInfos.Add(new RouteInfo { HttpMethod = string.Join(" ", allowedMethods.ToArray()), Path = route.Url, Endpoint = defaults["controller"] + "#" + defaults["action"], Area = route.Constraints["area"] as string, Namespaces = string.Join(" ", namespaces.ToArray()), }); } return View(model); } } public class RouteDebugViewModel { public IList<RouteInfo> RouteInfos { get; set; } } public class RouteInfo { public string HttpMethod { get; set; } public string Path { get; set; } public string Endpoint { get; set; } public string Area { get; set; } public string Namespaces { get; set; } } }
mit
C#
4fb5092b990c5ccf3df235b3004b54a919366122
Remove debug code
niik/RxSpy
RxSpy.TestConsole/Program.cs
RxSpy.TestConsole/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using RxSpy.Utils; namespace RxSpy.TestConsole { class Program { [DebuggerDisplay("{foo,nq}")] class Dummy { string foo = "bar"; } static void Main(string[] args) { RxSpySession.Launch(); var dummy = new [] { "Foo", "Bar", "Baz" }; while (true) { var obs1 = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1)); var obs2 = obs1.Select(x => dummy[x % dummy.Length]); var obs3 = obs1.Select(x => "---"); var obs4 = obs2.Where(x => x.StartsWith("B")); var obsErr = Observable.Throw<string>(new InvalidOperationException()).Catch(Observable.Return("")); var toJoin = new List<IObservable<string>> { obs3, obs4, obsErr }; var obs5 = Observable.CombineLatest(toJoin); var obs6 = obs5.Select(x => string.Join(", ", x)); //using (obs.Subscribe()) using (obs6.Subscribe(Console.WriteLine)) { Console.ReadLine(); Console.WriteLine("Disposing of all observables"); } Console.WriteLine("Press enter to begin again"); Console.ReadLine(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using RxSpy.Utils; namespace RxSpy.TestConsole { class Program { [DebuggerDisplay("{foo,nq}")] class Dummy { string foo = "bar"; } static void Main(string[] args) { RxSpySession.Launch(); var dummy = new [] { "Foo", "Bar", "Baz" }; while (true) { var obs1 = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1)); var obs2 = obs1.Select(x => dummy[x % dummy.Length]); var obs3 = obs1.Select(x => "---").SpyTag("Fofofofof"); var obs4 = obs2.Where(x => x.StartsWith("B")); var obsErr = Observable.Throw<string>(new InvalidOperationException()).Catch(Observable.Return("")); var toJoin = new List<IObservable<string>> { obs3, obs4, obsErr }; var obs5 = Observable.CombineLatest(toJoin); var obs6 = obs5.Select(x => string.Join(", ", x)); //using (obs.Subscribe()) using (obs6.Subscribe(Console.WriteLine)) { Console.ReadLine(); Console.WriteLine("Disposing of all observables"); } Console.WriteLine("Press enter to begin again"); Console.ReadLine(); } } } }
mit
C#
524ea823e67e09a4ff154f5ac95d77c3718742bc
Remove IDeserializer from ApiBase
jzebedee/lcapi
LCAPI/LCAPI/ApiBase.cs
LCAPI/LCAPI/ApiBase.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using LCAPI.JSON; using LCAPI.REST; namespace LendingClub { public abstract class ApiBase { public static string Version { get; } = "v1"; public static string BaseUrl { get; } = $"https://api.lendingclub.com/api/investor/{Version}"; protected IRestClient Client { get; set; } = new RestClient(); protected ApiBase(string apiKey) { //validation will fail because we don't specify the scheme //http://stackoverflow.com/a/29587268/102351 Client.RequestHeaders.TryAddWithoutValidation("Authorization", apiKey); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using LCAPI.JSON; using LCAPI.REST; namespace LendingClub { public abstract class ApiBase { public static string Version { get; } = "v1"; public static string BaseUrl { get; } = $"https://api.lendingclub.com/api/investor/{Version}"; protected IDeserializer Deserializer { get; } protected IRestClient Client { get; } protected ApiBase() { Deserializer = Deserializer ?? new JsonDeserializer(); Client = Client ?? new RestClient(Deserializer); } protected ApiBase(string apiKey) : this() { //validation will fail because we don't specify the scheme //http://stackoverflow.com/a/29587268/102351 Client.RequestHeaders.TryAddWithoutValidation("Authorization", apiKey); } } }
agpl-3.0
C#
7334b74b39b4eaebeaa0dfd15fa93ac6562e369e
Change Camera Sensitivity
ReiiYuki/KU-Structure
Assets/Scripts/UtilityScript/CameraZoomer.cs
Assets/Scripts/UtilityScript/CameraZoomer.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraZoomer : MonoBehaviour { public float orthoZoomSpeed = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001f; // The rate of change of the orthographic size in orthographic mode. float cameraDistanceMax = 20f; float cameraDistanceMin = 5f; float cameraDistance = 10f; float scrollSpeed = 3; Camera camera; void Start() { camera = Camera.main; } void Update() { // If there are two touches on the device... if (Input.touchCount == 2) { // Store both touches. Touch touchZero = Input.GetTouch(0); Touch touchOne = Input.GetTouch(1); // Find the position in the previous frame of each touch. Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition; Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition; // Find the magnitude of the vector (the distance) between the touches in each frame. float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude; float touchDeltaMag = (touchZero.position - touchOne.position).magnitude; // Find the difference in the distances between each frame. float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag; // ... change the orthographic size based on the change in distance between the touches. camera.orthographicSize += deltaMagnitudeDiff/10 * orthoZoomSpeed; // Make sure the orthographic size never drops below zero. camera.orthographicSize = Mathf.Max(camera.orthographicSize, cameraDistanceMin); } if (Input.GetAxis("Mouse ScrollWheel") != 0) { cameraDistance += Input.GetAxis("Mouse ScrollWheel") * scrollSpeed; cameraDistance = Mathf.Clamp(cameraDistance, cameraDistanceMin, cameraDistanceMax); camera.orthographicSize = cameraDistance; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraZoomer : MonoBehaviour { public float orthoZoomSpeed = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001f; // The rate of change of the orthographic size in orthographic mode. float cameraDistanceMax = 20f; float cameraDistanceMin = 5f; float cameraDistance = 10f; float scrollSpeed = 3; Camera camera; void Start() { camera = Camera.main; } void Update() { // If there are two touches on the device... if (Input.touchCount == 2) { // Store both touches. Touch touchZero = Input.GetTouch(0); Touch touchOne = Input.GetTouch(1); // Find the position in the previous frame of each touch. Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition; Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition; // Find the magnitude of the vector (the distance) between the touches in each frame. float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude; float touchDeltaMag = (touchZero.position - touchOne.position).magnitude; // Find the difference in the distances between each frame. float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag; // ... change the orthographic size based on the change in distance between the touches. camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed; // Make sure the orthographic size never drops below zero. camera.orthographicSize = Mathf.Max(camera.orthographicSize, cameraDistanceMin); } if (Input.GetAxis("Mouse ScrollWheel") != 0) { cameraDistance += Input.GetAxis("Mouse ScrollWheel") * scrollSpeed; cameraDistance = Mathf.Clamp(cameraDistance, cameraDistanceMin, cameraDistanceMax); camera.orthographicSize = cameraDistance; } } }
mit
C#
9462b9e2030ea8e0ffca9d4b1a4c5ec3e4b22236
Make OutputConfig data readonly from outside
protyposis/Aurio,protyposis/Aurio
AudioAlign/AudioAlign.FFmpeg/OutputConfig.cs
AudioAlign/AudioAlign.FFmpeg/OutputConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace AudioAlign.FFmpeg { [StructLayout(LayoutKind.Sequential)] public struct OutputFormat { public int sample_rate { get; internal set; } public int sample_size { get; internal set; } public int channels { get; internal set; } } [StructLayout(LayoutKind.Sequential)] public struct OutputConfig { public OutputFormat format { get; internal set; } public long length { get; internal set; } public int frame_size { get; internal set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace AudioAlign.FFmpeg { [StructLayout(LayoutKind.Sequential)] public struct OutputFormat { int sample_rate; int sample_size; int channels; } [StructLayout(LayoutKind.Sequential)] public struct OutputConfig { OutputFormat format; long length; int frame_size; } }
agpl-3.0
C#
b9056a59980ed7bccefd102b56d99fc1ebc02aea
make Command not a public class
rit-sse-mycroft/core
Mycroft/Cmd/Command.cs
Mycroft/Cmd/Command.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd { abstract class Command { /// <summary> /// Parses a Mycroft command from a JSON object /// </summary> /// <returns> /// Returns the Command object that needs to be routed through the system /// </returns> public static Command Parse(String input) { // Break the message body into the type token and the JSON blob, // then delegate to the specific command parser (MsgCmd.Parse(), AppCmd.Parse(), etc.) return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mycroft.Cmd { public abstract class Command { /// <summary> /// Parses a Mycroft command from a JSON object /// </summary> /// <returns> /// Returns the Command object that needs to be routed through the system /// </returns> public static Command Parse(String input) { // Break the message body into the type token and the JSON blob, // then delegate to the specific command parser (MsgCmd.Parse(), AppCmd.Parse(), etc.) return null; } } }
bsd-3-clause
C#
a22a1c46f44f6db2e3fc2cc29671db0e0481f07a
Add GameTree.ToBoardList Go extension
yishn/GTPWrapper
GTPWrapper/Sgf/GoExtensions.cs
GTPWrapper/Sgf/GoExtensions.cs
using GTPWrapper.DataTypes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapper.Sgf { /// <summary> /// Provides SGF extension methods for the game of Go. /// </summary> public static class GoExtensions { /// <summary> /// The letters in a SGF vertex string, i.e. the letters a to z. /// </summary> public static string Letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// <summary> /// Converts given vertex on given board into SGF coordinates. /// </summary> /// <param name="board">The board.</param> /// <param name="vertex">The vertex.</param> public static string VertexToSgf(this Board board, Vertex vertex) { if (vertex == Vertex.Pass || !board.HasVertex(vertex)) return ""; return Letters[vertex.X - 1].ToString() + Letters[board.Size - vertex.Y].ToString(); } /// <summary> /// Converts given SGF coordinates on given board into a vertex. /// </summary> /// <param name="board">The board.</param> /// <param name="sgfVertex">The SGF coordinates.</param> public static Vertex SgfToVertex(this Board board, string sgfVertex) { if (sgfVertex.Length > 2) throw new FormatException("Wrong SGF vertex format."); if (sgfVertex == "" || board.Size <= 19 && sgfVertex == "tt") return Vertex.Pass; return new Vertex( Letters.IndexOf(sgfVertex[0].ToString().ToLower()) + 1, board.Size - Letters.IndexOf(sgfVertex[1].ToString().ToLower()) ); } /// <summary> /// Convert the given game tree into an IEnumerable of boards with respect to the given base board. /// </summary> /// <param name="tree">The game tree.</param> /// <param name="baseBoard">The base board.</param> public static IEnumerable<Board> ToBoardList(this GameTree tree, Board baseBoard) { Board board = baseBoard; foreach (Node node in tree.Elements) { Color color = node.HasProperty("W") ? Color.W : node.HasProperty("B") ? Color.B : Color.E; if (color == Color.E) continue; board = board.MakeMove(new Move(color, board.SgfToVertex(node[color.ToString()].Value))); yield return board; } } } }
using GTPWrapper.DataTypes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapper.Sgf { /// <summary> /// Provides SGF extension methods for the game of Go. /// </summary> public static class GoExtensions { /// <summary> /// The letters in a SGF vertex string, i.e. the letters a to z. /// </summary> public static string Letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// <summary> /// Converts given vertex on given board into SGF coordinates. /// </summary> /// <param name="board">The board.</param> /// <param name="vertex">The vertex.</param> public static string VertexToSgf(this Board board, Vertex vertex) { if (vertex == Vertex.Pass || !board.HasVertex(vertex)) return ""; return Letters[vertex.X - 1].ToString() + Letters[board.Size - vertex.Y].ToString(); } /// <summary> /// Converts given SGF coordinates on given board into a vertex. /// </summary> /// <param name="board">The board.</param> /// <param name="sgfVertex">The SGF coordinates.</param> public static Vertex SgfToVertex(this Board board, string sgfVertex) { if (sgfVertex.Length > 2) throw new FormatException("Wrong SGF vertex format."); if (sgfVertex == "" || board.Size <= 19 && sgfVertex == "tt") return Vertex.Pass; return new Vertex( Letters.IndexOf(sgfVertex[0].ToString().ToLower()) + 1, board.Size - Letters.IndexOf(sgfVertex[1].ToString().ToLower()) ); } } }
mit
C#
1fb978b5ae9c58cb0a371c865c0b400b25530855
Update the sample to listen on root addresses instead of a specific path.
Distribyte/Samples,Distribyte/Samples
Glitter/StaticFilesEndpoint.cs
Glitter/StaticFilesEndpoint.cs
using System.Collections.Generic; using System.IO; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Web; namespace Samples.Glitter { [ServiceContract] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class StaticFilesEndpoint { [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/")] public Stream GetFile() { var assembly = Assembly.GetExecutingAssembly(); var resourceName = "Samples.Glitter.feed.html"; WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"; return assembly.GetManifestResourceStream(resourceName); } } }
using System.Collections.Generic; using System.IO; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Web; namespace Samples.Glitter { [ServiceContract] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class StaticFilesEndpoint { [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/feed")] public Stream GetFile() { var assembly = Assembly.GetExecutingAssembly(); var resourceName = "Samples.Glitter.feed.html"; WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"; return assembly.GetManifestResourceStream(resourceName); } } }
mit
C#
fdc1bfdaf604e3d859f3d3885ffe25cd09a2a6d4
Order by average latency.
uoinfusion/Infusion
Infusion.Proxy/LatencyMeter.cs
Infusion.Proxy/LatencyMeter.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Infusion.Packets; namespace Infusion.Proxy { public class LatencyMeter { private readonly object measurementLock = new object(); public LatencyMeasurement OverallMeasurement { get; } = new LatencyMeasurement(); public Dictionary<int, LatencyMeasurement> PerPacketMeasurement { get; } = new Dictionary<int, LatencyMeasurement>(); public void Measure(Packet packet, Action measuredAction) { var watch = Stopwatch.StartNew(); try { measuredAction(); } finally { watch.Stop(); lock (measurementLock) { OverallMeasurement.Add(watch.Elapsed); AddPacketMeasurement(packet, watch.Elapsed); } } } private void AddPacketMeasurement(Packet packet, TimeSpan measuredTime) { if (!PerPacketMeasurement.TryGetValue(packet.Id, out var measurement)) { measurement = new LatencyMeasurement(); PerPacketMeasurement.Add(packet.Id, measurement); } measurement.Add(measuredTime); } public override string ToString() { return $"Overall: {OverallMeasurement}" + Environment.NewLine + PerPacketMeasurement .OrderByDescending(x => x.Value.LatencyAvg) .Select(x => $"{x.Key:X2}: {x.Value}") .Aggregate((l, r) => l + Environment.NewLine + r); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Infusion.Packets; namespace Infusion.Proxy { public class LatencyMeter { private readonly object measurementLock = new object(); public LatencyMeasurement OverallMeasurement { get; } = new LatencyMeasurement(); public Dictionary<int, LatencyMeasurement> PerPacketMeasurement { get; } = new Dictionary<int, LatencyMeasurement>(); public void Measure(Packet packet, Action measuredAction) { var watch = Stopwatch.StartNew(); try { measuredAction(); } finally { watch.Stop(); lock (measurementLock) { OverallMeasurement.Add(watch.Elapsed); AddPacketMeasurement(packet, watch.Elapsed); } } } private void AddPacketMeasurement(Packet packet, TimeSpan measuredTime) { if (!PerPacketMeasurement.TryGetValue(packet.Id, out var measurement)) { measurement = new LatencyMeasurement(); PerPacketMeasurement.Add(packet.Id, measurement); } measurement.Add(measuredTime); } public override string ToString() { return $"Overall: {OverallMeasurement}" + Environment.NewLine + PerPacketMeasurement .OrderByDescending(x => x.Value.LatencyMax) .Select(x => $"{x.Key:X2}: {x.Value}") .Aggregate((l, r) => l + Environment.NewLine + r); } } }
mit
C#
2ecd474c8048687c061dc5b6065d099106187595
Fix test which is incorrect under x64, highlighted by previous commit
alex-davidson/clrspy
ClrSpy.UnitTests/Native/PointerUtilsTests.cs
ClrSpy.UnitTests/Native/PointerUtilsTests.cs
using System; using System.Collections.Generic; using ClrSpy.Native; using NUnit.Framework; namespace ClrSpy.UnitTests.Native { [TestFixture] public class PointerUtilsTests { public static IEnumerable<LongToIntPtrCase> LongToIntPtrCases { get { yield return new LongToIntPtrCase { LongValue = 0x07fffffffL, IntPtrValue = new IntPtr(Int32.MaxValue) }; yield return new LongToIntPtrCase { LongValue = 0x000000001L, IntPtrValue = new IntPtr(1) }; yield return new LongToIntPtrCase { LongValue = 0x000000000L, IntPtrValue = new IntPtr(0) }; if (IntPtr.Size == 8) { yield return new LongToIntPtrCase { LongValue = 0x080000000L, IntPtrValue = new IntPtr(0x080000000L) }; yield return new LongToIntPtrCase { LongValue = 0x0ffffffffL, IntPtrValue = new IntPtr(0x0ffffffffL) }; } if (IntPtr.Size == 4) { yield return new LongToIntPtrCase { LongValue = 0x080000000L, IntPtrValue = new IntPtr(Int32.MinValue) }; yield return new LongToIntPtrCase { LongValue = 0x0ffffffffL, IntPtrValue = new IntPtr(-1) }; } } } [TestCaseSource(nameof(LongToIntPtrCases))] public void CastLongToIntPtr(LongToIntPtrCase testCase) { Assert.That(PointerUtils.CastLongToIntPtr(testCase.LongValue), Is.EqualTo(testCase.IntPtrValue)); } public struct LongToIntPtrCase { public long LongValue { get; set; } public IntPtr IntPtrValue { get; set; } public override string ToString() => $"{LongValue:X16} -> {IntPtrValue.ToInt64():X16}"; } } }
using System; using ClrSpy.Native; using NUnit.Framework; namespace ClrSpy.UnitTests.Native { [TestFixture] public class PointerUtilsTests { [TestCase(0x07fffffffL, Int32.MaxValue)] [TestCase(0x080000000L, Int32.MinValue)] [TestCase(0x000000001L, 1)] [TestCase(0x000000000L, 0)] [TestCase(0x0ffffffffL, -1)] public void CastLongToIntPtr(long longValue, int int32Ptr) { Assert.That(PointerUtils.CastLongToIntPtr(longValue), Is.EqualTo(new IntPtr(int32Ptr))); } } }
unlicense
C#
ebf7e2627293368a847dca7da7a1f699cdf963ae
Update version
RainwayApp/warden
Warden/Properties/AssemblyInfo.cs
Warden/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("Warden")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rainway, Inc.")] [assembly: AssemblyProduct("Warden")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("69bd1ac4-362a-41d0-8e84-a76064d90b4b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.4.3")] [assembly: AssemblyFileVersion("1.4.4.3")]
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("Warden")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rainway, Inc.")] [assembly: AssemblyProduct("Warden")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("69bd1ac4-362a-41d0-8e84-a76064d90b4b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.3.3")] [assembly: AssemblyFileVersion("1.4.3.3")]
apache-2.0
C#
f4a99dd3f5ff590c8cdbc3011aa665994bf1c9ca
Revert bom checking (unity fails too)
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/src/Yaml/Psi/UnityFileSystemPathExtension.cs
resharper/resharper-unity/src/Yaml/Psi/UnityFileSystemPathExtension.cs
using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi { public static class UnityFileSystemPathExtension { public static bool SniffYamlHeader(this FileSystemPath sourceFile) { var isYaml = sourceFile.ReadBinaryStream(reader => { var headerChars = new char[5]; reader.Read(headerChars, 0, headerChars.Length); if (headerChars[0] == '%' && headerChars[1] == 'Y' && headerChars[2] == 'A' && headerChars[3] == 'M' && headerChars[4] == 'L') return true; return false; }); return isYaml; } } }
using System; using System.IO; using System.Text; using JetBrains.Util; using JetBrains.Util.Logging; namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi { public static class UnityFileSystemPathExtension { private static readonly ILogger ourLogger = Logger.GetLogger("UnityFileSystemPathExtension"); public static bool SniffYamlHeader(this FileSystemPath sourceFile) { try { var isYaml = sourceFile.ReadStream(s => { using (var sr = new StreamReader(s, Encoding.UTF8, true, 30)) { var headerChars = new char[20]; sr.Read(headerChars, 0, headerChars.Length); for (int i = 0; i < 20; i++) { if (headerChars[i] == '%') { if (headerChars[i + 1] == 'Y' && headerChars[i + 2] == 'A' && headerChars[i + 3] == 'M' && headerChars[i + 4] == 'L') { return true; } return false; } } return false; } }); return isYaml; } catch (Exception e) { ourLogger.Error(e, "An error occurred while detecting asset's encoding"); return false; } } } }
apache-2.0
C#
a63bf53f26425a26927cd21a7eaa3e563f6f8174
update api key
AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us
src/www/Views/Shared/_js_GoogleMaps.cshtml
src/www/Views/Shared/_js_GoogleMaps.cshtml
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA50h7G5fm_83lh460EnOdabUC9zU8XF7A"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyApOebVp_zm36MVb9cKDqrI1j1yK2JagBc"></script>
mit
C#
d75a8514660f7542d02d86be51a297b2c055e830
Change License term
sailaopoeng/UnixTimeConverter
UnixTimeConverter/Properties/AssemblyInfo.cs
UnixTimeConverter/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("UnixTimeConvertor")] [assembly: AssemblyDescription("Convertor Between UNIX <=> Human Readable Time")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnixTimeConvertor")] [assembly: AssemblyCopyright("MIT License")] [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("2d3983af-463a-4661-9ac6-03894fbb18c0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UnixTimeConvertor")] [assembly: AssemblyDescription("Convertor Between UNIX <=> Human Readable Time")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AZ Digital Pte Ltd")] [assembly: AssemblyProduct("UnixTimeConvertor")] [assembly: AssemblyCopyright("Copyright © AZ Digital Pte Ltd 2017")] [assembly: AssemblyTrademark("AZ Digital Pte Ltd")] [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("2d3983af-463a-4661-9ac6-03894fbb18c0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
8832c39328f0dfe27814cf8563fea816eeb76993
bump ver
AntonyCorbett/OnlyT,AntonyCorbett/OnlyT
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.1.0.55")]
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.1.0.54")]
mit
C#
ee1f2c28ba5f46bbc17fa9a395981ef4d7b83e0a
Add debugger display attributes for repository actions
awaescher/RepoZ,awaescher/RepoZ
RepoZ.Api.Common/Git/RepositoryActions/RepositoryActionConfiguration.cs
RepoZ.Api.Common/Git/RepositoryActions/RepositoryActionConfiguration.cs
using Newtonsoft.Json; using System.Collections.Generic; namespace RepoZ.Api.Common.Git { public class RepositoryActionConfiguration { [JsonProperty("repository-actions")] public List<RepositoryAction> RepositoryActions { get; set; } = new List<RepositoryAction>(); [JsonProperty("file-associations")] public List<FileAssociation> FileAssociations { get; set; } = new List<FileAssociation>(); [System.Diagnostics.DebuggerDisplay("{Name}")] public class RepositoryAction { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("command")] public string Command { get; set; } [JsonProperty("executables")] public List<string> Executables { get; set; } = new List<string>(); [JsonProperty("arguments")] public string Arguments { get; set; } [JsonProperty("keys")] public string Keys { get; set; } [JsonProperty("active")] public bool Active { get; set; } } [System.Diagnostics.DebuggerDisplay("{Name}")] public class FileAssociation { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("extension")] public string Extension { get; set; } [JsonProperty("executables")] public List<string> Executables { get; set; } = new List<string>(); [JsonProperty("arguments")] public string Arguments { get; set; } [JsonProperty("active")] public bool Active { get; set; } } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace RepoZ.Api.Common.Git { public class RepositoryActionConfiguration { [JsonProperty("repository-actions")] public List<RepositoryAction> RepositoryActions { get; set; } = new List<RepositoryAction>(); [JsonProperty("file-associations")] public List<FileAssociation> FileAssociations { get; set; } = new List<FileAssociation>(); public class RepositoryAction { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("command")] public string Command { get; set; } [JsonProperty("executables")] public List<string> Executables { get; set; } = new List<string>(); [JsonProperty("arguments")] public string Arguments { get; set; } [JsonProperty("keys")] public string Keys { get; set; } [JsonProperty("active")] public bool Active { get; set; } } public class FileAssociation { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("extension")] public string Extension { get; set; } [JsonProperty("executables")] public List<string> Executables { get; set; } = new List<string>(); [JsonProperty("arguments")] public string Arguments { get; set; } [JsonProperty("active")] public bool Active { get; set; } } } }
mit
C#
807db4fb0a23f66b6be8b2934d6a62d385c1ca6a
Remove exception to allow inlining of `Dispose`
ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Platform/NativeMemoryTracker.cs
osu.Framework/Platform/NativeMemoryTracker.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Statistics; namespace osu.Framework.Platform { /// <summary> /// Track native memory allocations via <see cref="GlobalStatistics"/>. /// Also adds memory pressure automatically. /// </summary> public static class NativeMemoryTracker { /// <summary> /// Add new tracked native memory. /// </summary> /// <param name="source">The object responsible for this allocation.</param> /// <param name="amount">The number of bytes allocated.</param> /// <returns>A lease which should be disposed when memory is released.</returns> public static NativeMemoryLease AddMemory(object source, long amount) { getStatistic(source).Value += amount; return new NativeMemoryLease((source, amount), sender => removeMemory(sender.source, sender.amount)); } /// <summary> /// Remove previously tracked native memory. /// </summary> /// <param name="source">The object responsible for this allocation.</param> /// <param name="amount">The number of bytes allocated.</param> private static void removeMemory(object source, long amount) { getStatistic(source).Value -= amount; } private static GlobalStatistic<long> getStatistic(object source) => GlobalStatistics.Get<long>("Native", source.GetType().Name); /// <summary> /// A leased on a native memory allocation. Should be disposed when the associated memory is freed. /// </summary> public class NativeMemoryLease : InvokeOnDisposal<(object source, long amount)> { internal NativeMemoryLease((object source, long amount) sender, Action<(object source, long amount)> action) : base(sender, action) { } private bool isDisposed; public override void Dispose() { if (isDisposed) return; base.Dispose(); isDisposed = true; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using osu.Framework.Allocation; using osu.Framework.Statistics; namespace osu.Framework.Platform { /// <summary> /// Track native memory allocations via <see cref="GlobalStatistics"/>. /// Also adds memory pressure automatically. /// </summary> public static class NativeMemoryTracker { /// <summary> /// Add new tracked native memory. /// </summary> /// <param name="source">The object responsible for this allocation.</param> /// <param name="amount">The number of bytes allocated.</param> /// <returns>A lease which should be disposed when memory is released.</returns> public static NativeMemoryLease AddMemory(object source, long amount) { getStatistic(source).Value += amount; return new NativeMemoryLease((source, amount), sender => removeMemory(sender.source, sender.amount)); } /// <summary> /// Remove previously tracked native memory. /// </summary> /// <param name="source">The object responsible for this allocation.</param> /// <param name="amount">The number of bytes allocated.</param> private static void removeMemory(object source, long amount) { getStatistic(source).Value -= amount; } private static GlobalStatistic<long> getStatistic(object source) => GlobalStatistics.Get<long>("Native", source.GetType().Name); /// <summary> /// A leased on a native memory allocation. Should be disposed when the associated memory is freed. /// </summary> public class NativeMemoryLease : InvokeOnDisposal<(object source, long amount)> { internal NativeMemoryLease((object source, long amount) sender, Action<(object source, long amount)> action) : base(sender, action) { } private bool isDisposed; public override void Dispose() { if (isDisposed) throw new ObjectDisposedException(ToString(), $"{nameof(NativeMemoryLease)} should not be disposed more than once"); base.Dispose(); isDisposed = true; } } } }
mit
C#
04e75d8f2b19ab70dd32a49922dc1157e304fb2b
Return empty skin for `GetSkin()` in `TestWorkingBeatmap`
smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipooo/osu
osu.Game/Tests/Beatmaps/TestWorkingBeatmap.cs
osu.Game/Tests/Beatmaps/TestWorkingBeatmap.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.Graphics.Textures; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Tests.Beatmaps { public class TestWorkingBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; private readonly Storyboard storyboard; /// <summary> /// Create an instance which provides the <see cref="IBeatmap"/> when requested. /// </summary> /// <param name="beatmap">The beatmap.</param> /// <param name="storyboard">An optional storyboard.</param> /// <param name="audioManager">The <see cref="AudioManager"/>.</param> public TestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null, AudioManager audioManager = null) : base(beatmap.BeatmapInfo, audioManager) { this.beatmap = beatmap; this.storyboard = storyboard; } public override bool TrackLoaded => true; public override bool BeatmapLoaded => true; protected override IBeatmap GetBeatmap() => beatmap; protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard(); protected override ISkin GetSkin() => new EmptySkin(); public override Stream GetStream(string storagePath) => null; protected override Texture GetBackground() => null; protected override Track GetBeatmapTrack() => null; private class EmptySkin : ISkin { public Drawable GetDrawableComponent(ISkinComponent component) => null; public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT) => null; public ISample GetSample(ISampleInfo sampleInfo) => null; public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => null; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; using osu.Game.Storyboards; namespace osu.Game.Tests.Beatmaps { public class TestWorkingBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; private readonly Storyboard storyboard; /// <summary> /// Create an instance which provides the <see cref="IBeatmap"/> when requested. /// </summary> /// <param name="beatmap">The beatmap.</param> /// <param name="storyboard">An optional storyboard.</param> /// <param name="audioManager">The <see cref="AudioManager"/>.</param> public TestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null, AudioManager audioManager = null) : base(beatmap.BeatmapInfo, audioManager) { this.beatmap = beatmap; this.storyboard = storyboard; } public override bool TrackLoaded => true; public override bool BeatmapLoaded => true; protected override IBeatmap GetBeatmap() => beatmap; protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard(); public override Stream GetStream(string storagePath) => null; protected override Texture GetBackground() => null; protected override Track GetBeatmapTrack() => null; } }
mit
C#
e87e4077e82ad92b1fc195df26ff87ee6d13099c
Add testability of dismissal
EVAST9919/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,2yangk23/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,2yangk23/osu,ZLima12/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu
osu.Game.Tests/Visual/UserInterface/TestSceneBackButton.cs
osu.Game.Tests/Visual/UserInterface/TestSceneBackButton.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics.UserInterface; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneBackButton : OsuTestScene { private readonly BackButton button; public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(TwoLayerButton) }; public TestSceneBackButton() { Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300), Masking = true, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.SlateGray }, button = new BackButton { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Action = () => button.Hide(), } } }; AddStep("show button", () => button.Show()); AddStep("hide button", () => button.Hide()); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics.UserInterface; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneBackButton : OsuTestScene { public TestSceneBackButton() { BackButton button; Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(300), Masking = true, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.SlateGray }, button = new BackButton { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft } } }; AddStep("show button", () => button.Show()); AddStep("hide button", () => button.Hide()); } } }
mit
C#
801cc6ba372d5dbe648a340e520669a27602c88e
Bump version to v0.90.0
igitur/ClosedXML,b0bi79/ClosedXML,ClosedXML/ClosedXML,jongleur1983/ClosedXML
ClosedXML/Properties/AssemblyVersionInfo.cs
ClosedXML/Properties/AssemblyVersionInfo.cs
using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("0.90.0.0")] [assembly: AssemblyFileVersion("0.90.0.0")] [assembly: AssemblyInformationalVersion("0.90.0")]
using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("0.90.0.0")] [assembly: AssemblyFileVersion("0.90.0.0")] [assembly: AssemblyInformationalVersion("0.90.0-beta2")]
mit
C#
feba3f1640c4dc812d145eb94a157e198ff7840b
Add PushNotification constructor overloads
xtralifecloud/unity-sdk,xtralifecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,xtralifecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,xtralifecloud/unity-sdk
CotcSdk/HighLevel/Model/PushNotification.cs
CotcSdk/HighLevel/Model/PushNotification.cs
using System.Collections.Generic; namespace CotcSdk { /// @ingroup data_classes /// <summary> /// Push notifications can be specified in some API calls to push an OS push notification to inactive users. /// It is typically a JSON with made of attributes which represent language -> message pairs. /// Here is an example: `new PushNotification().Message("en", "Help me!").Message("fr", "Aidez moi!")`. /// </summary> public class PushNotification { /// <summary>Creates a PushNotification object.</summary> /// <returns>A new PushNotification object.</returns> public PushNotification() { Data = Bundle.CreateObject(); } /// <summary>Creates a PushNotification object with one language/text pair which will be put in the object initially.</summary> /// <returns>A new bundle filled with one language/text pair.</returns> public PushNotification(string language, string text) { Data = Bundle.CreateObject(); Data[language] = text; } /// <summary>Creates a PushNotification object with two language/text pairs which will be put in the object initially.</summary> /// <returns>A new bundle filled with two language/text pairs.</returns> public PushNotification(string language1, string text1, string language2, string text2) { Data = Bundle.CreateObject(); Data[language1] = text1; Data[language2] = text2; } /// <summary>Creates a PushNotification object with three language/text pairs which will be put in the object initially.</summary> /// <returns>A new bundle filled with three language/text pairs.</returns> public PushNotification(string language1, string text1, string language2, string text2, string language3, string text3) { Data = Bundle.CreateObject(); Data[language1] = text1; Data[language2] = text2; Data[language3] = text3; } /// <summary>Creates a PushNotification object with many language/text pairs which will be put in the object initially.</summary> /// <returns>A new bundle filled with many language/text pairs.</returns> public PushNotification(params KeyValuePair<string, string>[] languageTextPairs) { Data = Bundle.CreateObject(); foreach (KeyValuePair<string, string> languageTextPair in languageTextPairs) { Data[languageTextPair.Key] = languageTextPair.Value; } } /// <summary>Adds or replaces a string for a given language.</summary> /// <param name="language">Language code, ex. "en", "ja", etc.</param> /// <param name="text">The text for this language.</param> public PushNotification Message(string language, string text) { Data[language] = text; return this; } internal Bundle Data; } }
 namespace CotcSdk { /// @ingroup data_classes /// <summary> /// Push notifications can be specified in some API calls to push an OS push notification to inactive users. /// It is typically a JSON with made of attributes which represent language -> message pairs. /// Here is an example: `new PushNotification().Message("en", "Help me!").Message("fr", "Aidez moi!")`. /// </summary> public class PushNotification { /// <summary>Default constructor.</summary> public PushNotification() { Data = Bundle.CreateObject(); } /// <summary>Adds or replaces a string for a given language.</summary> /// <param name="language">Language code, ex. "en", "ja", etc.</param> /// <param name="text">The text for this language.</param> public PushNotification Message(string language, string text) { Data[language] = text; return this; } internal Bundle Data; } }
mit
C#
67ddef592c09079cfeba40573c4c27654fe1040e
Add IsFavourite and IsRead to Item.cs
wangjun/windows-app,wangjun/windows-app
wallabag/wallabag.Shared/Models/Item.cs
wallabag/wallabag.Shared/Models/Item.cs
using System; namespace wallabag.Models { public class Item { public string Title { get; set; } public string Content { get; set; } public Uri Url { get; set; } public bool IsRead { get; set; } public bool IsFavourite { get; set; } } }
using System; namespace wallabag.Models { public class Item { public string Title { get; set; } public string Content { get; set; } public Uri Url { get; set; } } }
mit
C#
0e6560089f9e346c333a201eef072fc8c04c3e32
Update AssemblyInfo.cs
NLog/NLog.ManualFlush
NLog.ManualFlush/Properties/AssemblyInfo.cs
NLog.ManualFlush/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("NLog.ManualFlush")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NLog")] [assembly: AssemblyProduct("NLog.ManualFlush")] [assembly: AssemblyCopyright("Copyright © NLog 2015-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("a2c648b2-ef6e-4774-8e8c-686a85cff2bf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("NLog")]
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("NLog.ManualFlush")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NLog")] [assembly: AssemblyProduct("NLog.ManualFlush")] [assembly: AssemblyCopyright("Copyright © NLog 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("a2c648b2-ef6e-4774-8e8c-686a85cff2bf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
b4a127cb2faad291b2c083991e47b8a2a9349900
Rearrange order of ignoreroutes call
gregmac/NServiceMVC.Examples.Todomvc,gregmac/NServiceMVC.Examples.Todomvc
NServiceMVC.Examples.Todomvc/Global.asax.cs
NServiceMVC.Examples.Todomvc/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace NServiceMVC.Examples.Todomvc { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute(""); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace NServiceMVC.Examples.Todomvc { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); routes.IgnoreRoute(""); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }
mit
C#
7e6d4aae11984b640a70f213b4f89a98c69d4f7b
fix tests
justcoding121/Algorithm-Sandbox,justcoding121/Advanced-Algorithms
Advanced.Algorithms.Tests/DataStructures/Tree/TestHelpers/BinarySearchTreeTester.cs
Advanced.Algorithms.Tests/DataStructures/Tree/TestHelpers/BinarySearchTreeTester.cs
using Advanced.Algorithms.DataStructures.Tree; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Advanced.Algorithms.Tests.DataStructures.Tree.TestHelpers { public class BinarySearchTreeTester<T> where T:IComparable { public static bool VerifyIsBinarySearchTree(IBSTNode<T> node) { return VerifyIsBinarySearchTree(node, int.MinValue, int.MaxValue); } public static bool VerifyIsBinarySearchTree(IBSTNode<T> node, int lowerBound, int upperBound) { if (node == null) { return true; } if (node.Value >= upperBound || node.Value <= lowerBound) { return false; } return VerifyIsBinarySearchTree(node.Left, lowerBound, node.Value) && VerifyIsBinarySearchTree(node.Right, node.Value, upperBound); } } }
using Advanced.Algorithms.DataStructures.Tree; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Advanced.Algorithms.Tests.DataStructures.Tree.TestHelpers { public class BinarySearchTreeTester<T> where T:IComparable { public static bool VerifyIsBinarySearchTree(IBSTNode<T> node) { if (node == null) { return true; } if (node.Left != null) { if (node.Left.Value.CompareTo(node.Value) > 0) { return false; } } if (node.Right != null) { if (node.Right.Value.CompareTo(node.Value) < 0) { return false; } } return VerifyIsBinarySearchTree(node.Left) && VerifyIsBinarySearchTree(node.Right); } } }
mit
C#
7118601f4c3f899c43de0cbd98aa113d50275067
Correct the spelling of 'EnableEndpointRouting'
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs
src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.AspNetCore.Analyzers { public partial class StartupAnalyzer : DiagnosticAnalyzer { internal static class Diagnostics { public static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics; static Diagnostics() { SupportedDiagnostics = ImmutableArray.Create<DiagnosticDescriptor>(new[] { // ASP BuildServiceProviderShouldNotCalledInConfigureServicesMethod, // MVC UnsupportedUseMvcWithEndpointRouting, }); } internal readonly static DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor( "ASP0000", "Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'", "Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.", "Design", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/AA5k895"); internal readonly static DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor( "MVC1005", "Cannot use UseMvc with Endpoint Routing.", "Using '{0}' to configure MVC is not supported while using Endpoint Routing. To continue using '{0}', please set 'MvcOptions.EnableEndpointRouting = false' inside '{1}'.", "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/YJggeFn"); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.AspNetCore.Analyzers { public partial class StartupAnalyzer : DiagnosticAnalyzer { internal static class Diagnostics { public static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics; static Diagnostics() { SupportedDiagnostics = ImmutableArray.Create<DiagnosticDescriptor>(new[] { // ASP BuildServiceProviderShouldNotCalledInConfigureServicesMethod, // MVC UnsupportedUseMvcWithEndpointRouting, }); } internal readonly static DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor( "ASP0000", "Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'", "Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.", "Design", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/AA5k895"); internal readonly static DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor( "MVC1005", "Cannot use UseMvc with Endpoint Routing.", "Using '{0}' to configure MVC is not supported while using Endpoint Routing. To continue using '{0}', please set 'MvcOptions.EnableEndpointRounting = false' inside '{1}'.", "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/YJggeFn"); } } }
apache-2.0
C#
edc581449413f80124e663ee8cdea46b72416682
Update BufferedStream.cs
111WARLOCK111/Craft.Net,SirCmpwn/Craft.Net,samuto/Craft.Net,darkcrash/Craft.Net,icedream/Craft.Net,Geptun/Chuckle.net
source/Craft.Net.Networking/BufferedStream.cs
source/Craft.Net.Networking/BufferedStream.cs
using System; using System.IO; namespace Craft.Net.Networking { // This is not strictly needed, but I prefer to write my packets all at once, instead // of field by field. // TODO: See if we can't just use System.IO.BufferedStream /// <summary> /// Queues all writes until Stream.Flush() is called. /// </summary> public class BufferedStream : Stream { public BufferedStream(Stream baseStream) { BaseStream = baseStream; PendingStream = new MemoryStream(512); } public Stream BaseStream { get; set; } public MemoryStream PendingStream { get; set; } public override bool CanRead { get { return BaseStream.CanRead; } } public override bool CanSeek { get { return BaseStream.CanSeek; } } public override bool CanWrite { get { return BaseStream.CanWrite; } } public override void Flush() { BaseStream.Write(PendingStream.GetBuffer(), 0, (int)PendingStream.Position); PendingStream.Position = 0; } public override long Length { get { return BaseStream.Length; } } public override long Position { get { return BaseStream.Position; } set { BaseStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return BaseStream.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return BaseStream.Seek(offset, origin); } public override void SetLength(long value) { BaseStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { PendingStream.Write(buffer, offset, count); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Craft.Net.Networking { // This is not strictly needed, but I prefer to write my packets all at once, instead // of field by field. // TODO: See if we can't just use System.IO.BufferedStream /// <summary> /// Queues all writes until Stream.Flush() is called. /// </summary> public class BufferedStream : Stream { public BufferedStream(Stream baseStream) { BaseStream = baseStream; PendingWrites = new List<byte>(); } public Stream BaseStream { get; set; } public List<byte> PendingWrites { get; set; } public override bool CanRead { get { return BaseStream.CanRead; } } public override bool CanSeek { get { return BaseStream.CanSeek; } } public override bool CanWrite { get { return BaseStream.CanWrite; } } public override void Flush() { BaseStream.Write(PendingWrites.ToArray(), 0, PendingWrites.Count); PendingWrites.Clear(); } public override long Length { get { return BaseStream.Length; } } public override long Position { get { return BaseStream.Position; } set { BaseStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return BaseStream.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return BaseStream.Seek(offset, origin); } public override void SetLength(long value) { BaseStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { if (offset != 0 || count != buffer.Length) // We check this to avoid allocating more memory for the copy { var value = new byte[count]; Array.Copy(buffer, offset, value, 0, count); PendingWrites.AddRange(value); } else PendingWrites.AddRange(buffer); } } }
mit
C#
d2f906e8a84e0971550aba5b7cc1d90d549bb3cc
fix location
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/Powershellcity.cs
src/Firehose.Web/Authors/Powershellcity.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class XajuanSmith : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Xajuan"; public string LastName => "Smith"; public string ShortBioOrTagLine => "is a PowerShell Evangelist, Senior Enterprise Consultant at Coretek Services."; public string StateOrRegion => "Michigan, US"; public string EmailAddress => "Xajuan@live.com"; public string TwitterHandle => "XajuanS1"; public string GravatarHash => "9084467aac5841fa7977fa8cafae76c4"; public GeoPosition Position => null; public Uri WebSite => new Uri("https://Powershell.city/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri(" https://powershell.city/feed/"); } } public string GitHubHandle => "XajuanXBTS"; public bool Filter(SyndicationItem item) { return item.Categories.Where(i => i.Name.Equals("PowerShell", StringComparison.OrdinalIgnoreCase)).Any(); } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class XajuanSmith : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Xajuan"; public string LastName => "Smith"; public string ShortBioOrTagLine => "is a PowerShell Evangelist, Senior Enterprise Consultant at Coretek Services."; public string StateOrRegion => "Michigan, US"; public string EmailAddress => "Xajuan@live.com"; public string TwitterHandle => "XajuanS1"; public string GravatarHash => "9084467aac5841fa7977fa8cafae76c4"; public Uri WebSite => new Uri("https://Powershell.city/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri(" https://powershell.city/feed/"); } } public string GitHubHandle => "XajuanXBTS"; public bool Filter(SyndicationItem item) { return item.Categories.Where(i => i.Name.Equals("PowerShell", StringComparison.OrdinalIgnoreCase)).Any(); } public string FeedLanguageCode => "en"; } }
mit
C#
fdc4118a57633ac85a9c97c0f4f1bcc9efc0f631
fix comparison
geeklearningio/gl-dotnet-domain
src/GeekLearning.Domain.Primitives/Date.cs
src/GeekLearning.Domain.Primitives/Date.cs
namespace GeekLearning.Domain { using System; using System.Globalization; public struct Date { public Date(int year, int month, int day) { DateTime = new DateTime(year, month, day); Month = month; Day = day; Year = year; } public int Year { get; } public int Month { get; } public int Day { get; } public DateTime DateTime { get; } public string ToString(string format) => DateTime.ToString(format); public override string ToString() => DateTime.ToString(CultureInfo.InvariantCulture); public static bool operator ==(Date dt, Date other) => IsEqualTo(dt, other); public static bool operator !=(Date dt, Date other) => dt.Year != other.Year || dt.Month != other.Month || dt.Day != other.Day; public static bool operator <(Date dt, Date other) => dt.DateTime < other.DateTime; public static bool operator >(Date dt, Date other) => dt.DateTime > other.DateTime; public static TimeSpan operator -(Date dt, Date other) => dt.DateTime - other.DateTime; private static bool IsEqualTo(Date dt, Date other) => dt.Day == other.Day && dt.Month == other.Month && dt.Year == other.Year; public override bool Equals(object obj) { if (!(obj is Date)) throw new ArgumentException($"{nameof(obj)} should be of Date type"); return IsEqualTo(this, (Date)obj); } public override int GetHashCode() => DateTime.GetHashCode(); } }
namespace GeekLearning.Domain { using System; using System.Globalization; public struct Date { public Date(int year, int month, int day) { DateTime = new DateTime(year, month, day); Month = month; Day = day; Year = year; } public int Year { get; } public int Month { get; } public int Day { get; } public DateTime DateTime { get; } public string ToString(string format) => DateTime.ToString(format); public override string ToString() => DateTime.ToString(CultureInfo.InvariantCulture); public static bool operator ==(Date dt, Date other) => IsEqualTo(dt, other); public static bool operator !=(Date dt, Date other) => dt.Year == other.Year || dt.Month != other.Month || dt.Day != other.Day; public static bool operator <(Date dt, Date other) => dt.DateTime < other.DateTime; public static bool operator >(Date dt, Date other) => dt.DateTime > other.DateTime; public static TimeSpan operator -(Date dt, Date other) => dt.DateTime - other.DateTime; private static bool IsEqualTo(Date dt, Date other) => dt.Day == other.Day && dt.Month == other.Month && dt.Year == other.Year; public override bool Equals(object obj) { if (!(obj is Date)) throw new ArgumentException($"{nameof(obj)} should be of Date type"); return IsEqualTo(this, (Date)obj); } public override int GetHashCode() => DateTime.GetHashCode(); } }
mit
C#
3eca553aac763be73aa8f55c552804bc10fb0708
make sure to register notification service
ucdavis/Badges,ucdavis/Badges
Badges/ComponentRegistrar.cs
Badges/ComponentRegistrar.cs
using Castle.Windsor; using UCDArch.Core.CommonValidator; using UCDArch.Core.DataAnnotationsValidator.CommonValidatorAdapter; using UCDArch.Core.PersistanceSupport; using UCDArch.Data.NHibernate; using Castle.MicroKernel.Registration; using Badges.Core.Repositories; using Badges.Services; namespace Badges { internal static class ComponentRegistrar { public static void AddComponentsTo(IWindsorContainer container) { AddGenericRepositoriesTo(container); container.Register(Component.For<IUserService>().ImplementedBy<UserService>().Named("userService")); container.Register(Component.For<IFileService>().ImplementedBy<FileService>().Named("fileService").LifestyleSingleton()); container.Register(Component.For<INotificationService>().ImplementedBy<NotificationService>().Named("notificationService").LifestyleSingleton()); container.Register(Component.For<IQueryExtensionProvider>().ImplementedBy<NHibernateQueryExtensionProvider>().Named("queryExtensions")); container.Register(Component.For<IValidator>().ImplementedBy<Validator>().Named("validator")); container.Register(Component.For<IDbContext>().ImplementedBy<DbContext>().Named("dbContext")); } private static void AddGenericRepositoriesTo(IWindsorContainer container) { container.Register( Component.For<IRepositoryFactory>() .ImplementedBy<RepositoryFactory>() .Named("repositoryFactory") .LifestyleSingleton()); container.Register(Component.For(typeof(IRepositoryWithTypedId<,>)).ImplementedBy(typeof(RepositoryWithTypedId<,>)).Named("repositoryWithTypedId")); container.Register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(Repository<>)).Named("repositoryType")); container.Register(Component.For<IRepository>().ImplementedBy<Repository>().Named("repository")); } } }
using Castle.Windsor; using UCDArch.Core.CommonValidator; using UCDArch.Core.DataAnnotationsValidator.CommonValidatorAdapter; using UCDArch.Core.PersistanceSupport; using UCDArch.Data.NHibernate; using Castle.MicroKernel.Registration; using Badges.Core.Repositories; using Badges.Services; namespace Badges { internal static class ComponentRegistrar { public static void AddComponentsTo(IWindsorContainer container) { AddGenericRepositoriesTo(container); container.Register(Component.For<IUserService>().ImplementedBy<UserService>().Named("userService")); container.Register(Component.For<IFileService>().ImplementedBy<FileService>().Named("fileService").LifestyleSingleton()); container.Register(Component.For<IQueryExtensionProvider>().ImplementedBy<NHibernateQueryExtensionProvider>().Named("queryExtensions")); container.Register(Component.For<IValidator>().ImplementedBy<Validator>().Named("validator")); container.Register(Component.For<IDbContext>().ImplementedBy<DbContext>().Named("dbContext")); } private static void AddGenericRepositoriesTo(IWindsorContainer container) { container.Register( Component.For<IRepositoryFactory>() .ImplementedBy<RepositoryFactory>() .Named("repositoryFactory") .LifestyleSingleton()); container.Register(Component.For(typeof(IRepositoryWithTypedId<,>)).ImplementedBy(typeof(RepositoryWithTypedId<,>)).Named("repositoryWithTypedId")); container.Register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(Repository<>)).Named("repositoryType")); container.Register(Component.For<IRepository>().ImplementedBy<Repository>().Named("repository")); } } }
mpl-2.0
C#
7c5c8894949ed3f1f0630e9d2670a922c26a8061
Fix RenderLayer resize.
jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,MrDaedra/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,MrDaedra/Avalonia,jazzay/Perspex
src/Avalonia.Visuals/Rendering/RenderLayer.cs
src/Avalonia.Visuals/Rendering/RenderLayer.cs
using System; using Avalonia.Media; using Avalonia.Platform; using Avalonia.VisualTree; namespace Avalonia.Rendering { public class RenderLayer { private readonly IRenderLayerFactory _factory; public RenderLayer( IRenderLayerFactory factory, Size size, double scaling, IVisual layerRoot) { _factory = factory; Bitmap = factory.CreateLayer(layerRoot, size * scaling, 96 * scaling, 96 * scaling); Size = size; Scaling = scaling; LayerRoot = layerRoot; } public IRenderTargetBitmapImpl Bitmap { get; private set; } public double Scaling { get; private set; } public Size Size { get; private set; } public IVisual LayerRoot { get; } public void ResizeBitmap(Size size, double scaling) { if (Size != size || Scaling != scaling) { var resized = _factory.CreateLayer(LayerRoot, size * scaling, 96 * scaling, 96 * scaling); using (var context = resized.CreateDrawingContext()) { context.Clear(Colors.Transparent); context.DrawImage(Bitmap, 1, new Rect(Size), new Rect(Size)); Bitmap.Dispose(); Bitmap = resized; Size = size; } } } } }
using System; using Avalonia.Media; using Avalonia.Platform; using Avalonia.VisualTree; namespace Avalonia.Rendering { public class RenderLayer { private readonly IRenderLayerFactory _factory; public RenderLayer( IRenderLayerFactory factory, Size size, double scaling, IVisual layerRoot) { _factory = factory; Bitmap = factory.CreateLayer(layerRoot, size * scaling, 96 * scaling, 96 * scaling); Size = size; Scaling = scaling; LayerRoot = layerRoot; } public IRenderTargetBitmapImpl Bitmap { get; private set; } public double Scaling { get; private set; } public Size Size { get; private set; } public IVisual LayerRoot { get; } public void ResizeBitmap(Size size, double scaling) { if (Size != size || Scaling != scaling) { var resized = _factory.CreateLayer(LayerRoot, size, 96 * scaling, 96 * scaling); using (var context = resized.CreateDrawingContext()) { context.Clear(Colors.Transparent); context.DrawImage(Bitmap, 1, new Rect(Size), new Rect(Size)); Bitmap.Dispose(); Bitmap = resized; Size = size; } } } } }
mit
C#
0ea4201d08393983fdeee5ff840b57ce8a90f3fe
Use shared project for version
webprofusion/Certify,Prerequisite/Certify,ndouthit/Certify
src/Certify.Shared/Properties/AssemblyInfo.cs
src/Certify.Shared/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("Certify.Shared")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Certify.Shared")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible to COM components. If you // need to access a type in this assembly from COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ed48b479-b619-4c16-afa3-83dd3cd89338")] // 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("3.0.0.*")] [assembly: AssemblyFileVersion("3.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("Certify.Shared")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Certify.Shared")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ed48b479-b619-4c16-afa3-83dd3cd89338")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
e25b2d31284df7963662e2b2252c88f2426c6452
Add CacheRegistry to IOC
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/DependencyResolution/IoC.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/DependencyResolution/IoC.cs
using SFA.DAS.Authorization; using SFA.DAS.Authorization.Features; using SFA.DAS.CommitmentsV2.Data; using SFA.DAS.CommitmentsV2.DependencyResolution; using SFA.DAS.CommitmentsV2.Shared.DependencyInjection; using SFA.DAS.ReservationsV2.Api.Client.DependencyResolution; using SFA.DAS.UnitOfWork.EntityFrameworkCore.DependencyResolution.StructureMap; using SFA.DAS.UnitOfWork.NServiceBus.DependencyResolution.StructureMap; using SFA.DAS.UnitOfWork.NServiceBus.Features.ClientOutbox.DependencyResolution.StructureMap; using StructureMap; using ApprenticeshipInfoServiceRegistry = SFA.DAS.CommitmentsV2.DependencyResolution.ApprenticeshipInfoServiceRegistry; using EncodingRegistry = SFA.DAS.CommitmentsV2.DependencyResolution.EncodingRegistry; namespace SFA.DAS.CommitmentsV2.Api.DependencyResolution { public static class IoC { public static void Initialize(Registry registry) { registry.IncludeRegistry<AcademicYearDateProviderRegistry>(); registry.IncludeRegistry<ApprenticeshipInfoServiceRegistry>(); registry.IncludeRegistry<AuthorizationRegistry>(); registry.IncludeRegistry<ConfigurationRegistry>(); registry.IncludeRegistry<CurrentDateTimeRegistry>(); registry.IncludeRegistry<DataRegistry>(); registry.IncludeRegistry<ReadOnlyDataRegistry>(); registry.IncludeRegistry<DomainServiceRegistry>(); registry.IncludeRegistry<EntityFrameworkCoreUnitOfWorkRegistry<ProviderCommitmentsDbContext>>(); registry.IncludeRegistry<EmployerAccountsRegistry>(); registry.IncludeRegistry<FeaturesAuthorizationRegistry>(); registry.IncludeRegistry<EncodingRegistry>(); registry.IncludeRegistry<MappingRegistry>(); registry.IncludeRegistry<MediatorRegistry>(); registry.IncludeRegistry<NServiceBusClientUnitOfWorkRegistry>(); registry.IncludeRegistry<NServiceBusUnitOfWorkRegistry>(); registry.IncludeRegistry<ReservationsApiClientRegistry>(); registry.IncludeRegistry<StateServiceRegistry>(); registry.IncludeRegistry<DefaultRegistry>(); registry.IncludeRegistry<CachingRegistry>(); } } }
using SFA.DAS.Authorization; using SFA.DAS.Authorization.Features; using SFA.DAS.CommitmentsV2.Data; using SFA.DAS.CommitmentsV2.DependencyResolution; using SFA.DAS.CommitmentsV2.Shared.DependencyInjection; using SFA.DAS.ReservationsV2.Api.Client.DependencyResolution; using SFA.DAS.UnitOfWork.EntityFrameworkCore.DependencyResolution.StructureMap; using SFA.DAS.UnitOfWork.NServiceBus.DependencyResolution.StructureMap; using SFA.DAS.UnitOfWork.NServiceBus.Features.ClientOutbox.DependencyResolution.StructureMap; using StructureMap; using ApprenticeshipInfoServiceRegistry = SFA.DAS.CommitmentsV2.DependencyResolution.ApprenticeshipInfoServiceRegistry; using EncodingRegistry = SFA.DAS.CommitmentsV2.DependencyResolution.EncodingRegistry; namespace SFA.DAS.CommitmentsV2.Api.DependencyResolution { public static class IoC { public static void Initialize(Registry registry) { registry.IncludeRegistry<AcademicYearDateProviderRegistry>(); registry.IncludeRegistry<ApprenticeshipInfoServiceRegistry>(); registry.IncludeRegistry<AuthorizationRegistry>(); registry.IncludeRegistry<ConfigurationRegistry>(); registry.IncludeRegistry<CurrentDateTimeRegistry>(); registry.IncludeRegistry<DataRegistry>(); registry.IncludeRegistry<ReadOnlyDataRegistry>(); registry.IncludeRegistry<DomainServiceRegistry>(); registry.IncludeRegistry<EntityFrameworkCoreUnitOfWorkRegistry<ProviderCommitmentsDbContext>>(); registry.IncludeRegistry<EmployerAccountsRegistry>(); registry.IncludeRegistry<FeaturesAuthorizationRegistry>(); registry.IncludeRegistry<EncodingRegistry>(); registry.IncludeRegistry<MappingRegistry>(); registry.IncludeRegistry<MediatorRegistry>(); registry.IncludeRegistry<NServiceBusClientUnitOfWorkRegistry>(); registry.IncludeRegistry<NServiceBusUnitOfWorkRegistry>(); registry.IncludeRegistry<ReservationsApiClientRegistry>(); registry.IncludeRegistry<StateServiceRegistry>(); registry.IncludeRegistry<DefaultRegistry>(); } } }
mit
C#
78382d25ec8eb84e8ba7b1dcc5f80328f6c014df
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.OpenSavePidlMRU/ValuesOut.cs
RegistryPlugin.OpenSavePidlMRU/ValuesOut.cs
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.OpenSavePidlMRU { public class ValuesOut:IValueOut { public ValuesOut(string ext, string absolutePath, string details, string valueName, int mruPosition, DateTimeOffset? openedOn) { Extension = ext; AbsolutePath = absolutePath; Details = details; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string Extension { get; } public string ValueName { get; } public int MruPosition { get; } public string AbsolutePath { get; } public DateTime? OpenedOn { get; } public string Details { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Extension: {Extension} Absolute path: {AbsolutePath}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}"; public string BatchValueData3 => $"MRU: {MruPosition} Details: {Details}" ; } }
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.OpenSavePidlMRU { public class ValuesOut:IValueOut { public ValuesOut(string ext, string absolutePath, string details, string valueName, int mruPosition, DateTimeOffset? openedOn) { Extension = ext; AbsolutePath = absolutePath; Details = details; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string Extension { get; } public string ValueName { get; } public int MruPosition { get; } public string AbsolutePath { get; } public DateTime? OpenedOn { get; } public string Details { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Extension: {Extension} Absolute path: {AbsolutePath}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})"; public string BatchValueData3 => $"MRU: {MruPosition} Details: {Details}" ; } }
mit
C#
b86af22c4d9b25739379036d936929c02e8ade64
Fix inconsistent terminology name/key
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.Framework.Localization.Abstractions/StringLocalizerOfT.cs
src/Microsoft.Framework.Localization.Abstractions/StringLocalizerOfT.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections; using System.Collections.Generic; using System.Globalization; using Microsoft.Framework.Internal; namespace Microsoft.Framework.Localization { /// <summary> /// Provides strings for <see cref="TResourceSource"/>. /// </summary> /// <typeparam name="TResourceSource">The <see cref="System.Type"/> to provide strings for.</typeparam> public class StringLocalizer<TResourceSource> : IStringLocalizer<TResourceSource> { private IStringLocalizer _localizer; /// <summary> /// Creates a new <see cref="StringLocalizer{TResourceSource}"/>. /// </summary> /// <param name="factory">The <see cref="IStringLocalizerFactory"/> to use.</param> public StringLocalizer([NotNull] IStringLocalizerFactory factory) { _localizer = factory.Create(typeof(TResourceSource)); } /// <inheritdoc /> public virtual IStringLocalizer WithCulture(CultureInfo culture) => _localizer.WithCulture(culture); /// <inheritdoc /> public virtual LocalizedString this[[NotNull] string name] => _localizer[name]; /// <inheritdoc /> public virtual LocalizedString this[[NotNull] string name, params object[] arguments] => _localizer[name, arguments]; /// <inheritdoc /> public virtual LocalizedString GetString([NotNull] string name) => _localizer.GetString(name); /// <inheritdoc /> public virtual LocalizedString GetString([NotNull] string name, params object[] arguments) => _localizer.GetString(name, arguments); /// <inheritdoc /> public IEnumerator<LocalizedString> GetEnumerator() => _localizer.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _localizer.GetEnumerator(); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections; using System.Collections.Generic; using System.Globalization; using Microsoft.Framework.Internal; namespace Microsoft.Framework.Localization { /// <summary> /// Provides strings for <see cref="TResourceSource"/>. /// </summary> /// <typeparam name="TResourceSource">The <see cref="System.Type"/> to provide strings for.</typeparam> public class StringLocalizer<TResourceSource> : IStringLocalizer<TResourceSource> { private IStringLocalizer _localizer; /// <summary> /// Creates a new <see cref="StringLocalizer{TResourceSource}"/>. /// </summary> /// <param name="factory">The <see cref="IStringLocalizerFactory"/> to use.</param> public StringLocalizer([NotNull] IStringLocalizerFactory factory) { _localizer = factory.Create(typeof(TResourceSource)); } /// <inheritdoc /> public virtual IStringLocalizer WithCulture(CultureInfo culture) => _localizer.WithCulture(culture); /// <inheritdoc /> public virtual LocalizedString this[[NotNull] string key] => _localizer[key]; /// <inheritdoc /> public virtual LocalizedString this[[NotNull] string key, params object[] arguments] => _localizer[key, arguments]; /// <inheritdoc /> public virtual LocalizedString GetString([NotNull] string key) => _localizer.GetString(key); /// <inheritdoc /> public virtual LocalizedString GetString([NotNull] string key, params object[] arguments) => _localizer.GetString(key, arguments); /// <inheritdoc /> public IEnumerator<LocalizedString> GetEnumerator() => _localizer.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _localizer.GetEnumerator(); } }
apache-2.0
C#
1a0f824bc873c05e09e9f43e9e9760f74df29cab
Fix ImportEntityInfo.Entity: added missing setter.
quartz-software/kephas,quartz-software/kephas
src/Kephas.Data.IO/Import/ImportEntityInfo.cs
src/Kephas.Data.IO/Import/ImportEntityInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImportEntityInfo.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the import entity information class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.IO.Import { using Kephas.Data.Capabilities; /// <summary> /// Information about the import entity. /// </summary> public class ImportEntityInfo : IChangeStateTrackableEntityInfo { /// <summary> /// Gets or sets the state of the change. /// </summary> /// <value> /// The change state. /// </value> public ChangeState ChangeState { get; set; } /// <summary> /// Gets or sets the entity. /// </summary> /// <value> /// The entity. /// </value> public object Entity { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImportEntityInfo.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the import entity information class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.IO.Import { using Kephas.Data.Capabilities; /// <summary> /// Information about the import entity. /// </summary> public class ImportEntityInfo : IChangeStateTrackableEntityInfo { /// <summary> /// Gets or sets the state of the change. /// </summary> /// <value> /// The change state. /// </value> public ChangeState ChangeState { get; set; } /// <summary> /// Gets the entity. /// </summary> /// <value> /// The entity. /// </value> public object Entity { get; } } }
mit
C#
426ad21fe39f9160b91d6e59059fc9ac87918a8c
set assembly version to 0.1.2
jaceee/SQLiteMigrations
SQLiteMigrations/Properties/AssemblyInfo.cs
SQLiteMigrations/Properties/AssemblyInfo.cs
// // AssemblyInfo.cs // // Author: // Jonatan Cardona Casas <jace.casas@gmail.com> // // Copyright (c) 2017 // using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("SQLiteMigrations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Malla Creativa")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("0.1.2")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
// // AssemblyInfo.cs // // Author: // Jonatan Cardona Casas <jace.casas@gmail.com> // // Copyright (c) 2017 // using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("SQLiteMigrations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Malla Creativa")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("0.1.1")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
104e445232bd1d9dbe4fe43fcad0e09f52e1146b
Make PagingRewriter internal because we do not want to change public API with minor releases.
fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core
src/NHibernate/Linq/GroupBy/PagingRewriter.cs
src/NHibernate/Linq/GroupBy/PagingRewriter.cs
using System.Linq; using NHibernate.Linq.Visitors; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; namespace NHibernate.Linq.GroupBy { internal static class PagingRewriter { private static readonly System.Type[] PagingResultOperators = new[] { typeof (SkipResultOperator), typeof (TakeResultOperator), }; public static void ReWrite(QueryModel queryModel) { var subQueryExpression = queryModel.MainFromClause.FromExpression as SubQueryExpression; if (subQueryExpression != null && subQueryExpression.QueryModel.ResultOperators.All(x => PagingResultOperators.Contains(x.GetType()))) { FlattenSubQuery(subQueryExpression, queryModel); } } private static void FlattenSubQuery(SubQueryExpression subQueryExpression, QueryModel queryModel) { // we can not flattern subquery if outer query has body clauses. var subQueryModel = subQueryExpression.QueryModel; var subQueryMainFromClause = subQueryModel.MainFromClause; if (queryModel.BodyClauses.Count == 0) { foreach (var resultOperator in subQueryModel.ResultOperators) queryModel.ResultOperators.Add(resultOperator); foreach (var bodyClause in subQueryModel.BodyClauses) queryModel.BodyClauses.Add(bodyClause); } else { var cro = new ContainsResultOperator(new QuerySourceReferenceExpression(subQueryMainFromClause)); var newSubQueryModel = subQueryModel.Clone(); newSubQueryModel.ResultOperators.Add(cro); newSubQueryModel.ResultTypeOverride = typeof(bool); var where = new WhereClause(new SubQueryExpression(newSubQueryModel)); queryModel.BodyClauses.Add(where); if (!queryModel.BodyClauses.OfType<OrderByClause>().Any()) { var orderByClauses = subQueryModel.BodyClauses.OfType<OrderByClause>(); foreach (var orderByClause in orderByClauses) queryModel.BodyClauses.Add(orderByClause); } } var visitor1 = new PagingRewriterSelectClauseVisitor(); queryModel.SelectClause.TransformExpressions(visitor1.Swap); // Point all query source references to the outer from clause var visitor2 = new SwapQuerySourceVisitor(queryModel.MainFromClause, subQueryMainFromClause); queryModel.TransformExpressions(visitor2.Swap); // Replace the outer query source queryModel.MainFromClause = subQueryMainFromClause; } } }
using System.Linq; using NHibernate.Linq.Visitors; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; namespace NHibernate.Linq.GroupBy { public static class PagingRewriter { private static readonly System.Type[] PagingResultOperators = new[] { typeof (SkipResultOperator), typeof (TakeResultOperator), }; public static void ReWrite(QueryModel queryModel) { var subQueryExpression = queryModel.MainFromClause.FromExpression as SubQueryExpression; if (subQueryExpression != null && subQueryExpression.QueryModel.ResultOperators.All(x => PagingResultOperators.Contains(x.GetType()))) { FlattenSubQuery(subQueryExpression, queryModel); } } private static void FlattenSubQuery(SubQueryExpression subQueryExpression, QueryModel queryModel) { // we can not flattern subquery if outer query has body clauses. var subQueryModel = subQueryExpression.QueryModel; var subQueryMainFromClause = subQueryModel.MainFromClause; if (queryModel.BodyClauses.Count == 0) { foreach (var resultOperator in subQueryModel.ResultOperators) queryModel.ResultOperators.Add(resultOperator); foreach (var bodyClause in subQueryModel.BodyClauses) queryModel.BodyClauses.Add(bodyClause); } else { var cro = new ContainsResultOperator(new QuerySourceReferenceExpression(subQueryMainFromClause)); var newSubQueryModel = subQueryModel.Clone(); newSubQueryModel.ResultOperators.Add(cro); newSubQueryModel.ResultTypeOverride = typeof(bool); var where = new WhereClause(new SubQueryExpression(newSubQueryModel)); queryModel.BodyClauses.Add(where); if (!queryModel.BodyClauses.OfType<OrderByClause>().Any()) { var orderByClauses = subQueryModel.BodyClauses.OfType<OrderByClause>(); foreach (var orderByClause in orderByClauses) queryModel.BodyClauses.Add(orderByClause); } } var visitor1 = new PagingRewriterSelectClauseVisitor(); queryModel.SelectClause.TransformExpressions(visitor1.Swap); // Point all query source references to the outer from clause var visitor2 = new SwapQuerySourceVisitor(queryModel.MainFromClause, subQueryMainFromClause); queryModel.TransformExpressions(visitor2.Swap); // Replace the outer query source queryModel.MainFromClause = subQueryMainFromClause; } } }
lgpl-2.1
C#
d15585153daf759289013bce8f06e32ada67a501
Fix breadcrumb display in directory selector overlapping new "show hidden" button
ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game/Graphics/UserInterfaceV2/OsuDirectorySelectorBreadcrumbDisplay.cs
osu.Game/Graphics/UserInterfaceV2/OsuDirectorySelectorBreadcrumbDisplay.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.IO; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.Sprites; using osuTK; namespace osu.Game.Graphics.UserInterfaceV2 { internal class OsuDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay { protected override Drawable CreateCaption() => new OsuSpriteText { Text = "Current Directory: ", Font = OsuFont.Default.With(size: OsuDirectorySelector.ITEM_HEIGHT), }; protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new OsuBreadcrumbDisplayComputer(); protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new OsuBreadcrumbDisplayDirectory(directory, displayName); public OsuDirectorySelectorBreadcrumbDisplay() { Padding = new MarginPadding(15); } private class OsuBreadcrumbDisplayComputer : OsuBreadcrumbDisplayDirectory { protected override IconUsage? Icon => null; public OsuBreadcrumbDisplayComputer() : base(null, "Computer") { } } private class OsuBreadcrumbDisplayDirectory : OsuDirectorySelectorDirectory { public OsuBreadcrumbDisplayDirectory(DirectoryInfo directory, string displayName = null) : base(directory, displayName) { } [BackgroundDependencyLoader] private void load() { Flow.Add(new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = FontAwesome.Solid.ChevronRight, Size = new Vector2(FONT_SIZE / 2) }); } protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.IO; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.Sprites; using osuTK; namespace osu.Game.Graphics.UserInterfaceV2 { internal class OsuDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay { protected override Drawable CreateCaption() => new OsuSpriteText { Text = "Current Directory: ", Font = OsuFont.Default.With(size: OsuDirectorySelector.ITEM_HEIGHT), }; protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new OsuBreadcrumbDisplayComputer(); protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new OsuBreadcrumbDisplayDirectory(directory, displayName); [BackgroundDependencyLoader] private void load() { Height = 50; } private class OsuBreadcrumbDisplayComputer : OsuBreadcrumbDisplayDirectory { protected override IconUsage? Icon => null; public OsuBreadcrumbDisplayComputer() : base(null, "Computer") { } } private class OsuBreadcrumbDisplayDirectory : OsuDirectorySelectorDirectory { public OsuBreadcrumbDisplayDirectory(DirectoryInfo directory, string displayName = null) : base(directory, displayName) { } [BackgroundDependencyLoader] private void load() { Flow.Add(new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = FontAwesome.Solid.ChevronRight, Size = new Vector2(FONT_SIZE / 2) }); } protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null; } } }
mit
C#
cc544403e2ec3c3fa0cb2fcfe337d16d758c13e1
Fix stress test generator
ivaylo5ev/ink,inkle/ink,ghostpattern/ink,ivaylo5ev/ink,ghostpattern/ink,inkle/ink
inklecate/StressTestContentGenerator.cs
inklecate/StressTestContentGenerator.cs
using System.Text; namespace Ink { internal class StressTestContentGenerator { public string content { get; private set; } public int sizeInKiloChars { get { return content.Length / 1024; } } public StressTestContentGenerator (int repetitions) { var initialContent = "VAR myVar = 5\n\n"; var repeatingContent = @"== test__X__ == This is some content in a test knot with the number {myVar}. { myVar > 2: - This evaluation is true. - This evaluation is false. } This is some more content. * A choice * * A sub-choice -> * Another choice ==> somewhere_else__X__ - A gather Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. myVar is {myVar}. * Another choice[.] which is obviously really cool And some content within that choice * * Another sub choice * * * Another another sub choice * * * * Yet another choice. With more content in that choice. - A final gather. Nice one. Isn't this great? -> somewhere_else__X__ == somewhere_else__X__ == This is somewhere else -> END "; var sb = new StringBuilder (); sb.Append (initialContent); for (int i = 1; i <= repetitions; ++i) { var content = repeatingContent.Replace ("__X__", i.ToString()); content = content.Replace ("__Y__", (i + 1).ToString()); sb.Append (content); } var finalContent = @" == test__X__ Done! -> END"; finalContent = finalContent.Replace ("__X__", (repetitions+1).ToString ()); sb.AppendFormat (finalContent, repetitions.ToString()); this.content = sb.ToString (); } } }
using System.Text; namespace Ink { internal class StressTestContentGenerator { public string content { get; private set; } public int sizeInKiloChars { get { return content.Length / 1024; } } public StressTestContentGenerator (int repetitions) { var initialContent = "~ var myVar = 5 + 5 + (3 * 2 * 9) + 1.2\n\n"; var repeatingContent = @"== test__X__ == This is some content in a test knot with the number {myVar}. { myVar > 2: - This evaluation is true. - This evaluation is false. } This is some more content. * A choice * * A sub-choice -> * Another choice ==> somewhere_else__X__ - A gather Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. Some more content within the gather. myVar is {myVar}. * Another choice[.] which is obviously really cool And some content within that choice * * Another sub choice * * * Another another sub choice * * * * Yet another choice. With more content in that choice. - A final gather. Nice one. Isn't this great? ==> test__Y__ ~ done == somewhere_else__X__ == This is somewhere else ~ done "; var sb = new StringBuilder (); sb.Append (initialContent); for (int i = 1; i <= repetitions; ++i) { var content = repeatingContent.Replace ("__X__", i.ToString()); content = content.Replace ("__Y__", (i + 1).ToString()); sb.Append (content); } var finalContent = @" == test__X__ Done! ~ done"; finalContent = finalContent.Replace ("__X__", (repetitions+1).ToString ()); sb.AppendFormat (finalContent, repetitions.ToString()); this.content = sb.ToString (); } } }
mit
C#
98a14358dca260023d947f82dbb40103278c32ba
Fix tests to pass with newer setup
nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner
MultiMiner.Xgminer.Discovery.Tests/MinerFinderTests.cs
MultiMiner.Xgminer.Discovery.Tests/MinerFinderTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Net; namespace MultiMiner.Xgminer.Discovery.Tests { [TestClass] public class MinerFinderTests { [TestMethod] public void MinerFinder_FindsMiners() { const int times = 3; for (int i = 0; i < times; i++) { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); Assert.IsTrue(miners.Count >= 3); } } [TestMethod] public void MinerFinder_ChecksMiners() { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); int goodCount = miners.Count; miners.Add(new IPEndPoint(IPAddress.Parse("10.0.0.1"), 1000)); int checkCount = MinerFinder.Check(miners).Count; Assert.IsTrue(checkCount == goodCount); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Net; namespace MultiMiner.Xgminer.Discovery.Tests { [TestClass] public class MinerFinderTests { [TestMethod] public void MinerFinder_FindsMiners() { const int times = 3; for (int i = 0; i < times; i++) { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); Assert.IsTrue(miners.Count >= 4); } } [TestMethod] public void MinerFinder_ChecksMiners() { List<IPEndPoint> miners = MinerFinder.Find("192.168.0.29-100", 4028, 4029); int goodCount = miners.Count; miners.Add(new IPEndPoint(IPAddress.Parse("10.0.0.1"), 1000)); int checkCount = MinerFinder.Check(miners).Count; Assert.IsTrue(checkCount == goodCount); } } }
mit
C#
a24b74f8d60e89d5cc4954d2e2c62aaaf30271a4
Remove old comment
nbarbettini/beautiful-rest-api-aspnetcore
src/BeautifulRestApi/TypeInfoAllMemberExtensions.cs
src/BeautifulRestApi/TypeInfoAllMemberExtensions.cs
using System; using System.Collections.Generic; using System.Reflection; namespace BeautifulRestApi { public static class TypeInfoAllMemberExtensions { public static IEnumerable<ConstructorInfo> GetAllConstructors(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredConstructors); public static IEnumerable<EventInfo> GetAllEvents(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredEvents); public static IEnumerable<FieldInfo> GetAllFields(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredFields); public static IEnumerable<MemberInfo> GetAllMembers(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredMembers); public static IEnumerable<MethodInfo> GetAllMethods(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredMethods); public static IEnumerable<TypeInfo> GetAllNestedTypes(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredNestedTypes); public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredProperties); private static IEnumerable<T> GetAll<T>(TypeInfo typeInfo, Func<TypeInfo, IEnumerable<T>> accessor) { while (typeInfo != null) { foreach (var t in accessor(typeInfo)) { yield return t; } typeInfo = typeInfo.BaseType?.GetTypeInfo(); } } } }
using System; using System.Collections.Generic; using System.Reflection; namespace BeautifulRestApi { //todo remove? public static class TypeInfoAllMemberExtensions { public static IEnumerable<ConstructorInfo> GetAllConstructors(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredConstructors); public static IEnumerable<EventInfo> GetAllEvents(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredEvents); public static IEnumerable<FieldInfo> GetAllFields(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredFields); public static IEnumerable<MemberInfo> GetAllMembers(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredMembers); public static IEnumerable<MethodInfo> GetAllMethods(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredMethods); public static IEnumerable<TypeInfo> GetAllNestedTypes(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredNestedTypes); public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo typeInfo) => GetAll(typeInfo, ti => ti.DeclaredProperties); private static IEnumerable<T> GetAll<T>(TypeInfo typeInfo, Func<TypeInfo, IEnumerable<T>> accessor) { while (typeInfo != null) { foreach (var t in accessor(typeInfo)) { yield return t; } typeInfo = typeInfo.BaseType?.GetTypeInfo(); } } } }
apache-2.0
C#
74c7d9e67d6f09eb182d0765e808f8c01821e2b8
Use WithChild
peppy/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,smoogipooo/osu
osu.Game.Rulesets.Mania/Mods/ManiaModHidden.cs
osu.Game.Rulesets.Mania/Mods/ManiaModHidden.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; using osuTK; namespace osu.Game.Rulesets.Mania.Mods { public class ManiaModHidden : ModHidden, IApplicableToDrawableRuleset<ManiaHitObject> { public override string Description => @"Keys fade out before you hit them!"; public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModFlashlight<ManiaHitObject>) }; public virtual void ApplyToDrawableRuleset(DrawableRuleset<ManiaHitObject> drawableRuleset) { ManiaPlayfield maniaPlayfield = (ManiaPlayfield)drawableRuleset.Playfield; foreach (Column column in maniaPlayfield.Stages.SelectMany(stage => stage.Columns)) { HitObjectContainer hoc = column.HitObjectArea.HitObjectContainer; Container hocParent = (Container)hoc.Parent; hocParent.Remove(hoc); hocParent.Add(CreateCover().WithChild(hoc).With(c => { c.RelativeSizeAxes = Axes.Both; c.Coverage = 0.5f; })); } } protected virtual PlayfieldCoveringContainer CreateCover() => new ModHiddenCoveringContainer(); private class ModHiddenCoveringContainer : PlayfieldCoveringContainer { public ModHiddenCoveringContainer() { Cover.Scale = new Vector2(1, -1); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; using osuTK; namespace osu.Game.Rulesets.Mania.Mods { public class ManiaModHidden : ModHidden, IApplicableToDrawableRuleset<ManiaHitObject> { public override string Description => @"Keys fade out before you hit them!"; public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModFlashlight<ManiaHitObject>) }; public virtual void ApplyToDrawableRuleset(DrawableRuleset<ManiaHitObject> drawableRuleset) { ManiaPlayfield maniaPlayfield = (ManiaPlayfield)drawableRuleset.Playfield; foreach (Column column in maniaPlayfield.Stages.SelectMany(stage => stage.Columns)) { HitObjectContainer hoc = column.HitObjectArea.HitObjectContainer; Container hocParent = (Container)hoc.Parent; hocParent.Remove(hoc); hocParent.Add(CreateCover().With(c => { c.RelativeSizeAxes = Axes.Both; c.Coverage = 0.5f; c.Child = hoc; })); } } protected virtual PlayfieldCoveringContainer CreateCover() => new ModHiddenCoveringContainer(); private class ModHiddenCoveringContainer : PlayfieldCoveringContainer { public ModHiddenCoveringContainer() { Cover.Scale = new Vector2(1, -1); } } } }
mit
C#
9966abf50fa97819b2cadcee908d3a1a14ecf4b1
Remove unused control references
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Launchpad/ViewLaunchpad.ascx.controls.cs
R7.University.Launchpad/ViewLaunchpad.ascx.controls.cs
using System.Web.UI.WebControls; namespace R7.University.Launchpad { public partial class ViewLaunchpad { protected MultiView multiView; protected LinkButton linkPositions; protected LinkButton linkDivisions; protected LinkButton linkEmployees; protected HyperLink linkAddItem; protected TextBox textSearch; protected LinkButton buttonSearch; protected LinkButton buttonResetSearch; protected GridView gridPositions; protected GridView gridDivisions; protected GridView gridEmployees; protected GridView gridAchievements; protected GridView gridAchievementTypes; protected GridView gridEduLevels; protected GridView gridEduPrograms; protected GridView gridEduProfiles; protected GridView gridDocumentTypes; protected GridView gridDocuments; protected GridView gridEduForms; protected Repeater repeatTabs; } }
using System.Web.UI.WebControls; namespace R7.University.Launchpad { public partial class ViewLaunchpad { protected MultiView multiView; protected LinkButton linkPositions; protected LinkButton linkDivisions; protected LinkButton linkEmployees; protected HyperLink linkAddItem; protected TextBox textSearch; protected LinkButton buttonSearch; protected LinkButton buttonResetSearch; protected GridView gridPositions; protected GridView gridDivisions; protected GridView gridEmployees; protected GridView gridAchievements; protected GridView gridAchievementTypes; protected GridView gridEduLevels; protected GridView gridEduPrograms; protected GridView gridEduProfiles; protected GridView gridDocumentTypes; protected GridView gridDocuments; protected GridView gridEduForms; protected GridView gridEduProgramDivisions; protected Repeater repeatTabs; } }
agpl-3.0
C#
b8270259592d9ecd753441235fbd3f343540f711
fix selection
conceptdev/xamarin-forms-samples,conceptdev/xamarin-forms-samples
RestaurantGuide/RestaurantGuide/RestaurantList.xaml.cs
RestaurantGuide/RestaurantGuide/RestaurantList.xaml.cs
using System; using System.Collections.Generic; using Xamarin.Forms; namespace RestaurantGuide { public partial class RestaurantList : ContentPage { public RestaurantList () { InitializeComponent (); } public RestaurantList (List<Restaurant> r) : this() { listView.ItemsSource = r; } protected override void OnAppearing () { base.OnAppearing (); Application.Current.Properties ["rid"] = ""; } public async void OnItemSelected (object sender, SelectedItemChangedEventArgs e) { if (e.SelectedItem == null) return; var r = (Restaurant)e.SelectedItem; Application.Current.Properties ["rid"] = r.Number; await App.Current.SavePropertiesAsync (); var rPage = new RestaurantDetail(); rPage.BindingContext = r; await Navigation.PushAsync(rPage); ((ListView)sender).SelectedItem = null; } } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace RestaurantGuide { public partial class RestaurantList : ContentPage { public RestaurantList () { InitializeComponent (); } //List<Restaurant> restaurants; public RestaurantList (List<Restaurant> r) : this() { //restaurants = r; listView.ItemsSource = r; } protected override void OnAppearing () { base.OnAppearing (); Application.Current.Properties ["rid"] = ""; } public async void OnItemSelected (object sender, SelectedItemChangedEventArgs e) { var r = (Restaurant)e.SelectedItem; Application.Current.Properties ["rid"] = r.Number; await App.Current.SavePropertiesAsync (); var rPage = new RestaurantDetail(); rPage.BindingContext = r; await Navigation.PushAsync(rPage); } } }
mit
C#
7f950f5fc70ab9560e8dd891232fe71aca090cc6
refactor usings in mysql.data
nProdanov/Team-French-75
TravelAgency/TravelAgency.MySqlData/MySqlModelMetadataSource.cs
TravelAgency/TravelAgency.MySqlData/MySqlModelMetadataSource.cs
using System.Collections.Generic; using Telerik.OpenAccess.Metadata.Fluent; namespace TravelAgency.MySqlData { public partial class MySqlModelMetadataSource : FluentMetadataSource { protected override IList<MappingConfiguration> PrepareMapping() { var configurations = new List<MappingConfiguration>(); var tripReportMapping = new MappingConfiguration<TripReportMySqlModel>(); tripReportMapping.MapType(tripReport => new { ID = tripReport.ID, Name = tripReport.TripName, Touroperator = tripReport.TouroperatorName, TotalTripsSold = tripReport.TotalTripsSold, TotalIncomes = tripReport.TotalIncomes }).ToTable("TripsReports"); tripReportMapping.HasProperty(c => c.ID).IsIdentity(); configurations.Add(tripReportMapping); return configurations; } } }
using System.Collections.Generic; using Telerik.OpenAccess.Metadata.Fluent; namespace TravelAgency.MySqlData { public partial class MySqlModelMetadataSource : FluentMetadataSource { protected override IList<MappingConfiguration> PrepareMapping() { var configurations = new List<MappingConfiguration>(); var tripReportMapping = new MappingConfiguration<TripReportMySqlModel>(); tripReportMapping.MapType(tripReport => new { ID = tripReport.ID, Name = tripReport.TripName, Touroperator = tripReport.TouroperatorName, TotalTripsSold = tripReport.TotalTripsSold, TotalIncomes = tripReport.TotalIncomes }).ToTable("TripsReports"); tripReportMapping.HasProperty(c => c.ID).IsIdentity(); configurations.Add(tripReportMapping); return configurations; } } }
mit
C#
a37f2e1861b127919677fcb2826f902b8f962d1c
bump pre-release version
Dalet/140-speedrun-timer,Dalet/140-speedrun-timer,Dalet/140-speedrun-timer
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.6.1.4")] [assembly: AssemblyFileVersion("0.6.1.4")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.6.1.2")] [assembly: AssemblyFileVersion("0.6.1.2")]
unlicense
C#
28bb575c9d574a6b780e598a3aad9f6d4d74c678
Bump to next version
danbarua/NEventSocket,pragmatrix/NEventSocket,danbarua/NEventSocket,pragmatrix/NEventSocket
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NEventSocket")] [assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")] [assembly: AssemblyCompany("Dan Barua")] [assembly: AssemblyProduct("NEventSocket")] [assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")] [assembly: AssemblyVersion("1.0.2.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NEventSocket")] [assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")] [assembly: AssemblyCompany("Dan Barua")] [assembly: AssemblyProduct("NEventSocket")] [assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")] [assembly: AssemblyVersion("1.0.1.0")]
mpl-2.0
C#
27efe48d493d354770c648581fff1d177ca8ba28
Clean code
WeihanLi/SparkTodo,WeihanLi/SparkTodo,WeihanLi/SparkTodo,WeihanLi/SparkTodo
SparkTodo.WebExtension/Program.cs
SparkTodo.WebExtension/Program.cs
using System.Threading.Tasks; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using SparkTodo.DataAccess; using SparkTodo.Models; using SparkTodo.WebExtension; using SparkTodo.WebExtension.Services; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.Services.AddBrowserExtensionServices(options => { options.ProjectNamespace = typeof(Program).Namespace; }); builder.Services.AddDbContextPool<SparkTodoDbContext>(options => options.UseInMemoryDatabase("SparkTodo") ); builder.Services.AddSingleton<TodoScheduler>(); //Repository builder.Services.RegisterAssemblyTypesAsImplementedInterfaces(t => t.Name.EndsWith("Repository"), ServiceLifetime.Scoped, typeof(IUserAccountRepository).Assembly); var host = builder.Build(); await host.Services.GetRequiredService<TodoScheduler>() .Start(); await host.RunAsync();
using System.Threading.Tasks; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using SparkTodo.DataAccess; using SparkTodo.Models; using SparkTodo.WebExtension.Services; using WeihanLi.EntityFramework; namespace SparkTodo.WebExtension { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.Services.AddBrowserExtensionServices(options => { options.ProjectNamespace = typeof(Program).Namespace; }); builder.Services.AddDbContextPool<SparkTodoDbContext>(options => options.UseInMemoryDatabase("SparkTodo") ); builder.Services.AddSingleton<TodoScheduler>(); //Repository builder.Services.RegisterAssemblyTypesAsImplementedInterfaces(t => t.Name.EndsWith("Repository"), ServiceLifetime.Scoped, typeof(IUserAccountRepository).Assembly); var host = builder.Build(); await host.Services.GetRequiredService<TodoScheduler>() .Start(); await host.RunAsync(); } } }
mit
C#
8d1bb3b29348e2b11897821bd16e56b092ed812e
Implement UnitTest for EditReport#InitializeForNewReportAsync.
ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey
client/BlueMonkey/BlueMonkey.Model.Tests/EditReportTest.cs
client/BlueMonkey/BlueMonkey.Model.Tests/EditReportTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BlueMonkey.Business; using BlueMonkey.ExpenceServices; using Moq; using Xunit; namespace BlueMonkey.Model.Tests { public class EditReportTest { [Fact] public void Constructor() { var expenseService = new Mock<IExpenseService>(); var actual = new EditReport(expenseService.Object); Assert.Null(actual.Name); Assert.Equal(default(DateTime), actual.Date); Assert.NotNull(actual.SelectableExpenses); Assert.False(actual.SelectableExpenses.Any()); } [Fact] public async Task InitializeForNewReportAsync() { var expenseService = new Mock<IExpenseService>(); var expense01 = new Expense(); var expense02 = new Expense(); var expenses = new [] { expense01, expense02 }; expenseService .Setup(m => m.GetExpensesAsync()) .ReturnsAsync(expenses); var actual = new EditReport(expenseService.Object); await actual.InitializeForNewReportAsync(); Assert.Null(actual.Name); Assert.Equal(DateTime.Today, actual.Date); Assert.NotNull(actual.SelectableExpenses); Assert.Equal(2, actual.SelectableExpenses.Count); Assert.False(actual.SelectableExpenses[0].IsSelected); Assert.Equal(expense01.Id, actual.SelectableExpenses[0].Id); Assert.False(actual.SelectableExpenses[1].IsSelected); Assert.Equal(expense02.Id, actual.SelectableExpenses[1].Id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BlueMonkey.ExpenceServices; using Moq; using Xunit; namespace BlueMonkey.Model.Tests { public class EditReportTest { [Fact] public void Constructor() { var expenseService = new Mock<IExpenseService>(); var actual = new EditReport(expenseService.Object); Assert.Null(actual.Name); Assert.Equal(default(DateTime), actual.Date); Assert.NotNull(actual.SelectableExpenses); Assert.False(actual.SelectableExpenses.Any()); } } }
mit
C#
26e70e8f3b4ec39bbd4ebaaa0421e46b82e0ce2f
Fix spelling errors
dalealleshouse/TuringMachine
TuringMachine/Head.cs
TuringMachine/Head.cs
using System; using System.Collections.Generic; using System.Linq; namespace TuringMachine { public class Head { public const char Blank = '_'; public Head(IEnumerable<char> tape, int headPosition) { if (tape == null) throw new ArgumentNullException(nameof(tape)); var safeData = tape as char[] ?? tape.ToArray(); if (headPosition > safeData.Count() - 1 || headPosition < 0) throw new IndexOutOfRangeException("Invalid head position"); Tape = safeData; HeadPosition = headPosition; } public IEnumerable<char> Tape { get; } public int HeadPosition { get; } public Head Write(char head) => new Head(new List<char>(Tape) { [HeadPosition] = head }, HeadPosition); public Head MoveLeft() => HeadPosition == 0 ? new Head(new[] { Blank }.Concat(Tape), 0) : new Head(Tape, HeadPosition - 1); public Head MoveRight() => HeadPosition == Tape.Count() - 1 ? new Head(Tape.Concat(new[] { Blank }), HeadPosition + 1) : new Head(Tape, HeadPosition + 1); public Head Move(HeadDirection direction) { switch (direction) { case HeadDirection.Left: return MoveLeft(); case HeadDirection.NoMove: return this; case HeadDirection.Right: return MoveRight(); default: throw new ArgumentOutOfRangeException(nameof(direction), direction, null); } } public char Read() => Tape.ElementAt(HeadPosition); public override string ToString() => $@"Tape: {Tape.Select(GetChar).Aggregate((agg, next) => agg + next)}"; private string GetChar(char c, int index) => index == HeadPosition ? $"({c})" : c.ToString(); } }
using System; using System.Collections.Generic; using System.Linq; namespace TuringMachine { public class Head { public const char Blank = '_'; public Head(IEnumerable<char> tape, int headPosition) { if (tape == null) throw new ArgumentNullException(nameof(tape)); var safeData = tape as char[] ?? tape.ToArray(); if (headPosition > safeData.Count() - 1 || headPosition < 0) throw new IndexOutOfRangeException("Invalid head postion"); this.Tape = safeData; this.HeadPosition = headPosition; } public IEnumerable<char> Tape { get; } public int HeadPosition { get; } public Head Write(char head) => new Head(new List<char>(this.Tape) { [this.HeadPosition] = head }, this.HeadPosition); public Head MoveLeft() => this.HeadPosition == 0 ? new Head(new[] { Blank }.Concat(this.Tape), 0) : new Head(this.Tape, this.HeadPosition - 1); public Head MoveRight() => this.HeadPosition == this.Tape.Count() - 1 ? new Head(this.Tape.Concat(new[] { Blank }), this.HeadPosition + 1) : new Head(this.Tape, this.HeadPosition + 1); public Head Move(HeadDirection direction) { switch (direction) { case HeadDirection.Left: return this.MoveLeft(); case HeadDirection.NoMove: return this; case HeadDirection.Right: return this.MoveRight(); default: throw new ArgumentOutOfRangeException(nameof(direction), direction, null); } } public char Read() => this.Tape.ElementAt(this.HeadPosition); public override string ToString() => $@"Tape: {this.Tape.Select(GetChar).Aggregate((agg, next) => agg + next)}"; private string GetChar(char c, int index) => index == this.HeadPosition ? $"({c})" : c.ToString(); } }
unlicense
C#
87426a000d28614a65b82843d1d9cf9d08c5e74d
Implement IDisposable on SetUp class in Specs
Myslik/opencat,Myslik/opencat
WebApp.Specs/SetUp.cs
WebApp.Specs/SetUp.cs
using System; using System.Configuration; using System.Diagnostics; using System.IO; using MongoDB.Driver; using NUnit.Framework; using OpenCat; namespace WebApp.Specs { [SetUpFixture] public class SetUp : IDisposable { private Process iisexpress; private string IISExpress { get { var programs = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); return Path.Combine(programs, "IIS Express\\iisexpress.exe"); } } private string SitePath { get { var path = new DirectoryInfo(Environment.CurrentDirectory); return Path.Combine(path.Parent.Parent.Parent.FullName, "WebApp"); } } private int Port { get { return Int32.Parse(ConfigurationManager.AppSettings["port"]); } } [SetUp] public void RunBeforeAnyTests() { iisexpress = new Process(); iisexpress.StartInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Hidden, FileName = IISExpress, Arguments = String.Format("/path:{0} /port:{1}", SitePath, Port) }; iisexpress.Start(); } [TearDown] public void RunAfterAnyTests() { if (!iisexpress.HasExited) { iisexpress.Kill(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~SetUp() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) { if (iisexpress != null) { iisexpress.Dispose(); iisexpress = null; } } } } }
using System; using System.Configuration; using System.Diagnostics; using System.IO; using MongoDB.Driver; using NUnit.Framework; using OpenCat; namespace WebApp.Specs { [SetUpFixture] public class SetUp { private Process iisexpress; private string IISExpress { get { var programs = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); return Path.Combine(programs, "IIS Express\\iisexpress.exe"); } } private string SitePath { get { var path = new DirectoryInfo(Environment.CurrentDirectory); return Path.Combine(path.Parent.Parent.Parent.FullName, "WebApp"); } } private int Port { get { return Int32.Parse(ConfigurationManager.AppSettings["port"]); } } [SetUp] public void RunBeforeAnyTests() { iisexpress = new Process(); iisexpress.StartInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Hidden, FileName = IISExpress, Arguments = String.Format("/path:{0} /port:{1}", SitePath, Port) }; iisexpress.Start(); } [TearDown] public void RunAfterAnyTests() { if (!iisexpress.HasExited) { iisexpress.Kill(); } } } }
mit
C#
fd90977dfc502ee784b28b05b552d5126a5b389c
Revert "Enabled cascading delete"
miracle-as/kitos,miracle-as/kitos,os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,os2kitos/kitos
Infrastructure.DataAccess/Mapping/ItProjectStatusMap.cs
Infrastructure.DataAccess/Mapping/ItProjectStatusMap.cs
using Core.DomainModel.ItProject; namespace Infrastructure.DataAccess.Mapping { public class ItProjectStatusMap : EntityMap<ItProjectStatus> { public ItProjectStatusMap() { // Table & Column Mappings this.ToTable("ItProjectStatus"); this.HasOptional(t => t.AssociatedUser) .WithMany(d => d.ItProjectStatuses) .HasForeignKey(t => t.AssociatedUserId) .WillCascadeOnDelete(false); this.HasRequired(t => t.AssociatedItProject) .WithMany(t => t.ItProjectStatuses) .HasForeignKey(d => d.AssociatedItProjectId) .WillCascadeOnDelete(false); } } }
using Core.DomainModel.ItProject; namespace Infrastructure.DataAccess.Mapping { public class ItProjectStatusMap : EntityMap<ItProjectStatus> { public ItProjectStatusMap() { // Table & Column Mappings this.ToTable("ItProjectStatus"); this.HasOptional(t => t.AssociatedUser) .WithMany(d => d.ItProjectStatuses) .HasForeignKey(t => t.AssociatedUserId) .WillCascadeOnDelete(false); this.HasRequired(t => t.AssociatedItProject) .WithMany(t => t.ItProjectStatuses) .HasForeignKey(d => d.AssociatedItProjectId) .WillCascadeOnDelete(true); } } }
mpl-2.0
C#
7a918af827604f05a7342e761a04a11d379bca1d
Use language rather than platform type
unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl
MatterControlLib/PrinterCommunication/Io/SendProgressStream.cs
MatterControlLib/PrinterCommunication/Io/SendProgressStream.cs
/* Copyright (c) 2019, Tyler Anderson, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.PrinterCommunication.Io { public class SendProgressStream : GCodeStreamProxy { private double nextPercent = -1; public SendProgressStream(GCodeStream internalStream, PrinterConfig printer) : base(printer, internalStream) { } public override string DebugInfo => ""; public override string ReadLine() { if (printer.Settings.GetValue(SettingsKey.progress_reporting) != "None" && printer.Connection.CommunicationState == CommunicationStates.Printing && printer.Connection.ActivePrintTask != null && printer.Connection.ActivePrintTask.PercentDone > nextPercent) { nextPercent = Math.Round(printer.Connection.ActivePrintTask.PercentDone) + 0.5; if (printer.Settings.GetValue(SettingsKey.progress_reporting) == "M73") { return string.Format("M73 P{0:0}", printer.Connection.ActivePrintTask.PercentDone); } else { return string.Format("M117 Printing - {0:0}%", printer.Connection.ActivePrintTask.PercentDone); } } return base.ReadLine(); } } }
/* Copyright (c) 2015, Lars Brubaker 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.MatterControl.DataStorage; using MatterHackers.MatterControl.SlicerConfiguration; using System; namespace MatterHackers.MatterControl.PrinterCommunication.Io { public class SendProgressStream : GCodeStreamProxy { private double nextPercent = -1; public SendProgressStream(GCodeStream internalStream, PrinterConfig printer) : base(printer, internalStream) { } public override string DebugInfo => ""; public override string ReadLine() { if (printer.Settings.GetValue(SettingsKey.progress_reporting) != "None" && printer.Connection.CommunicationState == CommunicationStates.Printing && printer.Connection.ActivePrintTask != null && printer.Connection.ActivePrintTask.PercentDone > nextPercent) { nextPercent = Math.Round(printer.Connection.ActivePrintTask.PercentDone) + 0.5; if (printer.Settings.GetValue(SettingsKey.progress_reporting) == "M73") { return String.Format("M73 P{0:0}", printer.Connection.ActivePrintTask.PercentDone); } else { return String.Format("M117 Printing - {0:0}%", printer.Connection.ActivePrintTask.PercentDone); } } return base.ReadLine(); } } }
bsd-2-clause
C#
3258a6dbe7e49fed219907b943b5d8381e9462cf
Add a much more accurate measuring system
peejster/Rover,jmservera/Rover
Rover/UltrasonicDistanceSensor.cs
Rover/UltrasonicDistanceSensor.cs
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Gpio; namespace Rover { public class UltrasonicDistanceSensor { private readonly GpioPin _gpioPinTrig; // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private readonly GpioPin _gpioPinEcho; public UltrasonicDistanceSensor(int trigGpioPin, int echoGpioPin) { var gpio = GpioController.GetDefault(); _gpioPinTrig = gpio.OpenPin(trigGpioPin); _gpioPinEcho = gpio.OpenPin(echoGpioPin); _gpioPinTrig.SetDriveMode(GpioPinDriveMode.Output); _gpioPinEcho.SetDriveMode(GpioPinDriveMode.Input); _gpioPinTrig.Write(GpioPinValue.Low); } public Task<double> GetDistanceInCmAsync(int timeoutInMilliseconds) { return Task.Run(() => { double distance = double.MaxValue; // turn on the pulse _gpioPinTrig.Write(GpioPinValue.High); Task.Delay(TimeSpan.FromTicks(100)).Wait(); _gpioPinTrig.Write(GpioPinValue.Low); SpinWait.SpinUntil(()=> { return _gpioPinEcho.Read() != GpioPinValue.Low; }); var stopwatch = Stopwatch.StartNew(); while (stopwatch.ElapsedMilliseconds < timeoutInMilliseconds && _gpioPinEcho.Read() == GpioPinValue.High) { distance = stopwatch.Elapsed.TotalSeconds * 17150; } stopwatch.Stop(); return distance; }); } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using Windows.Devices.Gpio; namespace Rover { public class UltrasonicDistanceSensor { private readonly GpioPin _gpioPinTrig; // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private readonly GpioPin _gpioPinEcho; private readonly Stopwatch _stopwatch; private double? _distance; public UltrasonicDistanceSensor(int trigGpioPin, int echoGpioPin) { _stopwatch = new Stopwatch(); var gpio = GpioController.GetDefault(); _gpioPinTrig = gpio.OpenPin(trigGpioPin); _gpioPinEcho = gpio.OpenPin(echoGpioPin); _gpioPinTrig.SetDriveMode(GpioPinDriveMode.Output); _gpioPinEcho.SetDriveMode(GpioPinDriveMode.Input); _gpioPinTrig.Write(GpioPinValue.Low); _gpioPinEcho.ValueChanged += GpioPinEcho_ValueChanged; } private void GpioPinEcho_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args) { _distance = _stopwatch.ElapsedMilliseconds * 34.3 / 2.0; } public async Task<double> GetDistanceInCmAsync(int timeoutInMilliseconds) { _distance = null; try { _stopwatch.Reset(); // turn on the pulse _gpioPinTrig.Write(GpioPinValue.High); await Task.Delay(TimeSpan.FromMilliseconds(10)); _gpioPinTrig.Write(GpioPinValue.Low); _stopwatch.Start(); for (var i = 0; i < timeoutInMilliseconds/100; i++) { if (_distance.HasValue) return _distance.Value; await Task.Delay(TimeSpan.FromMilliseconds(100)); } } finally { _stopwatch.Stop(); } return double.MaxValue; } } }
mit
C#
6afadf197f23138b4df387cfb50d30ef46a678e6
Fix for namespace collision.
kniteli/Pulsar4x,ProgrammerHero/Pulsar4x
Pulsar4X/Pulsar4X.Lib/Entities/StarSystem/Atmosphere.cs
Pulsar4X/Pulsar4X.Lib/Entities/StarSystem/Atmosphere.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pulsar4X.Entities { /// <summary> /// The Atmosphere of a Planet or Moon. /// @todo Make this a generic component. /// </summary> class Atmosphere { /// <summary> /// Atmospheric Presure /// Units to be decided. /// </summary> public float Pressure { get; set; } /// <summary> /// Weather or not the planet has abundent water. /// </summary> public bool Hydrosphere { get; set; } /// <summary> /// The percentage of the bodies sureface covered by water. /// </summary> public short HydrosphereExtent { get; set; } /// <summary> /// A measure of the greenhouse factor provided by this Atmosphere. /// </summary> public float GreenhouseFactor { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pulsar4X.Entities.StarSystem { /// <summary> /// The Atmosphere of a Planet or Moon. /// @todo Make this a generic component. /// </summary> class Atmosphere { /// <summary> /// Atmospheric Presure /// Units to be decided. /// </summary> public float Pressure { get; set; } /// <summary> /// Weather or not the planet has abundent water. /// </summary> public bool Hydrosphere { get; set; } /// <summary> /// The percentage of the bodies sureface covered by water. /// </summary> public short HydrosphereExtent { get; set; } /// <summary> /// A measure of the greenhouse factor provided by this Atmosphere. /// </summary> public float GreenhouseFactor { get; set; } } }
mit
C#
5de271b25f8aba5ec4e3ffe63f5be6031a255456
add missing model: FeedPackageFilter
lvermeulen/ProGet.Net
src/ProGet.Net/Native/Models/FeedPackageFilter.cs
src/ProGet.Net/Native/Models/FeedPackageFilter.cs
// ReSharper disable InconsistentNaming namespace ProGet.Net.Native.Models { public class FeedPackageFilter { public int Feed_Id { get; set; } public int Sequence_Number { get; set; } public string PackageFilter_Name { get; set; } public string PackageFilter_Configuration { get; set; } } }
namespace ProGet.Net.Native.Models { public class FeedPackageFilter { } }
mit
C#
f9098220e84037d0c609b78c11f0670c092a4fd1
Update QRUtils.cs
HouseBreaker/Shameless
Shameless/QRGeneration/QRUtils.cs
Shameless/QRGeneration/QRUtils.cs
namespace Shameless.QRGeneration { using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ZXing; using ZXing.Common; public static class QrUtils { public static QrResult MakeUrlIntoQrCode(string url) { var writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Height = 325, Width = 325 } }; var result = writer.Write(url); var qrResult = new QrResult(url, new Bitmap(result)); return qrResult; } public static string Shorten(string url) { return url; } } }
namespace Shameless.QRGeneration { using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ZXing; using ZXing.Common; public static class QrUtils { public static QrResult MakeUrlIntoQrCode(string url) { var writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Height = 325, Width = 325 } }; var result = writer.Write(url); var qrResult = new QrResult(url, new Bitmap(result)); return qrResult; } public static string Shorten(string url) { string shortUrl; return shortUrl; } } }
mit
C#