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
24c09fa37ffb954739c32ce91716cf0a1c4fde7c
make not-oculus-specific
gradientspace/frame3Sharp
behaviors/ScreenCaptureBehavior.cs
behaviors/ScreenCaptureBehavior.cs
using System; using System.Collections.Generic; using UnityEngine; namespace f3 { public class ScreenCaptureBehavior : StandardInputBehavior { public string ScreenshotPath = "C:\\"; public string ScreenshotPrefix = "Screenshot_"; public ScreenCaptureBehavior() { } public override InputDevice SupportedDevices { get { return InputDevice.AnySpatialDevice; } } public override CaptureRequest WantsCapture(InputState input) { throw new NotImplementedException("ScreenCaptureBehavior.WantsCapture: this is an override behavior and does not capture!!"); } public override Capture BeginCapture(InputState input, CaptureSide eSide) { throw new NotImplementedException("ScreenCaptureBehavior.BeginCapture: this is an override behavior and does not capture!!"); } public override Capture UpdateCapture(InputState input, CaptureData data) { if (input.bLeftMenuButtonReleased) { string sDate = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss"); // + DateTime.Now.ToString("tt").ToLower(); bool bDone = false; int i = 0; while (!bDone && i < 100) { string sPath = ScreenshotPath + ScreenshotPrefix + sDate + ((i == 0) ? "" : "_" + i.ToString()) + ".png"; i++; if (System.IO.File.Exists(sPath)) continue; UnityEngine.Application.CaptureScreenshot(sPath, 4); DebugUtil.Log(0, "Wrote screenshot " + sPath); bDone = true; } } return Capture.Ignore; } public override Capture ForceEndCapture(InputState input, CaptureData data) { throw new NotImplementedException("ScreenCaptureBehavior.ForceEndCapture: this is an override behavior and does not capture!!"); } } }
using System; using System.Collections.Generic; using UnityEngine; namespace f3 { public class ScreenCaptureBehavior : StandardInputBehavior { public string ScreenshotPath = "C:\\"; public string ScreenshotPrefix = "Screenshot_"; public ScreenCaptureBehavior() { } public override InputDevice SupportedDevices { get { return InputDevice.OculusTouch; } } public override CaptureRequest WantsCapture(InputState input) { throw new NotImplementedException("ScreenCaptureBehavior.WantsCapture: this is an override behavior and does not capture!!"); } public override Capture BeginCapture(InputState input, CaptureSide eSide) { throw new NotImplementedException("ScreenCaptureBehavior.BeginCapture: this is an override behavior and does not capture!!"); } public override Capture UpdateCapture(InputState input, CaptureData data) { if (input.bLeftMenuButtonReleased) { string sDate = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss"); // + DateTime.Now.ToString("tt").ToLower(); bool bDone = false; int i = 0; while (!bDone && i < 100) { string sPath = ScreenshotPath + ScreenshotPrefix + sDate + ((i == 0) ? "" : "_" + i.ToString()) + ".png"; i++; if (System.IO.File.Exists(sPath)) continue; UnityEngine.Application.CaptureScreenshot(sPath, 4); DebugUtil.Log(0, "Wrote screenshot " + sPath); bDone = true; } } return Capture.Ignore; } public override Capture ForceEndCapture(InputState input, CaptureData data) { throw new NotImplementedException("ScreenCaptureBehavior.ForceEndCapture: this is an override behavior and does not capture!!"); } } }
mit
C#
a94109f2806663c16fc092c1c8bc823512ce4fd8
upgrade enode.equeue to 1.6.3
tangxuehua/enode,Aaron-Liu/enode
src/ENode.EQueue/Properties/AssemblyInfo.cs
src/ENode.EQueue/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("ENode.EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode.EQueue")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e534ee24-4ea0-410e-847a-227e53faed7c")] // 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.6.3")] [assembly: AssemblyFileVersion("1.6.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("ENode.EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode.EQueue")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e534ee24-4ea0-410e-847a-227e53faed7c")] // 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.6.2")] [assembly: AssemblyFileVersion("1.6.2")]
mit
C#
11ee72a0a483c61835161afcbe3da0f59182e40a
use new varable name for current branch in gitlab ci
dazinator/GitVersion,asbjornu/GitVersion,asbjornu/GitVersion,gep13/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,ParticularLabs/GitVersion,dazinator/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,ermshiperete/GitVersion,ParticularLabs/GitVersion
src/GitVersionCore/BuildServers/GitLabCi.cs
src/GitVersionCore/BuildServers/GitLabCi.cs
namespace GitVersion { using System; using System.IO; public class GitLabCi : BuildServerBase { string _file; public GitLabCi() : this("gitversion.properties") { } public GitLabCi(string propertiesFileName) { _file = propertiesFileName; } public override bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GITLAB_CI")); } public override string GenerateSetVersionMessage(VersionVariables variables) { return variables.FullSemVer; } public override string[] GenerateSetParameterMessage(string name, string value) { return new[] { $"GitVersion_{name}={value}" }; } public override string GetCurrentBranch(bool usingDynamicRepos) { return Environment.GetEnvironmentVariable("CI_COMMIT_REF_NAME"); } public override bool PreventFetch() { return true; } public override void WriteIntegration(Action<string> writer, VersionVariables variables) { base.WriteIntegration(writer, variables); writer($"Outputting variables to '{_file}' ... "); WriteVariablesFile(variables); } void WriteVariablesFile(VersionVariables variables) { File.WriteAllLines(_file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables)); } } }
namespace GitVersion { using System; using System.IO; public class GitLabCi : BuildServerBase { string _file; public GitLabCi() : this("gitversion.properties") { } public GitLabCi(string propertiesFileName) { _file = propertiesFileName; } public override bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GITLAB_CI")); } public override string GenerateSetVersionMessage(VersionVariables variables) { return variables.FullSemVer; } public override string[] GenerateSetParameterMessage(string name, string value) { return new[] { $"GitVersion_{name}={value}" }; } public override string GetCurrentBranch(bool usingDynamicRepos) { return Environment.GetEnvironmentVariable("CI_BUILD_REF_NAME"); } public override bool PreventFetch() { return true; } public override void WriteIntegration(Action<string> writer, VersionVariables variables) { base.WriteIntegration(writer, variables); writer($"Outputting variables to '{_file}' ... "); WriteVariablesFile(variables); } void WriteVariablesFile(VersionVariables variables) { File.WriteAllLines(_file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables)); } } }
mit
C#
14ffdf6ed28d9e89224f41f754dd2a300f467198
Use the AppSettings 'NuGetPackagePath' if exists and the default ~/Packages otherwise
antiufo/NuGet2,GearedToWar/NuGet2,mrward/nuget,jmezach/NuGet2,jholovacs/NuGet,pratikkagda/nuget,indsoft/NuGet2,mrward/nuget,indsoft/NuGet2,antiufo/NuGet2,pratikkagda/nuget,oliver-feng/nuget,indsoft/NuGet2,akrisiun/NuGet,dolkensp/node.net,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,jmezach/NuGet2,oliver-feng/nuget,mrward/NuGet.V2,zskullz/nuget,GearedToWar/NuGet2,rikoe/nuget,ctaggart/nuget,atheken/nuget,indsoft/NuGet2,zskullz/nuget,themotleyfool/NuGet,GearedToWar/NuGet2,GearedToWar/NuGet2,jholovacs/NuGet,mrward/NuGet.V2,kumavis/NuGet,jmezach/NuGet2,anurse/NuGet,antiufo/NuGet2,alluran/node.net,jholovacs/NuGet,dolkensp/node.net,zskullz/nuget,mono/nuget,jmezach/NuGet2,themotleyfool/NuGet,rikoe/nuget,ctaggart/nuget,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,ctaggart/nuget,xero-github/Nuget,alluran/node.net,mrward/NuGet.V2,atheken/nuget,xoofx/NuGet,oliver-feng/nuget,chocolatey/nuget-chocolatey,antiufo/NuGet2,mrward/nuget,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,rikoe/nuget,GearedToWar/NuGet2,alluran/node.net,jholovacs/NuGet,kumavis/NuGet,oliver-feng/nuget,alluran/node.net,jholovacs/NuGet,akrisiun/NuGet,dolkensp/node.net,dolkensp/node.net,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,mrward/nuget,oliver-feng/nuget,antiufo/NuGet2,xoofx/NuGet,indsoft/NuGet2,xoofx/NuGet,anurse/NuGet,xoofx/NuGet,mrward/nuget,mrward/NuGet.V2,pratikkagda/nuget,chester89/nugetApi,chocolatey/nuget-chocolatey,mrward/NuGet.V2,chester89/nugetApi,OneGet/nuget,mrward/nuget,GearedToWar/NuGet2,mono/nuget,mrward/NuGet.V2,zskullz/nuget,xoofx/NuGet,oliver-feng/nuget,rikoe/nuget,chocolatey/nuget-chocolatey,chocolatey/nuget-chocolatey,pratikkagda/nuget,pratikkagda/nuget,mono/nuget,RichiCoder1/nuget-chocolatey,OneGet/nuget,xoofx/NuGet,pratikkagda/nuget,jmezach/NuGet2,OneGet/nuget,jmezach/NuGet2,jholovacs/NuGet,antiufo/NuGet2,ctaggart/nuget,mono/nuget,themotleyfool/NuGet,OneGet/nuget
src/Server/Infrastructure/PackageUtility.cs
src/Server/Infrastructure/PackageUtility.cs
using System; using System.Web; using System.Web.Hosting; using System.Configuration; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath; private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); static PackageUtility() { string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"]; if (string.IsNullOrEmpty(packagePath)) { PackagePhysicalPath = DefaultPackagePhysicalPath; } else { PackagePhysicalPath = packagePath; } } public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } }
using System; using System.Web; using System.Web.Hosting; namespace NuGet.Server.Infrastructure { public class PackageUtility { internal static string PackagePhysicalPath = HostingEnvironment.MapPath("~/Packages"); public static Uri GetPackageUrl(string path, Uri baseUri) { return new Uri(baseUri, GetPackageDownloadUrl(path)); } private static string GetPackageDownloadUrl(string path) { return VirtualPathUtility.ToAbsolute("~/Packages/" + path); } } }
apache-2.0
C#
74ee3948b0338ad668b899ea49a6ca061306b1d4
Fix nullref in NoCacheAttribute
thinktecture/relayserver,jasminsehic/relayserver,jasminsehic/relayserver,thinktecture/relayserver,thinktecture/relayserver,jasminsehic/relayserver
Thinktecture.Relay.Server/Http/Filters/NoCacheAttribute.cs
Thinktecture.Relay.Server/Http/Filters/NoCacheAttribute.cs
using System; using System.Net.Http.Headers; using System.Web.Http.Filters; namespace Thinktecture.Relay.Server.Http.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class NoCacheAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null) { actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true, NoStore = true, }; } base.OnActionExecuted(actionExecutedContext); } } }
using System; using System.Net.Http.Headers; using System.Web.Http.Filters; namespace Thinktecture.Relay.Server.Http.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class NoCacheAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true, NoStore = true, }; base.OnActionExecuted(actionExecutedContext); } } }
bsd-3-clause
C#
81f433a989d9ce25c5803e6c2687e627a6132e95
fix human story
peteroid/HumanWannabe
Assets/Scripts/DialogueScript.cs
Assets/Scripts/DialogueScript.cs
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; using SimpleJSON; using System.IO; public class DialogueScript : MonoBehaviour { public float delay; public Tile.TerrainType lastType; public Text dialogue1; public Text dialogue2; public Image image1; public Image image2; public Sprite spriteCat; public Sprite spriteOther; public SharedDataScript sharedDataObject; public void LoadGameScene () { SceneManager.LoadScene("UnifiedGame"); } // Use this for initialization void Start () { Invoke ("LoadGameScene", delay); TextAsset levelFile = Resources.Load<TextAsset>("Levels/StoryData"); JSONNode jsonObj = JSON.Parse(levelFile.text); JSONArray data = jsonObj["catStory"].AsArray; Debug.Log (sharedDataObject.type); if (sharedDataObject.type == Tile.TerrainType.kHumanExit) { Debug.Log ("human"); data = jsonObj ["human"].AsArray; } JSONArray order = data[sharedDataObject.levelIndex]["order"].AsArray; if (order.Count > 0) { dialogue1.text = data[sharedDataObject.levelIndex][order[0]]; // Debug.Log (order [0].Value == "cat"); if (order [0].Value == "cat") image1.overrideSprite = spriteCat; else if (order [0].Value == "other") image1.overrideSprite = spriteOther; } if (order.Count > 1) { dialogue2.text = data[sharedDataObject.levelIndex][order[1]]; Debug.Log (order [1].Value); if (order [1].Value == "cat") image2.overrideSprite = spriteCat; else if (order [1].Value == "other") image2.overrideSprite = spriteOther; image2.gameObject.SetActive (true); } } // Update is called once per frame void Update () { } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; using SimpleJSON; using System.IO; public class DialogueScript : MonoBehaviour { public float delay; public Tile.TerrainType lastType; public Text dialogue1; public Text dialogue2; public Image image1; public Image image2; public Sprite spriteCat; public Sprite spriteOther; public SharedDataScript sharedDataObject; public void LoadGameScene () { SceneManager.LoadScene("UnifiedGame"); } // Use this for initialization void Start () { Invoke ("LoadGameScene", delay); TextAsset levelFile = Resources.Load<TextAsset>("Levels/StoryData"); JSONNode jsonObj = JSON.Parse(levelFile.text); JSONArray data = jsonObj["catStory"].AsArray; if (lastType == Tile.TerrainType.kHumanExit) data = jsonObj["humanStory"].AsArray; JSONArray order = data[sharedDataObject.levelIndex]["order"].AsArray; if (order.Count > 0) { dialogue1.text = data[sharedDataObject.levelIndex][order[0]]; // Debug.Log (order [0].Value == "cat"); if (order [0].Value == "cat") image1.overrideSprite = spriteCat; else if (order [0].Value == "other") image1.overrideSprite = spriteOther; } if (order.Count > 1) { dialogue2.text = data[sharedDataObject.levelIndex][order[1]]; Debug.Log (order [1].Value); if (order [1].Value == "cat") image2.overrideSprite = spriteCat; else if (order [1].Value == "other") image2.overrideSprite = spriteOther; image2.gameObject.SetActive (true); } } // Update is called once per frame void Update () { } }
cc0-1.0
C#
b9e867317565ad57e480d23f40946f3cdf01e89b
Add Strict-Transport-Security header and http->https redirect
nikmd23/signatory,nikmd23/signatory
source/Signatory/Global.asax.cs
source/Signatory/Global.asax.cs
using System; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Signatory.Extensions; using Signatory.Framework; namespace Signatory { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : HttpApplication { protected void Application_Start() { ValueProviderFactories.Factories.Add(new CookieValueProviderFactory()); MvcHandler.DisableMvcResponseHeader = true; AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } public override string GetVaryByCustomString(HttpContext context, string arg) { switch (arg) { case "IsRepoCollaborator": var collabs = context.GetCollaborators(); if (collabs == null) return false.ToString(); var result = collabs.Any(c => c.Equals(User.Identity.Name, StringComparison.InvariantCultureIgnoreCase)).ToString(); return result; default: return base.GetVaryByCustomString(context, arg); } } protected void Application_PreSendRequestHeaders(object sender, EventArgs e) { var httpRuntime = sender as HttpApplication; if (httpRuntime != null) httpRuntime.Context.Response.Headers.Remove("Server"); } protected void Application_BeginRequest(Object sender, EventArgs e) { switch (Request.Url.Scheme) { case "https": Response.AddHeader("Strict-Transport-Security", "max-age=3600"); // one hour break; case "http": var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery; Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", path); break; } } } }
using System; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Signatory.Extensions; using Signatory.Framework; namespace Signatory { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : HttpApplication { protected void Application_Start() { ValueProviderFactories.Factories.Add(new CookieValueProviderFactory()); MvcHandler.DisableMvcResponseHeader = true; AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } public override string GetVaryByCustomString(HttpContext context, string arg) { switch (arg) { case "IsRepoCollaborator": var collabs = context.GetCollaborators(); if (collabs == null) return false.ToString(); var result = collabs.Any(c => c.Equals(User.Identity.Name, StringComparison.InvariantCultureIgnoreCase)).ToString(); return result; default: return base.GetVaryByCustomString(context, arg); } } protected void Application_PreSendRequestHeaders(object sender, EventArgs e) { var httpRuntime = sender as HttpApplication; if (httpRuntime != null) httpRuntime.Context.Response.Headers.Remove("Server"); } } }
apache-2.0
C#
23adb1e371cf86b0446a7da24e82b536bb0e4252
test for factories
andremarcondesteixeira/currency
test/AndreMarcondesTeixeira/CurrencyTest.cs
test/AndreMarcondesTeixeira/CurrencyTest.cs
using System; using Xunit; namespace AndreMarcondesTeixeira { public class CurrencyTest { [Fact] public void Currency_Is_A_Value_Type_And_All_Factory_Methods_Return_New_Instances() { Assert.False(Object.ReferenceEquals(Currency.XXX, Currency.XXX)); Assert.False(Object.ReferenceEquals(Currency.GetByLetterCode("XXX"), Currency.GetByLetterCode("XXX"))); Assert.False(Object.ReferenceEquals(Currency.GetByNumericCode("999"), Currency.GetByNumericCode("999"))); } [Fact] public void Currency_Instances_Can_Be_Created_By_Four_Ways() { Assert.IsType(typeof(Currency), Currency.XXX); Assert.IsType(typeof(Currency), new Currency("ZZZ", "000", 0, "Test")); Assert.IsType(typeof(Currency), Currency.GetByLetterCode("XXX")); Assert.IsType(typeof(Currency), Currency.GetByNumericCode("999")); } [Fact] public void Currency_Instances_Are_Compared_Through_Their_Properties() { var customCurrency = new Currency("ZZ", "000", 2, "Test"); var differentLetterCode = new Currency("ZZZ", "000", 2, "Test"); var differentNumberCode = new Currency("ZZ", "00", 2, "Test"); var differentMinorUnits = new Currency("ZZ", "000", 1, "Test"); var differentName = new Currency("ZZ", "000", 2, "Different Name"); var equivalentCurrency = new Currency("ZZ", "000", 2, "Test"); Assert.True(customCurrency != differentLetterCode); Assert.True(customCurrency != differentNumberCode); Assert.True(customCurrency != differentMinorUnits); Assert.True(customCurrency != differentName); Assert.True(customCurrency == equivalentCurrency); Assert.False(customCurrency != equivalentCurrency); Assert.False(Currency.XXX == Currency.XTS); Assert.True(Currency.XTS != Currency.XXX); } } }
using System; using Xunit; namespace AndreMarcondesTeixeira { public class CurrencyTest { [Fact] public void Currency_Is_A_Value_Type_And_All_Factory_Methods_Return_New_Instances() { Assert.False(Object.ReferenceEquals(Currency.XXX, Currency.XXX)); //Assert.False(Object.ReferenceEquals(Currency.GetByLetterCode("XXX"), Currency.GetByLetterCode("XXX"))); //Assert.False(Object.ReferenceEquals(Currency.GetByNumericCode("999"), Currency.GetByNumericCode("999"))); } [Fact] public void Currency_Instances_Can_Be_Created_By_Four_Ways() { Assert.IsType(typeof(Currency), Currency.XXX); Assert.IsType(typeof(Currency), new Currency("ZZZ", "000", 0, "Test")); //Assert.IsType(typeof(Currency), Currency.GetByLetterCode("XXX")); //Assert.IsType(typeof(Currency), Currency.GetByNumericCode("999")); } [Fact] public void Currency_Instances_Are_Compared_Through_Their_Properties() { var customCurrency = new Currency("ZZ", "000", 2, "Test"); var differentLetterCode = new Currency("ZZZ", "000", 2, "Test"); var differentNumberCode = new Currency("ZZ", "00", 2, "Test"); var differentMinorUnits = new Currency("ZZ", "000", 1, "Test"); var differentName = new Currency("ZZ", "000", 2, "Different Name"); var equivalentCurrency = new Currency("ZZ", "000", 2, "Test"); Assert.True(customCurrency != differentLetterCode); Assert.True(customCurrency != differentNumberCode); Assert.True(customCurrency != differentMinorUnits); Assert.True(customCurrency != differentName); Assert.True(customCurrency == equivalentCurrency); Assert.False(customCurrency != equivalentCurrency); Assert.False(Currency.XXX == Currency.XTS); Assert.True(Currency.XTS != Currency.XXX); } } }
mit
C#
1b9472392c567378db28e6da51acbd9fe7c8cdd8
Fix assets app position when a warning is visible. (#3173)
xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2
src/OrchardCore.Modules/OrchardCore.Media/Views/Admin/Index.cshtml
src/OrchardCore.Modules/OrchardCore.Media/Views/Admin/Index.cshtml
<script asp-src="~/OrchardCore.Media/Scripts/media.js" asp-name="media" at="Foot" depends-on="admin, vuejs, sortable, vuedraggable"></script> <style asp-src="~/OrchardCore.Media/Styles/media.min.css" debug-src="~/OrchardCore.Media/Styles/media.css"></style> <script asp-src="https://vuejs.org/js/vue.min.js" debug-src="https://vuejs.org/js/vue.js" asp-name="vuejs" at="Foot"></script> <script asp-src="https://cdn.jsdelivr.net/sortable/1.4.2/Sortable.min.js" debug-src="https://cdn.jsdelivr.net/sortable/1.4.2/Sortable.js" asp-name="sortable" at="Foot"></script> <script asp-src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.14.1/vuedraggable.min.js" debug-src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.14.1/vuedraggable.js" asp-name="vuedraggable" depends-on="vuejs, sortable" at="Foot"></script> <script at="Foot"> initializeMediaApplication(true, '@Url.Action("MediaApplication", "Admin", new { area = "OrchardCore.Media" })'); @* mediaApp is absolutely positioned. When a warning is shown we need to move it down to avoid overlapping. *@ $(function () { if (!$('.message').length) { return; }; var mediaAppInitialTop = 0; var mediaAppLoaded = false; var repositionMediaApp = function () { var messagesHeight = 0; $('.message').each(function () { messagesHeight += $(this).outerHeight(true); }); var newTop = mediaAppInitialTop + messagesHeight; $('#mediaApp').css('top', newTop + 'px'); } $(window).on('resize', function () { if (mediaAppLoaded) { repositionMediaApp(); } }); // before moving we need to wait until the vuejs mediaapp is loaded. var checkMediaAppIsLoaded = setInterval(function () { if ($('#mediaApp').length) { mediaAppInitialTop = $('#mediaApp').offset().top; clearInterval(checkMediaAppIsLoaded); mediaAppLoaded = true; repositionMediaApp(); } }, 100); }); </script> <h1>@RenderTitleSegments(T["Assets"])</h1>
<script asp-src="~/OrchardCore.Media/Scripts/media.js" asp-name="media" at="Foot" depends-on="admin, vuejs, sortable, vuedraggable"></script> <style asp-src="~/OrchardCore.Media/Styles/media.min.css" debug-src="~/OrchardCore.Media/Styles/media.css"></style> <script asp-src="https://vuejs.org/js/vue.min.js" debug-src="https://vuejs.org/js/vue.js" asp-name="vuejs" at="Foot"></script> <script asp-src="https://cdn.jsdelivr.net/sortable/1.4.2/Sortable.min.js" debug-src="https://cdn.jsdelivr.net/sortable/1.4.2/Sortable.js" asp-name="sortable" at="Foot"></script> <script asp-src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.14.1/vuedraggable.min.js" debug-src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.14.1/vuedraggable.js" asp-name="vuedraggable" depends-on="vuejs, sortable" at="Foot"></script> <script at="Foot"> initializeMediaApplication(true, '@Url.Action("MediaApplication", "Admin", new { area = "OrchardCore.Media" })'); </script> <h1>@RenderTitleSegments(T["Assets"])</h1>
bsd-3-clause
C#
034d9a69facfca101da5f321af290055be8d81cf
Fix a typo in Rehearsal model
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Models/Rehearsal.cs
src/CGO.Web/Models/Rehearsal.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CGO.Web.Models { public class Rehearsal { public Rehearsal(int id, DateTime dateAndStartTime, DateTime finishTime, string location) { Location = location; FinishTime = finishTime; DateAndStartTime = dateAndStartTime; Id = id; } public int Id { get; private set; } public DateTime DateAndStartTime { get; private set; } public DateTime FinishTime { get; private set; } public string Location { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CGO.Web.Models { public class Rehearsal { public Rehearsal(int id, DateTime dateAndStartTime, DateTime finishTime, string loction) { Loction = loction; FinishTime = finishTime; DateAndStartTime = dateAndStartTime; Id = id; } public int Id { get; private set; } public DateTime DateAndStartTime { get; private set; } public DateTime FinishTime { get; private set; } public string Loction { get; private set; } } }
mit
C#
3f57809136ba75c13b5535f7a07afd942059c586
Change menu
rippo/React.Tests,rippo/React.Tests,rippo/React.Tests
Mvc/Views/Shared/_Layout.cshtml
Mvc/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ReactJs Tests</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("ReactJs Tests", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Event Sub/pub", "Index", "Event")</li> <li>@Html.ActionLink("Flux McFly", "Index", "Flux")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ReactJs Tests</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("ReactJs Tests", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
mit
C#
43219182bbc403cc5a51dd9236eeb982db867663
Add debug logging and injection of "Accept-Charset" header that is required when running on Mono
os2indberetning/os2indberetning,os2indberetning/os2indberetning,os2indberetning/os2indberetning,os2indberetning/os2indberetning
Presentation.Web/Global.asax.cs
Presentation.Web/Global.asax.cs
using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Http.ExceptionHandling; using System.Web.Http.Controllers; using System.Net.Http.Headers; using System.Diagnostics; using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute; namespace OS2Indberetning { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); #if DEBUG GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new DebugExceptionLogger()); GlobalConfiguration.Configuration.Filters.Add(new AddAcceptCharsetHeaderActionFilter()); #endif //// Turns off self reference looping when serializing models in API controlllers //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //// Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } #if DEBUG public class AddAcceptCharsetHeaderActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { // Inject "Accept-Charset" header into the client request, // since apparently this is required when running on Mono // See: https://github.com/OData/odata.net/issues/165 actionContext.Request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("UTF-8")); base.OnActionExecuting(actionContext); } } public class DebugExceptionLogger : ExceptionLogger { public override void Log(ExceptionLoggerContext context) { Debug.WriteLine(context.Exception); } } #endif }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace OS2Indberetning { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //// Turns off self reference looping when serializing models in API controlllers //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //// Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } }
mpl-2.0
C#
7e65d8bc1fcf6d95964cdd4f11caab708885dd31
Fix commit 93b3d6a7f4332a0a56a01f8edb0379b4e95a93a5
StockSharp/StockSharp
Messages/BaseRequestMessage.cs
Messages/BaseRequestMessage.cs
namespace StockSharp.Messages { using System; using System.Runtime.Serialization; /// <summary> /// Base implementation of <see cref="ISubscriptionMessage"/> interface with non-online mode. /// </summary> [DataContract] [Serializable] public abstract class BaseRequestMessage : BaseSubscriptionMessage { /// <summary> /// Initializes a new instance of the <see cref="BaseRequestMessage"/>. /// </summary> /// <param name="type">Message type.</param> public BaseRequestMessage(MessageTypes type) : base(type) { } /// <inheritdoc /> [DataMember] public override DateTimeOffset? From => null; /// <inheritdoc /> [DataMember] public override DateTimeOffset? To => DateTimeOffset.MaxValue /* prevent for online mode */; /// <inheritdoc /> [DataMember] public override bool IsSubscribe => true; /// <inheritdoc /> [DataMember] public override long OriginalTransactionId => 0; } }
namespace StockSharp.Messages { using System; using System.Runtime.Serialization; /// <summary> /// Base implementation of <see cref="ISubscriptionMessage"/> interface with non-online mode. /// </summary> public abstract class BaseRequestMessage : BaseSubscriptionMessage { /// <summary> /// Initializes a new instance of the <see cref="BaseRequestMessage"/>. /// </summary> /// <param name="type">Message type.</param> public BaseRequestMessage(MessageTypes type) : base(type) { } /// <inheritdoc /> [DataMember] public override DateTimeOffset? From => null; /// <inheritdoc /> [DataMember] public override DateTimeOffset? To => DateTimeOffset.MaxValue /* prevent for online mode */; /// <inheritdoc /> [DataMember] public override bool IsSubscribe => true; /// <inheritdoc /> [DataMember] public override long OriginalTransactionId => 0; } }
apache-2.0
C#
52faec34ce41388a74c85e009e46ad35705f3657
Add --preserve-commands option to trim command.
Prof9/TextPet
TextPet/Commands/TrimCommand.cs
TextPet/Commands/TrimCommand.cs
using LibTextPet.General; using LibTextPet.Msg; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TextPet.Commands { internal class TrimCommand : CliCommand { public override string Name => "trim"; public override string RunString => "Trimming scripts..."; private const string maxArg = "max"; private const string amountArg = "amount"; private const string preserveTextArg = "preserve-text"; private const string preserveCommandsArg = "preserve-commands"; public TrimCommand(CommandLineInterface cli, TextPetCore core) : base(cli, core, new string[0], new OptionalArgument[] { new OptionalArgument(maxArg, 'm', new string[] { amountArg, }), new OptionalArgument(preserveTextArg, 't'), new OptionalArgument(preserveCommandsArg, 'c'), }) { } protected override void RunImplementation() { string maxStr = GetOptionalValues(maxArg)?[0]; int max = maxStr != null ? NumberParser.ParseInt32(maxStr) : int.MaxValue; bool preserveText = GetOptionalValues(preserveTextArg) != null; bool preserveCommands = GetOptionalValues(preserveCommandsArg) != null; // Cycle through every script in every text archive. foreach (TextArchive ta in this.Core.TextArchives) { foreach (Script script in ta) { // Find the first script-ending command. int endPos = 0; for (int i = 0; i < script.Count; i++) { if (script[i].EndsScript) { endPos = i; break; } } // Remove elements from the end of the script until the script-ending element or maximum is reached. int trimmed = 0; while (script.Count > endPos && (maxStr == null || trimmed < max)) { // If the preverse text option is enabled, cancel if this would trim non-whitespace text. if (preserveText) { TextElement textElem = script[script.Count - 1] as TextElement; if (textElem != null && !textElem.Text.All(c => Char.IsWhiteSpace(c))) { break; } } // If the preserve commands option is enabled, cancel if this would trim commands. if (preserveCommands) { Command cmdElem = script[script.Count - 1] as Command; if (cmdElem != null) { break; } } script.RemoveAt(script.Count - 1); trimmed++; } } } } } }
using LibTextPet.General; using LibTextPet.Msg; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TextPet.Commands { internal class TrimCommand : CliCommand { public override string Name => "trim"; public override string RunString => "Trimming scripts..."; private const string maxArg = "max"; private const string amountArg = "amount"; private const string preserveTextArg = "preserve-text"; public TrimCommand(CommandLineInterface cli, TextPetCore core) : base(cli, core, new string[0], new OptionalArgument[] { new OptionalArgument(maxArg, 'm', new string[] { amountArg, }), new OptionalArgument(preserveTextArg, 'p'), }) { } protected override void RunImplementation() { string maxStr = GetOptionalValues(maxArg)?[0]; int max = maxStr != null ? NumberParser.ParseInt32(maxStr) : int.MaxValue; bool preserveText = GetOptionalValues(preserveTextArg) != null; // Cycle through every script in every text archive. foreach (TextArchive ta in this.Core.TextArchives) { foreach (Script script in ta) { // Find the first script-ending command. int endPos = 0; for (int i = 0; i < script.Count; i++) { if (script[i].EndsScript) { endPos = i; break; } } // Remove commands from the end of the script until the script-ending command or maximum is reached. int trimmed = 0; while (script.Count > endPos && (maxStr == null || trimmed < max)) { // If the preverse text option is enabled, cancel if this would trim non-whitespace text. if (preserveText) { TextElement textElem = script[script.Count - 1] as TextElement; if (textElem != null && !textElem.Text.All(c => Char.IsWhiteSpace(c))) { break; } } script.RemoveAt(script.Count - 1); trimmed++; } } } } } }
mit
C#
14cd00d0fd6404ad5f922bab2f22b76062c8787b
Add optional timestamp to IAirlock
vostok/core
Vostok.Core/Airlock/IAirlock.cs
Vostok.Core/Airlock/IAirlock.cs
using System; namespace Vostok.Airlock { public interface IAirlock { void Push<T>(string routingKey, T item, DateTimeOffset timestamp = default(DateTimeOffset)); } }
namespace Vostok.Airlock { public interface IAirlock { void Push<T>(string routingKey, T item); } }
mit
C#
fd7dc96d63d52caac121fdf1c689477bd124983b
Remove unneeded Initialize method
AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud
src/server/Adaptive.ReactiveTrader.Server.ReferenceDataWrite/ReferenceDataWriteServiceHostFactory.cs
src/server/Adaptive.ReactiveTrader.Server.ReferenceDataWrite/ReferenceDataWriteServiceHostFactory.cs
using Adaptive.ReactiveTrader.Common; using Adaptive.ReactiveTrader.EventStore.Domain; using Adaptive.ReactiveTrader.Messaging; using Adaptive.ReactiveTrader.Server.Core; using Common.Logging; using EventStore.ClientAPI; using System; using System.Reactive.Disposables; namespace Adaptive.ReactiveTrader.Server.ReferenceDataWrite { public class ReferenceDataWriteServiceHostFactory : IServiceHostFactoryWithEventStore, IDisposable { protected static readonly ILog Log = LogManager.GetLogger<ReferenceDataWriteServiceHostFactory>(); private readonly SerialDisposable _cleanup = new SerialDisposable(); public IDisposable Initialize(IObservable<IConnected<IBroker>> broker) { return Disposable.Empty; } public IDisposable Initialize(IObservable<IConnected<IBroker>> brokerStream, IObservable<IConnected<IEventStoreConnection>> eventStoreStream) { var repositoryStream = eventStoreStream.LaunchOrKill(conn => new Repository(conn)); var serviceStream = repositoryStream.LaunchOrKill(engine => new ReferenceWriteService(engine)); _cleanup.Disposable = serviceStream.LaunchOrKill(brokerStream, (service, broker) => new ReferenceWriteServiceHost(service, broker)).Subscribe(); return _cleanup; } public void Dispose() { _cleanup.Dispose(); } } }
using Adaptive.ReactiveTrader.Common; using Adaptive.ReactiveTrader.EventStore.Connection; using Adaptive.ReactiveTrader.EventStore.Domain; using Adaptive.ReactiveTrader.Messaging; using Adaptive.ReactiveTrader.Server.Core; using Common.Logging; using EventStore.ClientAPI; using System; using System.Reactive.Disposables; namespace Adaptive.ReactiveTrader.Server.ReferenceDataWrite { public class ReferenceDataWriteServiceHostFactory : IServiceHostFactoryWithEventStore, IDisposable { protected static readonly ILog Log = LogManager.GetLogger<ReferenceDataWriteServiceHostFactory>(); private readonly SerialDisposable _cleanup = new SerialDisposable(); private Repository _repository; private ReferenceWriteService _service; public void Initialize(IEventStoreConnection es, IConnectionStatusMonitor monitor) { _repository = new Repository(es); _service = new ReferenceWriteService(_repository); } public IDisposable Initialize(IObservable<IConnected<IBroker>> broker) { return Disposable.Empty; } public IDisposable Initialize(IObservable<IConnected<IBroker>> brokerStream, IObservable<IConnected<IEventStoreConnection>> eventStoreStream) { var repositoryStream = eventStoreStream.LaunchOrKill(conn => new Repository(conn)); var serviceStream = repositoryStream.LaunchOrKill(engine => new ReferenceWriteService(engine)); _cleanup.Disposable = serviceStream.LaunchOrKill(brokerStream, (service, broker) => new ReferenceWriteServiceHost(service, broker)).Subscribe(); return _cleanup; } public void Dispose() { _cleanup.Dispose(); } } }
apache-2.0
C#
29c2e3328f396ff53a12a0cc828d8a337826d8ba
Update ArrayEntity.cs
dimmpixeye/Unity3dTools
Runtime/LibMisc/ArrayEntity.cs
Runtime/LibMisc/ArrayEntity.cs
// Project : ecs // Contacts : Pix - ask@pixeye.games using System; using Unity.IL2CPP.CompilerServices; namespace Pixeye.Framework { [Serializable] public struct ArrayEntity { public int length; public ent[] source; public ref ent this[int index] { get => ref source[index]; } public ArrayEntity(int size) { source = new ent[size]; length = 0; } public void Add(in ent entity) { if (length>=source.Length) Array.Resize(ref source, length << 1); source[length++] = entity; } public void Remove(in ent entity) { for (int i = 0; i < length; i++) { ref var val = ref source[i]; if (entity.EqualsAndExist(val)) { Array.Copy(source, i + 1, source, i, --length - i); break; } } } public bool Removed(in ent entity) { for (int i = 0; i < length; i++) { ref var val = ref source[i]; if (entity.EqualsAndExist(val)) { Array.Copy(source, i + 1, source, i, --length - i); return true; } } return false; } } }
// Project : ecs // Contacts : Pix - ask@pixeye.games using System; using Unity.IL2CPP.CompilerServices; namespace Pixeye.Framework { [Serializable] public struct ArrayEntity { public int length; public ent[] source; public ref ent this[int index] { get => ref source[index]; } public ArrayEntity(int size) { source = new ent[size]; length = 0; } public void Add(in ent entity) { source[length++] = entity; } public void Remove(in ent entity) { for (int i = 0; i < length; i++) { ref var val = ref source[i]; if (entity.EqualsAndExist(val)) { Array.Copy(source, i + 1, source, i, --length - i); break; } } } public bool Removed(in ent entity) { for (int i = 0; i < length; i++) { ref var val = ref source[i]; if (entity.EqualsAndExist(val)) { Array.Copy(source, i + 1, source, i, --length - i); return true; } } return false; } } }
mit
C#
4590bfd468adcff263a13f00bf9feede190c3288
Remove instantiations of extended option in recommendations module.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Modules/TraktRecommendationsModule.cs
Source/Lib/TraktApiSharp/Modules/TraktRecommendationsModule.cs
namespace TraktApiSharp.Modules { using Extensions; using Objects.Basic; using Objects.Get.Movies; using Objects.Get.Shows; using Requests; using Requests.Params; using Requests.WithOAuth.Recommendations; using System; using System.Threading.Tasks; public class TraktRecommendationsModule : TraktBaseModule { internal TraktRecommendationsModule(TraktClient client) : base(client) { } public async Task<TraktPaginationListResult<TraktMovie>> GetMovieRecommendationsAsync(int? limit = null, TraktExtendedOption extended = null) { return await QueryAsync(new TraktUserMovieRecommendationsRequest(Client) { PaginationOptions = new TraktPaginationOptions(null, limit), ExtendedOption = extended }); } public async Task HideMovieRecommendationAsync(string movieId) { Validate(movieId); await QueryAsync(new TraktUserRecommendationHideMovieRequest(Client) { Id = movieId }); } public async Task<TraktPaginationListResult<TraktShow>> GetShowRecommendationsAsync(int? limit = null, TraktExtendedOption extended = null) { return await QueryAsync(new TraktUserShowRecommendationsRequest(Client) { PaginationOptions = new TraktPaginationOptions(null, limit), ExtendedOption = extended }); } public async Task HideShowRecommendationAsync(string showId) { Validate(showId); await QueryAsync(new TraktUserRecommendationHideShowRequest(Client) { Id = showId }); } private void Validate(string id) { if (string.IsNullOrEmpty(id) || id.ContainsSpace()) throw new ArgumentException("id not valid", nameof(id)); } } }
namespace TraktApiSharp.Modules { using Extensions; using Objects.Basic; using Objects.Get.Movies; using Objects.Get.Shows; using Requests; using Requests.Params; using Requests.WithOAuth.Recommendations; using System; using System.Threading.Tasks; public class TraktRecommendationsModule : TraktBaseModule { internal TraktRecommendationsModule(TraktClient client) : base(client) { } public async Task<TraktPaginationListResult<TraktMovie>> GetMovieRecommendationsAsync(int? limit = null, TraktExtendedOption extended = null) { return await QueryAsync(new TraktUserMovieRecommendationsRequest(Client) { PaginationOptions = new TraktPaginationOptions(null, limit), ExtendedOption = extended != null ? extended : new TraktExtendedOption() }); } public async Task HideMovieRecommendationAsync(string movieId) { Validate(movieId); await QueryAsync(new TraktUserRecommendationHideMovieRequest(Client) { Id = movieId }); } public async Task<TraktPaginationListResult<TraktShow>> GetShowRecommendationsAsync(int? limit = null, TraktExtendedOption extended = null) { return await QueryAsync(new TraktUserShowRecommendationsRequest(Client) { PaginationOptions = new TraktPaginationOptions(null, limit), ExtendedOption = extended != null ? extended : new TraktExtendedOption() }); } public async Task HideShowRecommendationAsync(string showId) { Validate(showId); await QueryAsync(new TraktUserRecommendationHideShowRequest(Client) { Id = showId }); } private void Validate(string id) { if (string.IsNullOrEmpty(id) || id.ContainsSpace()) throw new ArgumentException("id not valid", nameof(id)); } } }
mit
C#
35c0f96e8960b95b460f6e38ab858109b9d47230
Initialize ApplicationCommand with an ApplicationConfiguration
appharbor/appharbor-cli
src/AppHarbor/Commands/ApplicationCommand.cs
src/AppHarbor/Commands/ApplicationCommand.cs
namespace AppHarbor.Commands { public abstract class ApplicationCommand : Command { private readonly IApplicationConfiguration _applicationConfiguration; public ApplicationCommand(IApplicationConfiguration applicationConfiguration) { _applicationConfiguration = applicationConfiguration; } } }
namespace AppHarbor.Commands { public abstract class ApplicationCommand : Command { } }
mit
C#
0f11cfe97478a6d85e806def528efd4f982dab42
Add xmldoc describing `SynchronizationContext` behaviour
peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Threading/GameThreadSynchronizationContext.cs
osu.Framework/Threading/GameThreadSynchronizationContext.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.Diagnostics; using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuations to an isolated scheduler instance. /// </summary> /// <remarks> /// This implementation roughly follows the expectations set out for winforms/WPF as per /// https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/february/msdn-magazine-parallel-computing-it-s-all-about-the-synchronizationcontext. /// - Calls to <see cref="Post"/> are guaranteed to run asynchronously. /// - Calls to <see cref="Send"/> will run inline when they can. /// - Order of execution is guaranteed (in our case, it is guaranteed over <see cref="Send"/> and <see cref="Post"/> calls alike). /// - To enforce the above, calling <see cref="Send"/> will flush any pending work until the newly queued item has been completed. /// </remarks> internal class GameThreadSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public int TotalTasksRun => scheduler.TotalTasksRun; public GameThreadSynchronizationContext(GameThread gameThread) { scheduler = new GameThreadScheduler(gameThread); } public override void Send(SendOrPostCallback callback, object? state) { var scheduledDelegate = scheduler.Add(() => callback(state)); Debug.Assert(scheduledDelegate != null); while (scheduledDelegate.State == ScheduledDelegate.RunState.Waiting) { if (scheduler.IsMainThread) scheduler.Update(); else Thread.Sleep(1); } } public override void Post(SendOrPostCallback callback, object? state) => scheduler.Add(() => callback(state)); public void RunWork() => scheduler.Update(); } }
// 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.Diagnostics; using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuations to a scheduler instance. /// </summary> internal class GameThreadSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public int TotalTasksRun => scheduler.TotalTasksRun; public GameThreadSynchronizationContext(GameThread gameThread) { scheduler = new GameThreadScheduler(gameThread); } public override void Send(SendOrPostCallback d, object? state) { var del = scheduler.Add(() => d(state)); Debug.Assert(del != null); while (del.State == ScheduledDelegate.RunState.Waiting) { if (scheduler.IsMainThread) scheduler.Update(); else Thread.Sleep(1); } } public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state)); public void RunWork() => scheduler.Update(); } }
mit
C#
8f4bccb6e69d0fce47ece0b7cb9afb452ba2e9f0
Update LocalRepository.cs
Pierry/finan-api,Pierry/finan-api
Finan/Finan.Repository/Repositories/LocalRepository.cs
Finan/Finan.Repository/Repositories/LocalRepository.cs
using System; using System.Collections.Generic; using System.Linq; using Finan.Domain.Contracts.Repositories; using Finan.Domain.Entities; namespace Finan.Repository.Repositories { public class LocalRepository : ILocalRepository { private readonly IList<Local> _mock; public LocalRepository() { _mock = new List<Local>(); _mock.Add(new Local(1, "Market", 1)); _mock.Add(new Local(2, "Gas Station", 1)); _mock.Add(new Local(3, "Car", 1)); _mock.Add(new Local(4, "Home", 1)); _mock.Add(new Local(5, "Market", 2)); _mock.Add(new Local(6, "Meal", 2)); _mock.Add(new Local(7, "Gas", 2)); _mock.Add(new Local(8, "Coffee", 2)); _mock.Add(new Local(9, "Market", 3)); _mock.Add(new Local(10, "Hobby", 3)); } public IList<Local> Get() { return _mock.ToList(); } public Local GetById(int id) { return _mock.FirstOrDefault(c => c.LocalId == id); } public Local Create(Local item) { item.LocalId = _mock.Max(c => c.LocalId) + 1; _mock.Add(item); return item; } public void Update(Local item) { throw new NotImplementedException(); } public void Delete(Local item) { _mock.Remove(item); } public void Dispose() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using Finan.Domain.Contracts.Repositories; using Finan.Domain.Entities; namespace Finan.Repository.Repositories { public class LocalRepository : ILocalRepository { private readonly IList<Local> _mock; public LocalRepository() { _mock = new List<Local>(); _mock.Add(new Local(1, "Market", 1)); _mock.Add(new Local(2, "Gas Station", 1)); _mock.Add(new Local(3, "Car", 1)); _mock.Add(new Local(4, "Home", 1)); _mock.Add(new Local(5, "Market", 2)); _mock.Add(new Local(6, "Meat", 2)); _mock.Add(new Local(7, "Gas", 2)); _mock.Add(new Local(8, "Coffee", 2)); _mock.Add(new Local(9, "Market", 3)); _mock.Add(new Local(10, "Hobby", 3)); } public IList<Local> Get() { return _mock.ToList(); } public Local GetById(int id) { return _mock.FirstOrDefault(c => c.LocalId == id); } public Local Create(Local item) { item.LocalId = _mock.Max(c => c.LocalId) + 1; _mock.Add(item); return item; } public void Update(Local item) { throw new NotImplementedException(); } public void Delete(Local item) { _mock.Remove(item); } public void Dispose() { throw new NotImplementedException(); } } }
apache-2.0
C#
8ecaaa7864a0164b3475fb271f6b2cd842ce939b
Update calc code content
mathieumack/epsi_samples
csharp/b2/Calculatrice/Program.cs
csharp/b2/Calculatrice/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculatrice { class Program { static void Main(string[] args) { double value1 = 0; double value2 = 0; string line1 = ""; string line2 = ""; string line3 = ""; bool tf = true; while (tf) { line1 = Console.ReadLine(); // Traitement pour gérer la saisie sur une ligne : if (line1.Contains("+")) { string[] line = line1.Split('+'); line1 = line[0]; line2 = "+"; line3 = line[1]; } // TODO : Ajouter ici le traitement pour les autres opérations : // Lancement des calculs : try { value1 = double.Parse(line1); value2 = double.Parse(line3); if (line2 != "+" && line2 != "-") throw new InvalidOperationException(); tf = false; } catch (Exception ex) { Console.WriteLine("Données invalides"); } } if (line2 == "+") { Addition add = new Addition(); double result = add.DoOperation(value1, value2); Console.WriteLine(result); } else if (line2 == "-") { Soustraction sous = new Soustraction(); double result = sous.DoOperation(value1, value2); Console.WriteLine(result); } Console.ReadLine(); } } public class Addition { public double DoOperation(double a, double b) { return a + b; } } public class Soustraction { public double DoOperation(double a, double b) { return a - b; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculatrice { class Program { static void Main(string[] args) { string line1 = Console.ReadLine(); string line2 = Console.ReadLine(); string line3 = Console.ReadLine(); int value1 = int.Parse(line1); int value2 = int.Parse(line3); if (line2 == "+") { Addition add = new Addition(); double result = add.DoOperation(value1, value2); Console.WriteLine(result); } else if (line2 == "-") { Soustraction sous = new Soustraction(); double result = sous.DoOperation(value1, value2); Console.WriteLine(result); } Console.ReadLine(); } } public class Addition { public double DoOperation(double a, double b) { return a + b; } } public class Soustraction { public double DoOperation(double a, double b) { return a - b; } } public class Multiplication { public double DoOperation(double a, double b) { return a * b; } } public class Division { public double DoOperation(double a, double b) { return a / b; } } }
mit
C#
2633174886ffda924af3023445e6ef1dc7b8cd90
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.22.2")] [assembly: AssemblyInformationalVersion("0.22.2")] /* * Version 0.22.2 * * - [FIX] Fixed that custom display name and timeout cannot be declared on * FirstClassTestAttribute. */
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.22.1")] [assembly: AssemblyInformationalVersion("0.22.1")] /* * Version 0.22.2 * * - [FIX] Fixed that custom display name and timeout cannot be declared on * FirstClassTestAttribute. */
mit
C#
ba8c9a8720b1f00c59c0096a79716d4863388959
Bump to v1.5.0
danielwertheim/requester
buildconfig.cake
buildconfig.cake
public class BuildConfig { private const string Version = "1.5.0"; private const bool IsPreRelease = false; public readonly string SrcDir = "./src/"; public readonly string OutDir = "./build/"; public string Target { get; private set; } public string SemVer { get; private set; } public string BuildVersion { get; private set; } public string BuildProfile { get; private set; } public bool IsTeamCityBuild { get; private set; } public static BuildConfig Create( ICakeContext context, BuildSystem buildSystem) { if (context == null) throw new ArgumentNullException("context"); var target = context.Argument("target", "Default"); var buildRevision = context.Argument("buildrevision", "0"); return new BuildConfig { Target = target, SemVer = Version + (IsPreRelease ? "-b" + buildRevision : string.Empty), BuildVersion = Version + "." + buildRevision, BuildProfile = context.Argument("configuration", "Release"), IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity }; } }
public class BuildConfig { private const string Version = "1.4.0"; private const bool IsPreRelease = false; public readonly string SrcDir = "./src/"; public readonly string OutDir = "./build/"; public string Target { get; private set; } public string SemVer { get; private set; } public string BuildVersion { get; private set; } public string BuildProfile { get; private set; } public bool IsTeamCityBuild { get; private set; } public static BuildConfig Create( ICakeContext context, BuildSystem buildSystem) { if (context == null) throw new ArgumentNullException("context"); var target = context.Argument("target", "Default"); var buildRevision = context.Argument("buildrevision", "0"); return new BuildConfig { Target = target, SemVer = Version + (IsPreRelease ? "-b" + buildRevision : string.Empty), BuildVersion = Version + "." + buildRevision, BuildProfile = context.Argument("configuration", "Release"), IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity }; } }
mit
C#
a3be8615742b84a73a7080b38c6f391e01b92ab8
Update TextDrawNode.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Modules/Renderer/SkiaSharp/Nodes/TextDrawNode.cs
src/Core2D/Modules/Renderer/SkiaSharp/Nodes/TextDrawNode.cs
#nullable enable using Core2D.Model.Renderer; using Core2D.Model.Renderer.Nodes; using Core2D.ViewModels.Shapes; using Core2D.ViewModels.Style; using SkiaSharp; using Core2D.Spatial; namespace Core2D.Modules.Renderer.SkiaSharp.Nodes; internal class TextDrawNode : DrawNode, ITextDrawNode { public TextShapeViewModel Text { get; set; } public SKRect Rect { get; set; } public SKPoint Origin { get; set; } public SKTypeface? Typeface { get; set; } public SKPaint? FormattedText { get; set; } public string? BoundText { get; set; } public TextDrawNode(TextShapeViewModel text, ShapeStyleViewModel? style) { Style = style; Text = text; UpdateGeometry(); } public sealed override void UpdateGeometry() { ScaleThickness = Text.State.HasFlag(ShapeStateFlags.Thickness); ScaleSize = Text.State.HasFlag(ShapeStateFlags.Size); if (Text.TopLeft is { } && Text.BottomRight is { }) { var rect2 = Rect2.FromPoints(Text.TopLeft.X, Text.TopLeft.Y, Text.BottomRight.X, Text.BottomRight.Y, 0, 0); Rect = SKRect.Create((float)rect2.X, (float)rect2.Y, (float)rect2.Width, (float)rect2.Height); Center = new SKPoint(Rect.MidX, Rect.MidY); } UpdateTextGeometry(); } private void UpdateTextGeometry() { BoundText = Text.GetProperty(nameof(TextShapeViewModel.Text)) is string boundText ? boundText : Text.Text; if (BoundText is null) { return; } if (Style.TextStyle.FontSize < 0.0) { return; } FormattedText = SkiaSharpDrawUtil.GetSKPaint(BoundText, Style, Text.TopLeft, Text.BottomRight, out var origin); Origin = origin; } public override void OnDraw(object? dc, double zoom) { if (dc is not SKCanvas canvas) { return; } if (FormattedText is { }) { canvas.DrawText(BoundText, Origin.X, Origin.Y, FormattedText); } } }
#nullable enable using Core2D.Model.Renderer; using Core2D.Model.Renderer.Nodes; using Core2D.ViewModels.Shapes; using Core2D.ViewModels.Style; using SkiaSharp; using Core2D.Spatial; namespace Core2D.Modules.Renderer.SkiaSharp.Nodes; internal class TextDrawNode : DrawNode, ITextDrawNode { public TextShapeViewModel Text { get; set; } public SKRect Rect { get; set; } public SKPoint Origin { get; set; } public SKTypeface? Typeface { get; set; } public SKPaint? FormattedText { get; set; } public string? BoundText { get; set; } public TextDrawNode(TextShapeViewModel text, ShapeStyleViewModel? style) { Style = style; Text = text; UpdateGeometry(); } public sealed override void UpdateGeometry() { ScaleThickness = Text.State.HasFlag(ShapeStateFlags.Thickness); ScaleSize = Text.State.HasFlag(ShapeStateFlags.Size); var rect2 = Rect2.FromPoints(Text.TopLeft.X, Text.TopLeft.Y, Text.BottomRight.X, Text.BottomRight.Y, 0, 0); Rect = SKRect.Create((float)rect2.X, (float)rect2.Y, (float)rect2.Width, (float)rect2.Height); Center = new SKPoint(Rect.MidX, Rect.MidY); UpdateTextGeometry(); } private void UpdateTextGeometry() { BoundText = Text.GetProperty(nameof(TextShapeViewModel.Text)) is string boundText ? boundText : Text.Text; if (BoundText is null) { return; } if (Style.TextStyle.FontSize < 0.0) { return; } FormattedText = SkiaSharpDrawUtil.GetSKPaint(BoundText, Style, Text.TopLeft, Text.BottomRight, out var origin); Origin = origin; } public override void OnDraw(object? dc, double zoom) { if (dc is not SKCanvas canvas) { return; } if (FormattedText is { }) { canvas.DrawText(BoundText, Origin.X, Origin.Y, FormattedText); } } }
mit
C#
3d09ee5a80107f7cc3406a67fcb17a6385cb943c
Add test
sakapon/Bellona.Analysis
Bellona/UnitTest/Core/DeviationModelTest.cs
Bellona/UnitTest/Core/DeviationModelTest.cs
using System; using System.Linq; using Bellona.Core; using Bellona.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest.Core { [TestClass] public class DeviationModelTest { [TestMethod] public void Test_0() { var model = DeviationModel.Create(Enumerable.Empty<SamplePoint>(), d => d.Point); Assert.AreEqual(false, model.HasRecords); Assert.AreEqual(null, model.Mean); Assert.AreEqual(double.NaN, model.StandardDeviation); } [TestMethod] public void Test_1() { var sample = new SamplePoint { Id = 1, Point = new[] { 2.0, 3.0 } }; var model = DeviationModel.Create(sample.ToEnumerable(), d => d.Point); Assert.AreEqual(true, model.HasRecords); Assert.AreEqual(sample.Point, model.Mean); Assert.AreEqual(0.0, model.StandardDeviation); Assert.AreEqual(0.0, model.Records[0].Deviation); Assert.AreEqual(0.0, model.Records[0].StandardScore); } [TestMethod] public void Test_2() { var data = new[] { new SamplePoint { Id = 1, Point = new[] { 2.0, 3.0 } }, new SamplePoint { Id = 2, Point = new[] { 8.0, 11.0 } }, }; var model = DeviationModel.Create(data, d => d.Point); Assert.AreEqual(new[] { 5.0, 7.0 }, model.Mean); Assert.AreEqual(5.0, model.StandardDeviation); Assert.AreEqual(5.0, model.Records[0].Deviation); Assert.AreEqual(1.0, model.Records[0].StandardScore); Assert.AreEqual(5.0, model.Records[1].Deviation); Assert.AreEqual(1.0, model.Records[1].StandardScore); } [TestMethod] public void Test_140() { var model = DeviationModel.Create(TestData.GetColors(), c => new double[] { c.R, c.G, c.B }); model.Records .OrderBy(r => r.StandardScore) .Execute(r => Console.WriteLine("{0:F3}, {1}, {2}", r.StandardScore, r.Features, r.Element.Name)); } } }
using System; using System.Linq; using Bellona.Core; using Bellona.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest.Core { [TestClass] public class DeviationModelTest { [TestMethod] public void Test_1() { var data = new[] { new SamplePoint { Id = 1, Point = new[] { 2.0, 3.0 } }, new SamplePoint { Id = 2, Point = new[] { 8.0, 11.0 } }, }; var model = DeviationModel.Create(data, d => d.Point); Assert.AreEqual(new[] { 5.0, 7.0 }, model.Mean); Assert.AreEqual(5.0, model.StandardDeviation); Assert.AreEqual(1.0, model.Records[0].StandardScore); Assert.AreEqual(1.0, model.Records[1].StandardScore); } [TestMethod] public void Test_2() { var model = DeviationModel.Create(TestData.GetColors(), c => new double[] { c.R, c.G, c.B }); model.Records .OrderBy(r => r.StandardScore) .Execute(r => Console.WriteLine("{0:F3}: {1}, {2}", r.StandardScore, r.Element.Name, r.Features)); } } }
mit
C#
629ccbaed553117ce203e3dc15beadc9b5da4ff8
Fix for #41
coryrwest/B2.NET
src/Http/RequestGenerators/FileDownloadRequestGenerators.cs
src/Http/RequestGenerators/FileDownloadRequestGenerators.cs
using B2Net.Models; using Newtonsoft.Json; using System; using System.Net.Http; namespace B2Net.Http { public static class FileDownloadRequestGenerators { private static class Endpoints { public const string DownloadById = "b2_download_file_by_id"; public const string GetDownloadAuthorization = "b2_get_download_authorization"; public const string DownloadByName = "file"; } public static HttpRequestMessage DownloadById(B2Options options, string fileId, string byteRange = "") { var uri = new Uri(options.DownloadUrl + "/b2api/" + Constants.Version + "/" + Endpoints.DownloadById); var json = JsonConvert.SerializeObject(new { fileId }); var request = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = uri, Content = new StringContent(json) }; request.Headers.TryAddWithoutValidation("Authorization", options.AuthorizationToken); // Add byte range header if we have it if (!string.IsNullOrEmpty(byteRange)) { request.Headers.Add("Range", $"bytes={byteRange}"); } return request; } public static HttpRequestMessage DownloadByName(B2Options options, string bucketName, string fileName, string byteRange = "") { var uri = new Uri(options.DownloadUrl + "/" + Endpoints.DownloadByName + "/" + bucketName + "/" + fileName.b2UrlEncode()); var request = new HttpRequestMessage() { Method = HttpMethod.Get, RequestUri = uri }; request.Headers.TryAddWithoutValidation("Authorization", options.AuthorizationToken); // Add byte range header if we have it if (!string.IsNullOrEmpty(byteRange)) { request.Headers.Add("Range", $"bytes={byteRange}"); } return request; } public static HttpRequestMessage GetDownloadAuthorization(B2Options options, string fileNamePrefix, int validDurationInSeconds, string bucketId, string b2ContentDisposition = "") { var uri = new Uri(options.ApiUrl + "/b2api/" + Constants.Version + "/" + Endpoints.GetDownloadAuthorization); var body = "{\"bucketId\":" + JsonConvert.ToString(bucketId) + ", \"fileNamePrefix\":" + JsonConvert.ToString(fileNamePrefix) + ", \"validDurationInSeconds\":" + JsonConvert.ToString(validDurationInSeconds); if (!string.IsNullOrEmpty(b2ContentDisposition)) { body += ", \"b2ContentDisposition\":" + JsonConvert.ToString(b2ContentDisposition); } body += "}"; var request = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = uri, Content = new StringContent(body) }; request.Headers.TryAddWithoutValidation("Authorization", options.AuthorizationToken); return request; } } }
using B2Net.Models; using Newtonsoft.Json; using System; using System.Net.Http; namespace B2Net.Http { public static class FileDownloadRequestGenerators { private static class Endpoints { public const string DownloadById = "b2_download_file_by_id"; public const string GetDownloadAuthorization = "b2_get_download_authorization"; public const string DownloadByName = "file"; } public static HttpRequestMessage DownloadById(B2Options options, string fileId, string byteRange = "") { var uri = new Uri(options.DownloadUrl + "/b2api/" + Constants.Version + "/" + Endpoints.DownloadById); var json = JsonConvert.SerializeObject(new { fileId }); var request = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = uri, Content = new StringContent(json) }; request.Headers.TryAddWithoutValidation("Authorization", options.AuthorizationToken); // Add byte range header if we have it if (!string.IsNullOrEmpty(byteRange)) { request.Headers.Add("Range", $"bytes={byteRange}"); } return request; } public static HttpRequestMessage DownloadByName(B2Options options, string bucketName, string fileName, string byteRange = "") { var uri = new Uri(options.DownloadUrl + "/" + Endpoints.DownloadByName + "/" + bucketName + "/" + fileName.b2UrlEncode()); var request = new HttpRequestMessage() { Method = HttpMethod.Get, RequestUri = uri }; request.Headers.TryAddWithoutValidation("Authorization", options.AuthorizationToken); // Add byte range header if we have it if (!string.IsNullOrEmpty(byteRange)) { request.Headers.Add("Range", $"bytes={byteRange}"); } return request; } public static HttpRequestMessage GetDownloadAuthorization(B2Options options, string fileNamePrefix, int validDurationInSeconds, string bucketId, string b2ContentDisposition = "") { var uri = new Uri(options.ApiUrl + "/b2api/" + Constants.Version + "/" + Endpoints.GetDownloadAuthorization); var body = "{\"bucketId\":" + JsonConvert.ToString(bucketId) + ", \"fileNamePrefix\":" + JsonConvert.ToString(fileNamePrefix) + ", \"validDurationInSeconds\":" + JsonConvert.ToString(validDurationInSeconds); if (!string.IsNullOrEmpty(b2ContentDisposition)) { body += ", \"maxFileCount\":" + JsonConvert.ToString(b2ContentDisposition); } body += "}"; var request = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = uri, Content = new StringContent(body) }; request.Headers.TryAddWithoutValidation("Authorization", options.AuthorizationToken); return request; } } }
mit
C#
bd9d2048f2acd5efa7650d90b3ce73f2acd23076
Reduce logging clutter
siwater/Cloudworks,siwater/Cloudworks,siwater/Cloudworks
Citrix.Cloudworks.Agent/NetworkUtilities.cs
Citrix.Cloudworks.Agent/NetworkUtilities.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Xml.Linq; using System.Xml.XPath; using Citrix.Diagnostics; namespace Citrix.Cloudworks.Agent { public static class NetworkUtilities { /// <summary> /// Simple "GET" on the specified Url returing the contents as a string. If an error occurs /// it is logged and the method returns null /// </summary> /// <param name="url"></param> /// <returns></returns> public static string HttpGet(string url) { CtxTrace.TraceVerbose("url={0}", url); try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8)) { return streamReader.ReadToEnd(); } } } } catch (Exception e) { CtxTrace.TraceError(e); return null; } } /// <summary> /// Get a list of all the DHCP servers configured for this machine. An empty list indicates no /// DHCP servers found /// </summary> /// <returns></returns> public static List<IPAddress> GetDhcpServers() { List<IPAddress> result = new List<IPAddress>(); foreach (NetworkInterface i in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = i.GetIPProperties(); IPAddressCollection dhcpServers = properties.DhcpServerAddresses; if (dhcpServers != null) { result.AddRange(dhcpServers); } } return result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Xml.Linq; using System.Xml.XPath; using Citrix.Diagnostics; namespace Citrix.Cloudworks.Agent { public static class NetworkUtilities { /// <summary> /// Simple "GET" on the specified Url returing the contents as a string. If an error occurs /// it is logged and the method returns null /// </summary> /// <param name="url"></param> /// <returns></returns> public static string HttpGet(string url) { CtxTrace.TraceInformation("url={0}", url); try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8)) { return streamReader.ReadToEnd(); } } } } catch (Exception e) { CtxTrace.TraceError(e); return null; } } /// <summary> /// Get a list of all the DHCP servers configured for this machine. An empty list indicates no /// DHCP servers found /// </summary> /// <returns></returns> public static List<IPAddress> GetDhcpServers() { List<IPAddress> result = new List<IPAddress>(); foreach (NetworkInterface i in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = i.GetIPProperties(); IPAddressCollection dhcpServers = properties.DhcpServerAddresses; if (dhcpServers != null) { result.AddRange(dhcpServers); } } return result; } } }
mit
C#
1e313333b03d1a1fa7f09d071ead15d4c89358f9
Update ConsoleLogStrategy.cs
skahal/Skahal.Infrastructure.Framework
src/Skahal.Infrastructure.Framework/Logging/ConsoleLogStrategy.cs
src/Skahal.Infrastructure.Framework/Logging/ConsoleLogStrategy.cs
using System; namespace Skahal.Infrastructure.Framework.Logging { /// <summary> /// A log strategy that send the messages to default system console. /// </summary> public class ConsoleLogStrategy : LogStrategyBase { #region implemented abstract members of LogStrategyBase /// <summary> /// Writes the debug log level message. /// </summary> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> public override void WriteDebug (string message, params object[] args) { Console.ResetColor (); Console.WriteLine (message, args); OnDebugWritten (new LogWrittenEventArgs(message, args)); } /// <summary> /// Writes the warning log level message. /// </summary> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> public override void WriteWarning (string message, params object[] args) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine (message, args); Console.ResetColor (); OnWarningWritten (new LogWrittenEventArgs(message, args)); } /// <summary> /// Writes the error log level message. /// </summary> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> public override void WriteError (string message, params object[] args) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine (message, args); Console.ResetColor (); OnErrorWritten (new LogWrittenEventArgs(message, args)); } #endregion } }
using System; using Skahal.Infrastructure.Framework.Logging; namespace Skahal.Infrastructure.Framework { /// <summary> /// A log strategy that send the messages to default system console. /// </summary> public class ConsoleLogStrategy : LogStrategyBase { #region implemented abstract members of LogStrategyBase /// <summary> /// Writes the debug log level message. /// </summary> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> public override void WriteDebug (string message, params object[] args) { Console.ResetColor (); Console.WriteLine (message, args); OnDebugWritten (new LogWrittenEventArgs(message, args)); } /// <summary> /// Writes the warning log level message. /// </summary> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> public override void WriteWarning (string message, params object[] args) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine (message, args); Console.ResetColor (); OnWarningWritten (new LogWrittenEventArgs(message, args)); } /// <summary> /// Writes the error log level message. /// </summary> /// <param name="message">Message.</param> /// <param name="args">Arguments.</param> public override void WriteError (string message, params object[] args) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine (message, args); Console.ResetColor (); OnErrorWritten (new LogWrittenEventArgs(message, args)); } #endregion } }
mit
C#
2d68eef0961bb35dd8f57d2d464799f866993481
add Save/LoadContents
CyEy/CyberEyes
CyberEyes/CyberEyes/ScavengerHuntManager.cs
CyberEyes/CyberEyes/ScavengerHuntManager.cs
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Xml.Serialization; using System.Reflection; using Xamarin.Forms; namespace CyberEyes { public class ScavengerHuntManager : ViewModelBase { const string FILENAME = "file.xml"; FileHelper fileHelper = new FileHelper(); // handles FileIO per platform ScavengerHuntList itemList = new ScavengerHuntList(); public ScavengerHuntList ItemList { get { return itemList; } set { SetProperty(ref itemList, value); } } public ScavengerHuntManager() { } public void LoadContents() { this.itemList = new ScavengerHuntList(); // gather XML from local storage if (fileHelper.Exists(FILENAME)) { string contents = fileHelper.ReadText(FILENAME); // Deserialize TextReader tr = new StringReader(contents); XmlSerializer xml = new XmlSerializer(typeof(ScavengerHuntList)); this.itemList = xml.Deserialize(tr) as ScavengerHuntList; } } public void SaveContents() { // Serialize TextWriter tw = new StringWriter(); XmlSerializer xml = new XmlSerializer(typeof(ScavengerHuntList)); xml.Serialize(tw, itemList); string contents = tw.ToString(); fileHelper.WriteText(FILENAME, contents); } } }
using System; namespace CyberEyes { public class ScavengerHuntManager : ViewModelBase { public ScavengerHuntManager() { } } }
bsd-3-clause
C#
c0736dfb6e34c5ee513d3f2baa2daafacc1d8a6e
Fix minor typos
damiensawyer/cassette,andrewdavey/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,honestegg/cassette,honestegg/cassette,honestegg/cassette,damiensawyer/cassette,damiensawyer/cassette,BluewireTechnologies/cassette,andrewdavey/cassette
src/Website/Views/Documentation/Tutorials_TwitterBootstrap.cshtml
src/Website/Views/Documentation/Tutorials_TwitterBootstrap.cshtml
@{ ViewBag.Title = "Cassette | Twitter Bootstrap"; ViewBag.Description = "How to use Twitter Bootstrap with Cassette."; } <h1>Twitter Bootstrap</h1> <p> Cassette won't be able to compile the LESS files provided with <a href="http://twitter.github.com/bootstrap/" target="_blank" title="Twitter Bootstrap Project Page">Twitter Bootstrap</a> by default. This is because <code>bootstrap.less</code> uses a set of <span class="code-type">&#64;import</span> statements to build up the final LESS file; where Cassette will attempt to compile each file in the directory. </p> <p> In this tutorial we will assume that you have set up your project structure as follows: </p> <pre>Content/ - Styles/ - accordion.less - ... - bootstrap.less - ...</pre> <h2>Option 1: Using a bundle.txt File</h2> <p> You can inform Cassette that you only want to compile a certain set of files by adding a <a href="@Url.DocumentationUrl("configuration/bundle-descriptor-file")" title="Bundle Descriptor File"><code>bundle.txt</code> file</a> into the <code>Styles</code> folder, and include exactly one line in the file: </p> <pre>bootstrap.less</pre> <p>You will also need to enter in any custom LESS files (on separate lines) that do not appear in main <code>bootstrap.less</code> file.</p> <h2>Option 2: Using Configuration</h2> <p> You can also use the <code>CassetteConfiguration.cs</code> class to inform Cassette that it should not compile all the files in the directory. Simply add a new line to <code>Configure</code> method as such: </p> <pre><code><span class="keyword">public</span> <span class="keyword">class</span> <span class="code-type">CassetteConfiguration</span> : <span class="code-type">ICassetteConfiguration</span> { <span class="keyword">public</span> <span class="keyword">void</span> Configure(<span class="code-type">BundleCollection</span> bundles, <span class="code-type">CassetteSettings</span> settings) { <span class="comment">// Ensure that Cassette doesn't compile all the</span> <span class="comment">// .less files in ~/Content/Styles.</span> bundles.Add&lt;<span class="code-type">StylesheetBundle</span>&gt;(<span class="string">"Content/Styles/bootstrap.less"</span>); } }</code></pre> <p> This piece of code will also need to be maintained so that it stays in sync with any additional LESS files you have, that do not appear in the <code>bootstrap.less</code> file. </p> <h2>Concerns</h2> <p> Due to the fact that the Twitter Bootstrap LESS files cannot stand alone make sure that you do not <code>Reference</code> any Twitter Bootstrap LESS files in your views or pages apart from <code>bootstrap.less.</code> </p>
@{ ViewBag.Title = "Cassette | Twitter Bootstrap"; ViewBag.Description = "How to use Twitter Bootstrap with Cassette."; } <h1>Twitter Bootstrap</h1> <p> Cassette won't be able to compile the LESS files provided with <a href="http://twitter.github.com/bootstrap/" target="_blank" title="Twitter Bootstrap Project Page">Twitter Bootstrap</a> by default. This is because <code>bootstrap.less</code> uses a set of <span class="code-type">&#64;import</span> statements to build up the final LESS file; where Cassette will attempt to compile each file in the directory. </p> <p> In this tutorial we will assume that you have set up your project structure as follows: </p> <pre>Content/ - Styles/ - accordion.less - ... - bootstrap.less - ... </pre> <h1>Using a bundle.txt File</h1> <p> You can inform Cassette that you only want to compile a certain set of files by adding a <a href="@Url.DocumentationUrl("configuration/bundle-descriptor-file")" title="Bundle Descriptor File"><code>bundle.txt</code> file</a> into the <code>Styles</code> folder, and include exactly one line in the file: </p> <pre>bootstrap.less</pre> <p>You will also need to enter in any custom LESS files (on separate lines) that do no appear in main <code>bootstrap.less</code> file.</p> <h1>Using Configuration</h1> <p> You can also use the <code>CassetteConfiguration.cs</code> class to inform Cassette that it should not compile all the files in the directory. Simply add a new line to <code>Configure</code> method as such: </p> <pre><code><span class="keyword">public</span> <span class="keyword">class</span> <span class="code-type">CassetteConfiguration</span> : <span class="code-type">ICassetteConfiguration</span> { <span class="keyword">public</span> <span class="keyword">void</span> Configure(<span class="code-type">BundleCollection</span> bundles, <span class="code-type">CassetteSettings</span> settings) { <span class="comment">// Ensure that Cassette doesn't compile all the</span> <span class="comment">// .less files in ~/Content/Styles.</span> bundles.Add&lt;<span class="code-type">StylesheetBundle</span>&gt;(<span class="string">"Content/Styles/bootstrap.less"</span>); } }</code></pre> <p> This piece of code will also need to be maintained so that it stays in sync with any additional LESS files you have, that do not appear in the <code>bootstrap.less</code> file. </p> <h1>Concerns</h1> <p> Due to the fact that the Twitter Bootstrap LESS files cannot stand alone make sure that you do not <code>Reference</code> any Twitter Bootstrap LESS files in your views or pages apart from <code>bootstrap.less.</code> </p>
mit
C#
ef7c1b0acb80b1b4ee183f13fb932894db7a4c6d
Fix argument cannot be null message when uninstalling unknown package.
mrward/monodevelop-nuget-extensions,mrward/monodevelop-nuget-extensions
src/MonoDevelop.PackageManagement.Cmdlets/MonoDevelop.PackageManagement.Cmdlets/UninstallPackageCmdlet.cs
src/MonoDevelop.PackageManagement.Cmdlets/MonoDevelop.PackageManagement.Cmdlets/UninstallPackageCmdlet.cs
// // UninstallPackageCmdlet.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2011-2014 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Management.Automation; using ICSharpCode.PackageManagement.Scripting; using MonoDevelop.PackageManagement; using NuGet; namespace ICSharpCode.PackageManagement.Cmdlets { [Cmdlet (VerbsLifecycle.Uninstall, "Package", DefaultParameterSetName = ParameterAttribute.AllParameterSets)] public class UninstallPackageCmdlet : PackageManagementCmdlet { public UninstallPackageCmdlet () : this ( PackageManagementExtendedServices.ConsoleHost, null) { } public UninstallPackageCmdlet ( IPackageManagementConsoleHost consoleHost, ICmdletTerminatingError terminatingError) : base (consoleHost, terminatingError) { } [Parameter (Position = 0, Mandatory = true)] public string Id { get; set; } [Parameter (Position = 1)] public string ProjectName { get; set; } [Parameter (Position = 2)] public SemanticVersion Version { get; set; } [Parameter] public SwitchParameter Force { get; set; } [Parameter] public SwitchParameter RemoveDependencies { get; set; } protected override void ProcessRecord () { ThrowErrorIfProjectNotOpen (); using (IDisposable monitor = CreateEventsMonitor ()) { UninstallPackage (); } } void UninstallPackage () { ExtendedPackageManagementProject project = GetProject (); UninstallPackageAction2 action = CreateUninstallPackageAction (project); ExecuteWithScriptRunner (project, () => { action.Execute (); }); } ExtendedPackageManagementProject GetProject () { string source = null; return (ExtendedPackageManagementProject)ConsoleHost.GetProject (source, ProjectName); } UninstallPackageAction2 CreateUninstallPackageAction (ExtendedPackageManagementProject project) { UninstallPackageAction2 action = project.CreateUninstallPackageAction (); action.PackageId = Id; action.PackageVersion = Version; action.ForceRemove = Force.IsPresent; action.RemoveDependencies = RemoveDependencies.IsPresent; // action.PackageScriptRunner = this; return action; } } }
// // UninstallPackageCmdlet.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2011-2014 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Management.Automation; using ICSharpCode.PackageManagement.Scripting; using MonoDevelop.PackageManagement; using NuGet; namespace ICSharpCode.PackageManagement.Cmdlets { [Cmdlet (VerbsLifecycle.Uninstall, "Package", DefaultParameterSetName = ParameterAttribute.AllParameterSets)] public class UninstallPackageCmdlet : PackageManagementCmdlet { public UninstallPackageCmdlet () : this ( PackageManagementExtendedServices.ConsoleHost, null) { } public UninstallPackageCmdlet ( IPackageManagementConsoleHost consoleHost, ICmdletTerminatingError terminatingError) : base (consoleHost, terminatingError) { } [Parameter (Position = 0, Mandatory = true)] public string Id { get; set; } [Parameter (Position = 1)] public string ProjectName { get; set; } [Parameter (Position = 2)] public SemanticVersion Version { get; set; } [Parameter] public SwitchParameter Force { get; set; } [Parameter] public SwitchParameter RemoveDependencies { get; set; } protected override void ProcessRecord () { ThrowErrorIfProjectNotOpen (); using (IDisposable monitor = CreateEventsMonitor ()) { UninstallPackage (); } } void UninstallPackage () { ExtendedPackageManagementProject project = GetProject (); UninstallPackageAction2 action = CreateUninstallPackageAction (project); ExecuteWithScriptRunner (project, () => { action.Execute (); }); } ExtendedPackageManagementProject GetProject () { string source = null; return (ExtendedPackageManagementProject)ConsoleHost.GetProject (source, ProjectName); } UninstallPackageAction2 CreateUninstallPackageAction (ExtendedPackageManagementProject project) { UninstallPackageAction2 action = project.CreateUninstallPackageAction (); action.Package = project.ProjectManager.LocalRepository.FindPackage (Id, Version); action.ForceRemove = Force.IsPresent; action.RemoveDependencies = RemoveDependencies.IsPresent; // action.PackageScriptRunner = this; return action; } } }
mit
C#
029da35be96d8235428dc5d585534e002a8f49d7
Fix a null reference error using cgminer as a backend
nwoolls/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner
MultiMiner.Xgminer.Api/DeviceInformation.cs
MultiMiner.Xgminer.Api/DeviceInformation.cs
using System; namespace MultiMiner.Xgminer.Api { public class DeviceInformation { public DeviceInformation() { Status = String.Empty; Name = String.Empty; //cgminer may / does not return this } public string Kind { get; set; } public string Name { get; set; } public int Index { get; set; } public bool Enabled { get; set; } public string Status { get; set; } public double Temperature { get; set; } public int FanSpeed { get; set; } public int FanPercent { get; set; } public int GpuClock { get; set; } public int MemoryClock { get; set; } public double GpuVoltage { get; set; } public int GpuActivity { get; set; } public int PowerTune { get; set; } public double AverageHashrate { get; set; } public double CurrentHashrate { get; set; } public int AcceptedShares { get; set; } public int RejectedShares { get; set; } public int HardwareErrors { get; set; } public double Utility { get; set; } public string Intensity { get; set; } //string, might be D public int PoolIndex { get; set; } } }
using System; namespace MultiMiner.Xgminer.Api { public class DeviceInformation { public DeviceInformation() { Status = String.Empty; } public string Kind { get; set; } public string Name { get; set; } public int Index { get; set; } public bool Enabled { get; set; } public string Status { get; set; } public double Temperature { get; set; } public int FanSpeed { get; set; } public int FanPercent { get; set; } public int GpuClock { get; set; } public int MemoryClock { get; set; } public double GpuVoltage { get; set; } public int GpuActivity { get; set; } public int PowerTune { get; set; } public double AverageHashrate { get; set; } public double CurrentHashrate { get; set; } public int AcceptedShares { get; set; } public int RejectedShares { get; set; } public int HardwareErrors { get; set; } public double Utility { get; set; } public string Intensity { get; set; } //string, might be D public int PoolIndex { get; set; } } }
mit
C#
71f8ce5e32425e89300c1c46a541edf6df8bd6a1
update to support android app and xsrf
AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us
mikeandwan.us/Controllers/AccountApiController.cs
mikeandwan.us/Controllers/AccountApiController.cs
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Maw.Domain.Identity; using MawMvcApp.Filters; using MawMvcApp.ViewModels.Account; using SignInRes = Microsoft.AspNetCore.Identity.SignInResult; namespace MawMvcApp.Controllers { [Route("api/account")] public class AccountApiController : MawBaseController<AccountApiController> { const byte LOGIN_AREA_API = 2; readonly ILoginService _loginService; public AccountApiController(IAuthorizationService authorizationService, ILogger<AccountApiController> log, ILoginService loginService) : base(authorizationService, log) { if(loginService == null) { throw new ArgumentNullException(nameof(loginService)); } _loginService = loginService; } [HttpPost("login")] public async Task<bool> Login(LoginModel model) { var result = await _loginService.AuthenticateAsync(model.Username, model.Password, LOGIN_AREA_API); return result == SignInRes.Success; } [HttpGet("get-xsrf-token")] [TypeFilter(typeof(ApiAntiforgeryActionFilter))] public ActionResult GetXsrfToken() { return Ok(); } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Maw.Domain.Identity; using MawMvcApp.ViewModels.Account; using SignInRes = Microsoft.AspNetCore.Identity.SignInResult; namespace MawMvcApp.Controllers { [Route("api/account")] public class AccountApiController : MawBaseController<AccountApiController> { const byte LOGIN_AREA_API = 2; readonly ILoginService _loginService; public AccountApiController(IAuthorizationService authorizationService, ILogger<AccountApiController> log, ILoginService loginService) : base(authorizationService, log) { if(loginService == null) { throw new ArgumentNullException(nameof(loginService)); } _loginService = loginService; } [HttpPost("login")] public async Task<bool> Login(LoginModel model) { var result = await _loginService.AuthenticateAsync(model.Username, model.Password, LOGIN_AREA_API); return result == SignInRes.Success; } } }
mit
C#
b7167522d3ceea9c8086d56595e0f4fd33d3cc75
Refactor for readability
mstrother/BmpListener
BmpListener/Bgp/PathAttributeMPUnreachNLRI.cs
BmpListener/Bgp/PathAttributeMPUnreachNLRI.cs
using System; using System.Collections.Generic; using System.Linq; namespace BmpListener.Bgp { public class PathAttributeMPUnreachNLRI : PathAttribute { public PathAttributeMPUnreachNLRI(ArraySegment<byte> data) : base(ref data) { DecodeFromBytes(data); } public AddressFamily AFI { get; private set; } public SubsequentAddressFamily SAFI { get; private set; } public IPAddrPrefix[] Value { get; private set; } public void DecodeFromBytes(ArraySegment<byte> data) { var ipAddrPrefixes = new List<IPAddrPrefix>(); AFI = (AddressFamily) data.ToUInt16(0); SAFI = (SubsequentAddressFamily) data.ElementAt(2); for (var i = 3; i < data.Count;) { int length = data.ElementAt(i); if (length == 0) return; length = (length + 7) / 8; length++; var offset = data.Offset + i; var prefixSegment = new ArraySegment<byte>(data.Array, offset, length); var ipAddrPrefix = new IPAddrPrefix(prefixSegment, AFI); ipAddrPrefixes.Add(ipAddrPrefix); i += prefixSegment.Count; } Value = ipAddrPrefixes.ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace BmpListener.Bgp { public class PathAttributeMPUnreachNLRI : PathAttribute { public PathAttributeMPUnreachNLRI(ArraySegment<byte> data) : base(ref data) { DecodeFromBytes(data); } public Bgp.AddressFamily AFI { get; private set; } public Bgp.SubsequentAddressFamily SAFI { get; private set; } public IPAddrPrefix[] Value { get; private set; } public void DecodeFromBytes(ArraySegment<byte> data) { var ipAddrPrefixes = new List<IPAddrPrefix>(); AFI = (AddressFamily)data.ToUInt16(0); SAFI = (SubsequentAddressFamily)data.ElementAt(2); for (var i = 3; i < data.Count;) { int length = data.ElementAt(i); if (length == 0) return; length = (length + 7) / 8; length++; var offset = data.Offset + i; var prefixSegment = new ArraySegment<byte>(data.Array, offset, length); var ipAddrPrefix = new IPAddrPrefix(prefixSegment, AFI); ipAddrPrefixes.Add(ipAddrPrefix); i += prefixSegment.Count; } Value = ipAddrPrefixes.ToArray(); } } }
mit
C#
179656788dd87caae95c35c3e8e4b0372106bcbd
Remove unnecessary method
NeoAdonis/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,peppy/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,UselessToucan/osu
osu.Game/Screens/Edit/Compose/Components/MoveSelectionEvent.cs
osu.Game/Screens/Edit/Compose/Components/MoveSelectionEvent.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Edit; using osuTK; namespace osu.Game.Screens.Edit.Compose.Components { /// <summary> /// An event which occurs when a <see cref="SelectionBlueprint"/> is moved. /// </summary> public class MoveSelectionEvent { /// <summary> /// The <see cref="SelectionBlueprint"/> that triggered this <see cref="MoveSelectionEvent"/>. /// </summary> public readonly SelectionBlueprint Blueprint; /// <summary> /// The starting screen-space position of the hitobject. /// </summary> public readonly Vector2 ScreenSpaceStartPosition; /// <summary> /// The expected screen-space position of the hitobject at the current cursor position. /// </summary> public readonly Vector2 ScreenSpacePosition; /// <summary> /// The distance between <see cref="ScreenSpacePosition"/> and the hitobject's current position, in the coordinate-space of the hitobject's parent. /// </summary> /// <remarks> /// This does not use <see cref="ScreenSpaceStartPosition"/> and does not represent the cumulative movement distance. /// </remarks> public readonly Vector2 InstantDelta; public MoveSelectionEvent(SelectionBlueprint blueprint, Vector2 screenSpaceStartPosition, Vector2 screenSpacePosition) { Blueprint = blueprint; ScreenSpaceStartPosition = screenSpaceStartPosition; ScreenSpacePosition = screenSpacePosition; InstantDelta = Blueprint.HitObject.Parent.ToLocalSpace(ScreenSpacePosition) - Blueprint.HitObject.Position; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Edit; using osuTK; namespace osu.Game.Screens.Edit.Compose.Components { /// <summary> /// An event which occurs when a <see cref="SelectionBlueprint"/> is moved. /// </summary> public class MoveSelectionEvent { /// <summary> /// The <see cref="SelectionBlueprint"/> that triggered this <see cref="MoveSelectionEvent"/>. /// </summary> public readonly SelectionBlueprint Blueprint; /// <summary> /// The starting screen-space position of the hitobject. /// </summary> public readonly Vector2 ScreenSpaceStartPosition; /// <summary> /// The expected screen-space position of the hitobject at the current cursor position. /// </summary> public readonly Vector2 ScreenSpacePosition; /// <summary> /// The distance between <see cref="ScreenSpacePosition"/> and the hitobject's current position, in the coordinate-space of the hitobject's parent. /// </summary> /// <remarks> /// This does not use <see cref="ScreenSpaceStartPosition"/> and does not represent the cumulative movement distance. /// </remarks> public readonly Vector2 InstantDelta; public MoveSelectionEvent(SelectionBlueprint blueprint, Vector2 screenSpaceStartPosition, Vector2 screenSpacePosition) { Blueprint = blueprint; ScreenSpaceStartPosition = screenSpaceStartPosition; ScreenSpacePosition = screenSpacePosition; InstantDelta = toLocalSpace(ScreenSpacePosition) - Blueprint.HitObject.Position; } /// <summary> /// Converts a screen-space position into the coordinate space of the hitobject's parents. /// </summary> /// <param name="screenSpacePosition">The screen-space position.</param> /// <returns>The position in the coordinate space of the hitobject's parent.</returns> private Vector2 toLocalSpace(Vector2 screenSpacePosition) => Blueprint.HitObject.Parent.ToLocalSpace(screenSpacePosition); } }
mit
C#
a771d9ba2dfeef0e9183f6b3fe57371ef65ec7a6
update tile value on creation
evan-erdos/Sudoku-Reimagined,evan-erdos/Sudoku-Reimagined
Assets/Scripts/IconSelector.cs
Assets/Scripts/IconSelector.cs
using UnityEngine; using UnityEngine.UI; using System.Collections; public class IconSelector : MonoBehaviour { public GameObject[] tiles; static GameObject[] globalTiles; public static Tiles Current {get;set;} public void Awake() { IconSelector.globalTiles = tiles; } public void SetTileDefault() { SetTile(Tiles.Default); } public void SetTileRaise() { SetTile(Tiles.Raise); } public void SetTileLower() { SetTile(Tiles.Lower); } public void SetTileLevel() { SetTile(Tiles.Level); } public void SetTileSpout() { SetTile(Tiles.Spout); } public void SetTile(Tiles tile) { Current = tile; } public static GameObject CreateTile(Tiles tile) { var space = Object.Instantiate(globalTiles[(int) tile]) as GameObject; space.GetComponent<ISpace<Tiles>>().Value = tile; return space; } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class IconSelector : MonoBehaviour { public GameObject[] tiles; static GameObject[] globalTiles; public static Tiles Current {get;set;} public void Awake() { IconSelector.globalTiles = tiles; } public void SetTileDefault() { SetTile(Tiles.Default); } public void SetTileRaise() { SetTile(Tiles.Raise); } public void SetTileLower() { SetTile(Tiles.Lower); } public void SetTileLevel() { SetTile(Tiles.Level); } public void SetTileSpout() { SetTile(Tiles.Spout); } public void SetTile(Tiles tile) { Current = tile; } public static GameObject CreateTile(Tiles tile) { return (Object.Instantiate(globalTiles[(int) tile]) as GameObject); } }
mit
C#
36d0ef9f4731069eed4d86ade4bbfae6e83cb1ca
Test auto deploy
rippo/testing.casperjs.presentation.vscode.50mins,rippo/testing.casperjs.presentation.vscode.50mins,rippo/testing.casperjs.presentation.vscode.50mins,rippo/testing.casperjs.presentation.vscode.50mins
Casper.Mvc/Casper.Mvc/Views/Home/Index.cshtml
Casper.Mvc/Casper.Mvc/Views/Home/Index.cshtml
@{ViewBag.Title = "Home";} <div class="jumbotron"> <h1>CasperJS Testing By Richard Wilde</h1> <p>CasperJS is a navigation scripting & testing utility for PhantomJS written in Javascript</p> <p><a target="_blank" href="http://casperjs.org/" class="btn btn-primary btn-lg" role="button">Learn more</a></p> </div> <div class="row"> <div class="col-xs-1 imgbg"> <img src="~/Content/casperjs-logo.png" style="width: 100%;" /> </div> <div class="col-xs-5"> In case you haven’t seen CasperJS yet, go and take a look, it’s an extremely useful companion to PhantomJS. <a href="http://ariya.ofilabs.com/2012/03/phantomjs-and-travis-ci.html" target="_blank">Ariya Hidayat</a>, creator of Phantomjs </div> <div class="col-xs-1 imgbg"> <img src="~/Content/phantomjs-logo.png" style="width: 100%;" /> </div> <div class="col-xs-5"> <a href="http://phantomjs.org/" target="_blank">PhantomJS</a> is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. </div> </div>
@{ViewBag.Title = "Home";} <div class="jumbotron"> <h1>CasperJS Testing</h1> <p>CasperJS is a navigation scripting & testing utility for PhantomJS written in Javascript</p> <p><a target="_blank" href="http://casperjs.org/" class="btn btn-primary btn-lg" role="button">Learn more</a></p> </div> <div class="row"> <div class="col-xs-1 imgbg"> <img src="~/Content/casperjs-logo.png" style="width: 100%;" /> </div> <div class="col-xs-5"> In case you haven’t seen CasperJS yet, go and take a look, it’s an extremely useful companion to PhantomJS. <a href="http://ariya.ofilabs.com/2012/03/phantomjs-and-travis-ci.html" target="_blank">Ariya Hidayat</a>, creator of Phantomjs </div> <div class="col-xs-1 imgbg"> <img src="~/Content/phantomjs-logo.png" style="width: 100%;" /> </div> <div class="col-xs-5"> <a href="http://phantomjs.org/" target="_blank">PhantomJS</a> is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. </div> </div>
mit
C#
7d06b2cfaf517715e4becba9300ff0183197e125
Update QueueCallerLeaveEvent.cs
skrusty/AsterNET,AsterNET/AsterNET
Asterisk.2013/Asterisk.NET/Manager/Event/QueueCallerLeaveEvent.cs
Asterisk.2013/Asterisk.NET/Manager/Event/QueueCallerLeaveEvent.cs
namespace AsterNET.Manager.Event { /// <summary> /// A QueueCallerLeaveEvent is triggered when a channel leaves a queue.<br/> /// </summary> public class QueueCallerLeaveEvent : LeaveEvent { // "Channel" in ManagerEvent.cs // "Queue" in QueueEvent.cs // "Count" in QueueEvent.cs public QueueCallerLeaveEvent(ManagerConnection source) : base(source) { } } }
namespace AsterNET.Manager.Event { /// <summary> /// A QueueCallerLeaveEvent is triggered when a channel leaves a queue.<br/> /// </summary> public class QueueCallerLeaveEvent : QueueEvent { public string Position { get; set; } public QueueCallerLeaveEvent(ManagerConnection source) : base(source) { } } }
mit
C#
a202254e6426b7c240bace18f4db0b271b095b9a
Update version
bitbeans/libsodium-net,tabrath/libsodium-core,fraga/libsodium-net,adamcaudill/libsodium-net,deckar01/libsodium-net,BurningEnlightenment/libsodium-net,bitbeans/libsodium-net,fraga/libsodium-net,deckar01/libsodium-net,BurningEnlightenment/libsodium-net,adamcaudill/libsodium-net
libsodium-net/Properties/AssemblyInfo.cs
libsodium-net/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("libsodium-net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adam Caudill")] [assembly: AssemblyProduct("libsodium-net")] [assembly: AssemblyCopyright("Copyright © Adam Caudill 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bac54bf6-5a39-4ab5-90f1-746a9d6b06f4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.3.0.0")] [assembly: AssemblyFileVersion("0.3.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("libsodium-net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adam Caudill")] [assembly: AssemblyProduct("libsodium-net")] [assembly: AssemblyCopyright("Copyright © Adam Caudill 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bac54bf6-5a39-4ab5-90f1-746a9d6b06f4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
mit
C#
f084d318e9f34748588c1129fd7c1478ec06a5c1
add data annotations to need assessment model
ndrmc/cats,ndrmc/cats,ndrmc/cats
Models/Cats.Models/NeedAssessmentWoredaDao.cs
Models/Cats.Models/NeedAssessmentWoredaDao.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cats.Models { public class NeedAssessmentWoredaDao { public int Woreda { get; set; } public string WoredaName { get; set; } public int Zone { get; set; } public string ZoneName {get; set; } public int NeedAID { get; set; } public int NAId { get; set; } [Range(0, Int32.MaxValue)] [DataType(DataType.Currency)] public Nullable<int> ProjectedMale { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> ProjectedFemale { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> RegularPSNP { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> PSNP { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> NonPSNP { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> Contingencybudget { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> TotalBeneficiaries { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> PSNPFromWoredasMale { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> PSNPFromWoredasFemale { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> PSNPFromWoredasDOA { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> NonPSNPFromWoredasMale { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> NonPSNPFromWoredasFemale { get; set; } [DataType(DataType.Currency)] [Range(0, Int32.MaxValue)] public Nullable<int> NonPSNPFromWoredasDOA { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cats.Models { public class NeedAssessmentWoredaDao { public int Woreda { get; set; } public string WoredaName { get; set; } public int Zone { get; set; } public string ZoneName {get; set; } public int NeedAID { get; set; } public int NAId { get; set; } public Nullable<int> ProjectedMale { get; set; } public Nullable<int> ProjectedFemale { get; set; } public Nullable<int> RegularPSNP { get; set; } public Nullable<int> PSNP { get; set; } public Nullable<int> NonPSNP { get; set; } public Nullable<int> Contingencybudget { get; set; } public Nullable<int> TotalBeneficiaries { get; set; } public Nullable<int> PSNPFromWoredasMale { get; set; } public Nullable<int> PSNPFromWoredasFemale { get; set; } public Nullable<int> PSNPFromWoredasDOA { get; set; } public Nullable<int> NonPSNPFromWoredasMale { get; set; } public Nullable<int> NonPSNPFromWoredasFemale { get; set; } public Nullable<int> NonPSNPFromWoredasDOA { get; set; } } }
apache-2.0
C#
80ec64b40a8d5d906faf0fed058f7ff3f0165cb6
improve test coverage
richardschneider/net-ipfs-core
test/CoreApi/AddFileOptionsTest.cs
test/CoreApi/AddFileOptionsTest.cs
using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ipfs.CoreApi { [TestClass] public class AddFileOptionsTests { [TestMethod] public void Defaults() { var options = new AddFileOptions(); Assert.AreEqual(true, options.Pin); Assert.AreEqual(256 * 1024, options.ChunkSize); Assert.AreEqual(MultiHash.DefaultAlgorithmName, options.Hash); Assert.AreEqual(false, options.OnlyHash); Assert.AreEqual(false, options.RawLeaves); Assert.AreEqual(false, options.Trickle); Assert.AreEqual(false, options.Wrap); } [TestMethod] public void Setting() { var options = new AddFileOptions { Pin = false, ChunkSize = 2 * 1024, Hash = "sha2-512", OnlyHash = true, RawLeaves = true, Trickle = true, Wrap = true }; Assert.AreEqual(false, options.Pin); Assert.AreEqual(2 * 1024, options.ChunkSize); Assert.AreEqual("sha2-512", options.Hash); Assert.AreEqual(true, options.OnlyHash); Assert.AreEqual(true, options.RawLeaves); Assert.AreEqual(true, options.Trickle); Assert.AreEqual(true, options.Wrap); } } }
using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ipfs.CoreApi { [TestClass] public class AddFileOptionsTests { [TestMethod] public void Defaults() { var options = new AddFileOptions(); Assert.AreEqual(true, options.Pin); Assert.AreEqual(256 * 1024, options.ChunkSize); Assert.AreEqual(MultiHash.DefaultAlgorithmName, options.Hash); Assert.AreEqual(false, options.OnlyHash); Assert.AreEqual(false, options.RawLeaves); Assert.AreEqual(false, options.Trickle); Assert.AreEqual(false, options.Wrap); } } }
mit
C#
8240fca7230c2e6d8051e5c2799df9d8f1666136
Make DoNoTrackAttribute public
joelweiss/ChangeTracking
Source/ChangeTracking/DoNoTrackAttribute.cs
Source/ChangeTracking/DoNoTrackAttribute.cs
using System; namespace ChangeTracking { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] public sealed class DoNoTrackAttribute : Attribute { } }
using System; namespace ChangeTracking { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] sealed class DoNoTrackAttribute : Attribute { } }
mit
C#
5b870f6b5e064943b9db6914c909fd2a7bf67e38
Remove duplicate (case insensitive comparison) enum value (PowerShell issue)
0xd4d/dnlib
src/DotNet/MethodAttributes.cs
src/DotNet/MethodAttributes.cs
// dnlib: See LICENSE.txt for more info using System; namespace dnlib.DotNet { /// <summary> /// Method attributes, see CorHdr.h/CorMethodAttr /// </summary> [Flags] public enum MethodAttributes : ushort { /// <summary>member access mask - Use this mask to retrieve accessibility information.</summary> MemberAccessMask = 0x0007, /// <summary>Member not referenceable.</summary> PrivateScope = 0x0000, /// <summary>Member not referenceable.</summary> CompilerControlled = PrivateScope, /// <summary>Accessible only by the parent type.</summary> Private = 0x0001, /// <summary>Accessible by sub-types only in this Assembly.</summary> FamANDAssem = 0x0002, /// <summary>Accessibly by anyone in the Assembly.</summary> Assembly = 0x0003, /// <summary>Accessible only by type and sub-types.</summary> Family = 0x0004, /// <summary>Accessibly by sub-types anywhere, plus anyone in assembly.</summary> FamORAssem = 0x0005, /// <summary>Accessibly by anyone who has visibility to this scope.</summary> Public = 0x0006, /// <summary>Defined on type, else per instance.</summary> Static = 0x0010, /// <summary>Method may not be overridden.</summary> Final = 0x0020, /// <summary>Method virtual.</summary> Virtual = 0x0040, /// <summary>Method hides by name+sig, else just by name.</summary> HideBySig = 0x0080, /// <summary>vtable layout mask - Use this mask to retrieve vtable attributes.</summary> VtableLayoutMask = 0x0100, /// <summary>The default.</summary> ReuseSlot = 0x0000, /// <summary>Method always gets a new slot in the vtable.</summary> NewSlot = 0x0100, /// <summary>Overridability is the same as the visibility.</summary> CheckAccessOnOverride = 0x0200, /// <summary>Method does not provide an implementation.</summary> Abstract = 0x0400, /// <summary>Method is special. Name describes how.</summary> SpecialName = 0x0800, /// <summary>Implementation is forwarded through pinvoke.</summary> PinvokeImpl = 0x2000, /// <summary>Managed method exported via thunk to unmanaged code.</summary> UnmanagedExport = 0x0008, /// <summary>Runtime should check name encoding.</summary> RTSpecialName = 0x1000, /// <summary>Method has security associate with it.</summary> HasSecurity = 0x4000, /// <summary>Method calls another method containing security code.</summary> RequireSecObject = 0x8000, } }
// dnlib: See LICENSE.txt for more info using System; namespace dnlib.DotNet { /// <summary> /// Method attributes, see CorHdr.h/CorMethodAttr /// </summary> [Flags] public enum MethodAttributes : ushort { /// <summary>member access mask - Use this mask to retrieve accessibility information.</summary> MemberAccessMask = 0x0007, /// <summary>Member not referenceable.</summary> PrivateScope = 0x0000, /// <summary>Member not referenceable.</summary> CompilerControlled = PrivateScope, /// <summary>Accessible only by the parent type.</summary> Private = 0x0001, /// <summary>Accessible by sub-types only in this Assembly.</summary> FamANDAssem = 0x0002, /// <summary>Accessibly by anyone in the Assembly.</summary> Assembly = 0x0003, /// <summary>Accessible only by type and sub-types.</summary> Family = 0x0004, /// <summary>Accessibly by sub-types anywhere, plus anyone in assembly.</summary> FamORAssem = 0x0005, /// <summary>Accessibly by anyone who has visibility to this scope.</summary> Public = 0x0006, /// <summary>Defined on type, else per instance.</summary> Static = 0x0010, /// <summary>Method may not be overridden.</summary> Final = 0x0020, /// <summary>Method virtual.</summary> Virtual = 0x0040, /// <summary>Method hides by name+sig, else just by name.</summary> HideBySig = 0x0080, /// <summary>vtable layout mask - Use this mask to retrieve vtable attributes.</summary> VtableLayoutMask = 0x0100, /// <summary>The default.</summary> ReuseSlot = 0x0000, /// <summary>Method always gets a new slot in the vtable.</summary> NewSlot = 0x0100, /// <summary>Overridability is the same as the visibility.</summary> CheckAccessOnOverride = 0x0200, /// <summary>Method does not provide an implementation.</summary> Abstract = 0x0400, /// <summary>Method is special. Name describes how.</summary> SpecialName = 0x0800, /// <summary>Implementation is forwarded through pinvoke.</summary> PinvokeImpl = 0x2000, /// <summary>Implementation is forwarded through pinvoke.</summary> PInvokeImpl = PinvokeImpl, /// <summary>Managed method exported via thunk to unmanaged code.</summary> UnmanagedExport = 0x0008, /// <summary>Runtime should check name encoding.</summary> RTSpecialName = 0x1000, /// <summary>Method has security associate with it.</summary> HasSecurity = 0x4000, /// <summary>Method calls another method containing security code.</summary> RequireSecObject = 0x8000, } }
mit
C#
729cc4c5b96f6822d3a0c4e30e515c53935753b7
Implement some of StandardAjax.System
faint32/snowflake-1,faint32/snowflake-1,SnowflakePowered/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake
Snowflake.StandardAjax/StandardAjax.System.cs
Snowflake.StandardAjax/StandardAjax.System.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Ajax; using Snowflake.Service; namespace Snowflake.StandardAjax { public partial class StandardAjax { [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetEmulatorBridges(IJSRequest request) { return new JSResponse(request, this.CoreInstance.PluginManager.LoadedEmulators); } [AjaxMethod(MethodPrefix = "System")] [AjaxMethodParameter(ParameterName = "platform", ParameterType = AjaxMethodParameterType.StringParameter)] public IJSResponse GetEmulatorBridgesForPlatform(IJSRequest request) { return new JSResponse(request, this.CoreInstance.PluginManager.LoadedEmulators.Where(bridge => bridge.Value.SupportedPlatforms.Contains(request.GetParameter("platform")))); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetScrapers(IJSRequest request) { return new JSResponse(request, this.CoreInstance.PluginManager.LoadedScrapers); } [AjaxMethod(MethodPrefix = "System")] [AjaxMethodParameter(ParameterName = "platform", ParameterType = AjaxMethodParameterType.StringParameter)] public IJSResponse GetScrapersForPlatform(IJSRequest request) { return new JSResponse(request, this.CoreInstance.PluginManager.LoadedScrapers.Where(scraper => scraper.Value.SupportedPlatforms.Contains(request.GetParameter("platform")))); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetAllPlugins(IJSRequest request) { return new JSResponse(request, this.CoreInstance.PluginManager.Registry); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetAllAjaxMethods(IJSRequest request) { return new JSResponse(request, this.CoreInstance.AjaxManager.GlobalNamespace.ToDictionary(ajax => ajax.Key, ajax => ajax.Value.JavascriptMethods)); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse SendEmulatorPrompt(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse ShutdownCore(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetCoreVersionString(IJSRequest request) { return new JSResponse(request, null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Ajax; using Snowflake.Service; namespace Snowflake.StandardAjax { public partial class StandardAjax { [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetEmulatorBridges(IJSRequest request) { return new JSResponse(request, this.CoreInstance.PluginManager.LoadedEmulators); } [AjaxMethod(MethodPrefix = "System")] [AjaxMethodParameter(ParameterName = "platform", ParameterType = AjaxMethodParameterType.StringParameter)] public IJSResponse GetEmulatorBridgesForPlatform(IJSRequest request) { return new JSResponse(request, this.CoreInstance.PluginManager.LoadedEmulators.Where(bridge => bridge.Value.SupportedPlatforms.Contains(request.GetParameter("platform")))); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetScrapers(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetScrapersForPlatform(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetAllPlugins(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetAllAjaxMethods(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse SendEmulatorPrompt(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse ShutdownCore(IJSRequest request) { return new JSResponse(request, null); } [AjaxMethod(MethodPrefix = "System")] public IJSResponse GetCoreVersionString(IJSRequest request) { return new JSResponse(request, null); } } }
mpl-2.0
C#
c78404f08913dc44629d8d99a64ae40a5d72c578
fix styling on MouseAI
fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation
UnityProject/Assets/Scripts/NPC/AI/MouseAI.cs
UnityProject/Assets/Scripts/NPC/AI/MouseAI.cs
using UnityEngine; using System.Collections.Generic; using System.Collections; /// <summary> /// AI brain for mice /// used to get hunted by Runtime and squeak /// </summary> public class MouseAI : MobAI { private string mouseName; private string capMouseName; private float timeForNextRandomAction; private float timeWaiting; protected override void Awake() { base.Awake(); mouseName = mobName.ToLower(); capMouseName = char.ToUpper(mouseName[0]) + mouseName.Substring(1); BeginExploring(MobExplore.Target.food); } protected override void UpdateMe() { if (health.IsDead || health.IsCrit || health.IsCardiacArrest) return; base.UpdateMe(); MonitorExtras(); } void MonitorExtras() { //TODO eat cables if haven't eaten in a while timeWaiting += Time.deltaTime; if (timeWaiting > timeForNextRandomAction) { timeWaiting = 0f; timeForNextRandomAction = Random.Range(3f, 30f); DoRandomSqueek(); } } public override void OnPetted(GameObject performer) { Squeak(); StartFleeing(performer.transform, 3f); } protected override void OnAttackReceived(GameObject damagedBy) { Squeak(); FleeFromAttacker(damagedBy, 5f); } private void Squeak() { SoundManager.PlayNetworkedAtPos( "MouseSqueek", gameObject.transform.position, Random.Range(.6f, 1.2f)); Chat.AddActionMsgToChat( gameObject, $"{capMouseName} squeaks!", $"{capMouseName} squeaks!"); } private void DoRandomSqueek() { Squeak(); } }
using UnityEngine; using System.Collections.Generic; using System.Collections; /// <summary> /// AI brain for mice /// used to get hunted by Runtime and squeak /// </summary> public class MouseAI : MobAI { private string mouseName; private string capMouseName; private float timeForNextRandomAction; private float timeWaiting; protected override void Awake() { base.Awake(); mouseName = mobName.ToLower(); capMouseName = char.ToUpper(mouseName[0]) + mouseName.Substring(1); BeginExploring(MobExplore.Target.food); } protected override void UpdateMe() { if (health.IsDead || health.IsCrit || health.IsCardiacArrest) return; base.UpdateMe(); MonitorExtras(); } void MonitorExtras() { //TODO eat cables if haven't eaten in a while timeWaiting += Time.deltaTime; if (timeWaiting > timeForNextRandomAction) { timeWaiting = 0f; timeForNextRandomAction = Random.Range(3f,30f); DoRandomSqueek(); } } public override void OnPetted(GameObject performer) { Squeak(); StartFleeing(performer.transform, 3f); } protected override void OnAttackReceived(GameObject damagedBy) { Squeak(); StartFleeing(damagedBy.transform, 5f); } private void Squeak() { SoundManager.PlayNetworkedAtPos("MouseSqueek", gameObject.transform.position, Random.Range(.6f,1.2f)); Chat.AddActionMsgToChat(gameObject, $"{capMouseName} squeaks!", $"{capMouseName} squeaks!"); } private void DoRandomSqueek() { Squeak(); } }
agpl-3.0
C#
f8e2bb07116d38a50035e07e0880ce443dfe860e
Update comment
Archie-Yang/PcscDotNet
src/PcscDotNet/SCardContext.cs
src/PcscDotNet/SCardContext.cs
namespace PcscDotNet { /// <summary> /// A handle that identifies the resource manager context. /// </summary> public struct SCardContext { /// <summary> /// Default value. /// </summary> public static readonly SCardContext Default = default(SCardContext); /// <summary> /// Returns true if `Value` is not null; otherwise, false. /// </summary> public unsafe bool HasValue => Value != null; /// <summary> /// Handle value. /// </summary> public unsafe void* Value; } }
namespace PcscDotNet { public struct SCardContext { public static readonly SCardContext Default = default(SCardContext); public unsafe bool HasValue => Value != null; public unsafe void* Value; } }
mit
C#
22b7a09733c01633bf6bb4178b959d670b018476
Clear record before start new recording
thedoritos/unity-touch-recorder
Assets/UnityTouchRecorder/Scripts/TouchRecorderController.cs
Assets/UnityTouchRecorder/Scripts/TouchRecorderController.cs
using UnityEngine; namespace UnityTouchRecorder { public class TouchRecorderController : MonoBehaviour { UnityTouchRecorderPlugin plugin = new UnityTouchRecorderPlugin(); [SerializeField] TouchRecorderView view; void Awake() { Object.DontDestroyOnLoad(gameObject); view.OpenMenuButton.onClick.AddListener(() => { view.SetMenuActive(!view.IsMenuActive); }); view.StartRecordingButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Clear(); plugin.StartRecording(); }); view.PlayButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Play(view.Repeat, view.Interval); }); view.StopButton.onClick.AddListener(() => { view.OpenMenuButton.gameObject.SetActive(true); view.StopButton.gameObject.SetActive(false); plugin.StopRecording(); plugin.Stop(); }); } } }
using UnityEngine; namespace UnityTouchRecorder { public class TouchRecorderController : MonoBehaviour { UnityTouchRecorderPlugin plugin = new UnityTouchRecorderPlugin(); [SerializeField] TouchRecorderView view; void Awake() { Object.DontDestroyOnLoad(gameObject); view.OpenMenuButton.onClick.AddListener(() => { view.SetMenuActive(!view.IsMenuActive); }); view.StartRecordingButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.StartRecording(); }); view.PlayButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Play(view.Repeat, view.Interval); }); view.StopButton.onClick.AddListener(() => { view.OpenMenuButton.gameObject.SetActive(true); view.StopButton.gameObject.SetActive(false); plugin.StopRecording(); plugin.Stop(); }); } } }
mit
C#
c2cb128554f3de73c27157f73b8fdd2127b03b8f
Access token recieving implemented
DenisBabarykin/OAuth2AuthorizationExample,DenisBabarykin/OAuth2AuthorizationExample,DenisBabarykin/OAuth2AuthorizationExample
src/WebApp/src/WebApp/Controllers/VkAuthorizationController.cs
src/WebApp/src/WebApp/Controllers/VkAuthorizationController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using SimpleWebRequests; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace WebApp.Controllers { public class VkAuthorizationController : Controller { // GET: /<controller>/ public IActionResult VkAuthorization(Dictionary<string, string> parameters) { if (!parameters.ContainsKey("code")) return View("AuthorizationFail"); string code = parameters["code"]; dynamic response = RESTRequest.PostAsUrlEncodedWithJsonResponse("https://oauth.vk.com/access_token", new Dictionary<string, string>() { { "client_id", "5671241"}, { "client_secret", "7nHh8NwJJeaZrW7juOyZ" }, { "redirect_uri", "http://localhost:56230/VkAuthorization" }, { "code", code } }); return View("AuthorizationSucces"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace WebApp.Controllers { public class VkAuthorizationController : Controller { // GET: /<controller>/ public IActionResult VkAuthorization(Dictionary<string, string> parameters) { if (!parameters.ContainsKey("code")) return View("AuthorizationFail"); string code = parameters["code"]; return View("AuthorizationSucces"); } } }
mit
C#
45ca91d61a132d00fd7908c8ab4c903c86f13759
change home page
Team-Ressurrection/Asp.NetMVCApp,Team-Ressurrection/Asp.NetMVCApp,Team-Ressurrection/Asp.NetMVCApp
SalaryCalculator/SalaryCalculatorWeb/Views/Home/Index.cshtml
SalaryCalculator/SalaryCalculatorWeb/Views/Home/Index.cshtml
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>SALARY CALCULATOR</h1> <p class="lead"> This is a simple application, which allows you to calculate your incomes both from labor and non-labor contracts. You can easily calculate your social security income and social securities taxes. In just seconds you can get your net wage. </p> <p><a href="https://www.youtube.com/watch?v=EYgRIzkijdc&feature=youtu.be" class="btn btn-primary btn-block">View quick demo &raquo;</a></p> </div> <div class="row"> </div> <div class="row"> <div class="col-md-4 jumbotron" style="margin: 5px"> <h2>Legislation</h2> <p> For more information about Labour legislation area visit here. </p> <p> <a class="btn btn-info" href="https://www.mlsp.government.bg/index.php?section=CONTENT&I=629">MLSP &raquo;</a> </p> </div> <div class="col-md-4 jumbotron" style="margin: 5px"> <h2>Taxes</h2> <p> For more information about taxes visit National Revenue Agency site. </p> <p> <a class="btn btn-info" href="http://www.nap.bg/page?id=387">NRA &raquo;</a> </p> </div> <div class="col-md-4 jumbotron" style="margin: 5px"> <h2>Insurance</h2> <p> For more information about social security information visit National Social Security Institute </p> <p> <a class="btn btn-info" href="http://www.nssi.bg/legislationbg">NSSI &raquo;</a> </p> </div> </div>
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>ASP.NET</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p> <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p> ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development. </p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> </div>
mit
C#
de0aa92a403572e13e8da442d9dfd7f9b6a0d5c3
Add more tests
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Tests/UnitTests/GUI/SendControlViewModelTest.cs
WalletWasabi.Tests/UnitTests/GUI/SendControlViewModelTest.cs
using Xunit; using WalletWasabi.Gui.Controls.WalletExplorer; namespace WalletWasabi.Tests.UnitTests.GUI { public class SendControlViewModelTest { [Theory] [InlineData(false, "0")] [InlineData(false, "0.1")] [InlineData(true, "1.2099999997690000")] [InlineData(true, "1")] [InlineData(true, "47")] [InlineData(true, "47.0")] [InlineData(true, "1111111111111")] [InlineData(false, "11111111111111")] [InlineData(false, "2099999997690000")] [InlineData(false, "2099999997690001")] [InlineData(false, "111111111111111111111111111")] [InlineData(false, "99999999999999999999999999999999999999999999")] [InlineData(false, "abc")] [InlineData(false, "1a2b")] [InlineData(false, "")] [InlineData(false, null)] [InlineData(false, " ")] [InlineData(false, " 2")] [InlineData(true, "1.1")] [InlineData(false, "1.1 ")] [InlineData(false, "1,1")] [InlineData(false, "1. 1")] [InlineData(false, "1 .1")] [InlineData(false, "0. 1")] [InlineData(false, "csszáőüó@")] public void SendControlViewModel_Check_Test_Fees(bool isValid, string feeText) { Assert.Equal(isValid, SendControlViewModel.TryParseUserFee(feeText, out var _)); } } }
using Xunit; using WalletWasabi.Gui.Controls.WalletExplorer; namespace WalletWasabi.Tests.UnitTests.GUI { public class SendControlViewModelTest { [Theory] [InlineData(false, "0")] [InlineData(false, "0.1")] [InlineData(true, "1.2099999997690000")] [InlineData(true, "1")] [InlineData(true, "47")] [InlineData(true, "47.0")] [InlineData(true, "1111111111111")] [InlineData(false, "11111111111111")] [InlineData(false, "2099999997690000")] [InlineData(false, "2099999997690001")] [InlineData(false, "111111111111111111111111111")] [InlineData(false, "99999999999999999999999999999999999999999999")] public void SendControlViewModel_Check_Test_Fees(bool isValid, string feeText) { Assert.Equal(isValid, SendControlViewModel.TryParseUserFee(feeText, out var _)); } } }
mit
C#
385a9550a17579088dff1c92f6b2bec94a7829a0
fix broken dependancy
cityindex-attic/CIAPI.CS,cityindex-attic/CIAPI.CS,cityindex-attic/CIAPI.CS
src/packages/Lightstreamer.3-6.DotNetClient_N2/AssemblyInfo.cs
src/packages/Lightstreamer.3-6.DotNetClient_N2/AssemblyInfo.cs
// Assembly DotNetClient_N2, Version 1.1.3323.32539 [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] [assembly: System.Runtime.InteropServices.Guid("6957aed9-4119-47d8-a864-e8987adfa8a1")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows=true)] [assembly: System.Reflection.AssemblyFileVersion("1.1")] [assembly: System.Reflection.AssemblyCompany("Weswit s.r.l.")] [assembly: System.Reflection.AssemblyTrademark("")] [assembly: System.Reflection.AssemblyCopyright("Copyright \x00a9 2004-2008 Weswit s.r.l. All rights reserved.")] [assembly: System.Reflection.AssemblyProduct("Lightstreamer .Net Client")] [assembly: System.Reflection.AssemblyDescription("")] [assembly: System.Reflection.AssemblyConfiguration("")] [assembly: System.Reflection.AssemblyTitle("Lightstreamer .Net Client")] [assembly: System.Diagnostics.Debuggable(System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations | System.Diagnostics.DebuggableAttribute.DebuggingModes.EnableEditAndContinue | System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: System.Runtime.CompilerServices.CompilationRelaxations(8)]
// Assembly DotNetClient_N2, Version 1.1.3323.32539 [assembly: System.Reflection.AssemblyVersion("1.1.3323.32539")] [assembly: System.Runtime.InteropServices.Guid("6957aed9-4119-47d8-a864-e8987adfa8a1")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows=true)] [assembly: System.Reflection.AssemblyFileVersion("1.1")] [assembly: System.Reflection.AssemblyCompany("Weswit s.r.l.")] [assembly: System.Reflection.AssemblyTrademark("")] [assembly: System.Reflection.AssemblyCopyright("Copyright \x00a9 2004-2008 Weswit s.r.l. All rights reserved.")] [assembly: System.Reflection.AssemblyProduct("Lightstreamer .Net Client")] [assembly: System.Reflection.AssemblyDescription("")] [assembly: System.Reflection.AssemblyConfiguration("")] [assembly: System.Reflection.AssemblyTitle("Lightstreamer .Net Client")] [assembly: System.Diagnostics.Debuggable(System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations | System.Diagnostics.DebuggableAttribute.DebuggingModes.EnableEditAndContinue | System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: System.Runtime.CompilerServices.CompilationRelaxations(8)]
apache-2.0
C#
2153c69bd4fcab8e44b98e4e04238ad507e1c990
Set version 0.9.0
hazzik/DelegateDecompiler,jaenyph/DelegateDecompiler,morgen2009/DelegateDecompiler
src/DelegateDecompiler/Properties/AssemblyInfo.cs
src/DelegateDecompiler/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("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")] [assembly: InternalsVisibleTo("DelegateDecompiler.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c96a47f445d38b9b23cbf52e405743481cb9bd2df4672ad6494abcdeb9daf5588eb6159cc88af5fd5a18cece1f05ecb3ddba4b6329535438f4d173f2b769c4715c136ce65c2f25e7360916737056bca40bee22ab2f178af4c5fdc0e5051a6b2630f31447885eb4f5273271c56bd7b8fb240ab453635a79ec2d8aae4a58a6439f")]
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("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.3.0")] [assembly: AssemblyFileVersion("0.8.3.0")] [assembly: InternalsVisibleTo("DelegateDecompiler.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c96a47f445d38b9b23cbf52e405743481cb9bd2df4672ad6494abcdeb9daf5588eb6159cc88af5fd5a18cece1f05ecb3ddba4b6329535438f4d173f2b769c4715c136ce65c2f25e7360916737056bca40bee22ab2f178af4c5fdc0e5051a6b2630f31447885eb4f5273271c56bd7b8fb240ab453635a79ec2d8aae4a58a6439f")]
mit
C#
1c974721b06b152f00f856ea2d698bade69dc4e1
Fix FILETIME serialization is corrupt in Mono.
modulexcite/msgpack-cli,scopely/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli,undeadlabs/msgpack-cli,modulexcite/msgpack-cli,scopely/msgpack-cli,msgpack/msgpack-cli
src/MsgPack/Serialization/DefaultSerializers/System_Runtime_InteropServices_ComTypes_FILETIMEMessagePackSerializer.cs
src/MsgPack/Serialization/DefaultSerializers/System_Runtime_InteropServices_ComTypes_FILETIMEMessagePackSerializer.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2012 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- #if !SILVERLIGHT using System; using System.Runtime.InteropServices.ComTypes; namespace MsgPack.Serialization.DefaultSerializers { internal sealed class System_Runtime_InteropServices_ComTypes_FILETIMEMessagePackSerializer : MessagePackSerializer<FILETIME> { private static readonly DateTime _fileTimeEpocUtc = new DateTime( 1601, 1, 1, 0, 0, 0, DateTimeKind.Utc ); public System_Runtime_InteropServices_ComTypes_FILETIMEMessagePackSerializer( PackerCompatibilityOptions packerCompatibilityOptions ) : base( packerCompatibilityOptions ) { } protected internal sealed override void PackToCore( Packer packer, FILETIME value ) { packer.Pack( MessagePackConvert.FromDateTime( // DateTime.FromFileTimeUtc in Mono 2.10.x does not return Utc DateTime (Mono issue #2936), so do convert manually to ensure returned DateTime is UTC. _fileTimeEpocUtc.AddTicks(unchecked( ( ( long )value.dwHighDateTime << 32 ) | ( value.dwLowDateTime & 0xffffffff ) ) ) ) ); } protected internal sealed override FILETIME UnpackFromCore( Unpacker unpacker ) { var value = MessagePackConvert.ToDateTime( unpacker.LastReadData.AsInt64() ).ToFileTimeUtc(); return new FILETIME() { dwHighDateTime = unchecked( ( int )( value >> 32 ) ), dwLowDateTime = unchecked( ( int )( value & 0xffffffff ) ) }; } } } #endif
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2012 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- #if !SILVERLIGHT using System; using System.Runtime.InteropServices.ComTypes; namespace MsgPack.Serialization.DefaultSerializers { internal sealed class System_Runtime_InteropServices_ComTypes_FILETIMEMessagePackSerializer : MessagePackSerializer<FILETIME> { public System_Runtime_InteropServices_ComTypes_FILETIMEMessagePackSerializer( PackerCompatibilityOptions packerCompatibilityOptions ) : base( packerCompatibilityOptions ) { } protected internal sealed override void PackToCore( Packer packer, FILETIME value ) { packer.Pack( MessagePackConvert.FromDateTime( DateTime.FromFileTimeUtc( unchecked( ( ( long )value.dwHighDateTime << 32 ) | ( value.dwLowDateTime & 0xffffffff ) ) ) ) ); } protected internal sealed override FILETIME UnpackFromCore( Unpacker unpacker ) { var value = MessagePackConvert.ToDateTime( unpacker.LastReadData.AsInt64() ).ToFileTimeUtc(); return new FILETIME() { dwHighDateTime = unchecked( ( int )( value >> 32 ) ), dwLowDateTime = unchecked( ( int )( value & 0xffffffff ) ) }; } } } #endif
apache-2.0
C#
06ce3fff086a7df7d55418632865215c3f9ae353
Remove errant spaces from CompilerStatus.cs
tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
src/Tgstation.Server.Api/Models/CompilerStatus.cs
src/Tgstation.Server.Api/Models/CompilerStatus.cs
namespace Tgstation.Server.Api.Models { /// <summary> /// Status of the <see cref="DreamMaker"/> for an <see cref="Instance"/> /// </summary> #pragma warning disable CA1717 // Only FlagsAttribute enums should have plural names public enum CompilerStatus #pragma warning restore CA1717 // Only FlagsAttribute enums should have plural names { /// <summary> /// The <see cref="DreamMaker"/> is idle /// </summary> Idle, /// <summary> /// Pre-compile scripts are running /// </summary> PreCompile, /// <summary> /// The <see cref="Repository"/> is being copied /// </summary> Copying, /// <summary> /// The .dme is having it's server side modifications applied /// </summary> Modifying, /// <summary> /// DreamMaker is running /// </summary> Compiling, /// <summary> /// The DMAPI is being verified /// </summary> Verifying, /// <summary> /// The compile results are being duplicated /// </summary> Duplicating, /// <summary> /// The configuration is being linked to the compile results /// </summary> Symlinking, /// <summary> /// Post-compile scripts are running /// </summary> PostCompile, /// <summary> /// A failed compile job is being erased /// </summary> Cleanup } }
namespace Tgstation.Server.Api.Models { /// <summary> /// Status of the <see cref="DreamMaker"/> for an <see cref="Instance"/> /// </summary> #pragma warning disable CA1717 // Only FlagsAttribute enums should have plural names public enum CompilerStatus #pragma warning restore CA1717 // Only FlagsAttribute enums should have plural names { /// <summary> /// The <see cref="DreamMaker"/> is idle /// </summary> Idle, /// <summary> /// Pre-compile scripts are running /// </summary> PreCompile, /// <summary> /// The <see cref="Repository"/> is being copied /// </summary> Copying, /// <summary> /// The .dme is having it's server side modifications applied /// </summary> Modifying, /// <summary> /// DreamMaker is running /// </summary> Compiling, /// <summary> /// The DMAPI is being verified /// </summary> Verifying, /// <summary> /// The compile results are being duplicated /// </summary> Duplicating, /// <summary> /// The configuration is being linked to the compile results /// </summary> Symlinking, /// <summary> /// Post-compile scripts are running /// </summary> PostCompile, /// <summary> /// A failed compile job is being erased /// </summary> Cleanup } }
agpl-3.0
C#
59a6b278ef3d48c278927186d29e90fa7cc2752a
Update Chogath.cs
metaphorce/leaguesharp
MetaSmite/Champions/Chogath.cs
MetaSmite/Champions/Chogath.cs
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Chogath { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.R, 175f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Chogath { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.R, 175f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnGameUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
mit
C#
20b843e63c86dc8d84217c29ba5a5654c576adae
Add create tab
ppy/osu,smoogipoo/osu,smoogipoo/osu,2yangk23/osu,DrabWeb/osu,naoey/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,peppy/osu-new,DrabWeb/osu,ZLima12/osu,naoey/osu,EVAST9919/osu,naoey/osu,ZLima12/osu,EVAST9919/osu
osu.Game/Screens/Multi/Screens/Lounge/FilterControl.cs
osu.Game/Screens/Multi/Screens/Lounge/FilterControl.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Overlays.SearchableList; using osuTK.Graphics; namespace osu.Game.Screens.Multi.Screens.Lounge { public class FilterControl : SearchableListFilterControl<LoungeTab, LoungeTab> { protected override Color4 BackgroundColour => OsuColour.FromHex(@"362e42"); protected override LoungeTab DefaultTab => LoungeTab.Public; public FilterControl() { DisplayStyleControl.Hide(); } public RoomAvailability Availability { get { switch (Tabs.Current.Value) { default: case LoungeTab.Public: return RoomAvailability.Public; case LoungeTab.Private: return RoomAvailability.FriendsOnly; } } } } public enum LoungeTab { Create, Public, Private, } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Overlays.SearchableList; using osuTK.Graphics; namespace osu.Game.Screens.Multi.Screens.Lounge { public class FilterControl : SearchableListFilterControl<LoungeTab, LoungeTab> { protected override Color4 BackgroundColour => OsuColour.FromHex(@"362e42"); protected override LoungeTab DefaultTab => LoungeTab.Public; public FilterControl() { DisplayStyleControl.Hide(); } public RoomAvailability Availability { get { switch (Tabs.Current.Value) { default: case LoungeTab.Public: return RoomAvailability.Public; case LoungeTab.Private: return RoomAvailability.FriendsOnly; } } } } public enum LoungeTab { Public, Private, } }
mit
C#
49584da47cadf56a33953ac6863d379a76d88274
write test output to files to prevent interleaving when running tests in parallel
SQLStreamStore/SQLStreamStore,damianh/Cedar.EventStore,SQLStreamStore/SQLStreamStore
build.cake
build.cake
#addin "nuget:?package=Cake.FileHelpers&version=2.0.0" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var artifactsDir = Directory("./artifacts"); var sourceDir = Directory("./src"); var solution = "./src/SqlStreamStore.sln"; var buildNumber = string.IsNullOrWhiteSpace(EnvironmentVariable("BUILD_NUMBER")) ? "0" : EnvironmentVariable("BUILD_NUMBER"); Task("Clean") .Does(() => { CleanDirectory(artifactsDir); }); Task("RestorePackages") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore(solution); }); Task("Build") .IsDependentOn("RestorePackages") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; DotNetCoreBuild(solution, settings); }); Task("RunTests") .IsDependentOn("Build") .Does(() => { Parallel.ForEach(Projects, project => { using (var process = TestAssembly($"{project}.Tests")) { process.WaitForExit(); } }); }); Task("DotNetPack") .IsDependentOn("Build") .Does(() => { var versionSuffix = "build" + buildNumber.ToString().PadLeft(5, '0'); var dotNetCorePackSettings = new DotNetCorePackSettings { OutputDirectory = artifactsDir, NoBuild = true, Configuration = configuration, VersionSuffix = versionSuffix }; Parallel.ForEach(Projects, project => DotNetCorePack($"./src/{project}", dotNetCorePackSettings)); }); Task("Default") .IsDependentOn("RunTests") .IsDependentOn("DotNetPack"); RunTarget(target); IProcess TestAssembly(string name) => StartAndReturnProcess( "dotnet", new ProcessSettings { Arguments = XUnitArguments(name), WorkingDirectory = sourceDir + Directory(name) }); string XUnitArguments(string name) { var args = $"xunit -quiet -parallel all -configuration {configuration} -nobuild"; if (BuildSystem.IsRunningOnTeamCity) { args += $" -xml {artifactsDir + File($"{name}.xml")}"; } return args; } string[] Projects => new[] {"SqlStreamStore", "SqlStreamStore.MsSql"};
#addin "nuget:?package=Cake.FileHelpers&version=2.0.0" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var artifactsDir = Directory("./artifacts"); var sourceDir = Directory("./src"); var solution = "./src/SqlStreamStore.sln"; var buildNumber = string.IsNullOrWhiteSpace(EnvironmentVariable("BUILD_NUMBER")) ? "0" : EnvironmentVariable("BUILD_NUMBER"); Task("Clean") .Does(() => { CleanDirectory(artifactsDir); }); Task("RestorePackages") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore(solution); }); Task("Build") .IsDependentOn("RestorePackages") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; DotNetCoreBuild(solution, settings); }); Task("RunTests") .IsDependentOn("Build") .Does(() => { Parallel.ForEach(Projects, project => { using (var process = TestAssembly($"{project}.Tests")) { process.WaitForExit(); } }); }); Task("DotNetPack") .IsDependentOn("Build") .Does(() => { var versionSuffix = "build" + buildNumber.ToString().PadLeft(5, '0'); var dotNetCorePackSettings = new DotNetCorePackSettings { OutputDirectory = artifactsDir, NoBuild = true, Configuration = configuration, VersionSuffix = versionSuffix }; Parallel.ForEach(Projects, project => DotNetCorePack($"./src/{project}", dotNetCorePackSettings)); }); Task("Default") .IsDependentOn("RunTests") .IsDependentOn("DotNetPack"); RunTarget(target); IProcess TestAssembly(string name) => StartAndReturnProcess( "dotnet", new ProcessSettings { Arguments = $"xunit -quiet -parallel all -configuration {configuration} -nobuild", WorkingDirectory = sourceDir + Directory(name) }); string[] Projects => new[] {"SqlStreamStore", "SqlStreamStore.MsSql"};
mit
C#
c6ea10c6af894b588ba263616c24a9432dcc23d3
fix publish
Sphiecoh/MusicStore,Sphiecoh/MusicStore
build.cake
build.cake
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var sourcePath = Directory("./src/NancyMusicStore"); var testsPath = Directory("test"); var buildArtifacts = Directory("./artifacts/packages"); Task("Publish") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCorePublishSettings { // Framework = "netcoreapp1.0", Configuration = "Release", OutputDirectory = buildArtifacts }; var projects = GetFiles("./**/project.json"); foreach(var project in projects) { DotNetCorePublish(project.GetDirectory().FullPath, settings); } }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration // Runtime = IsRunningOnWindows() ? null : "unix-x64" }; DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("RunTests") .IsDependentOn("Build") .Does(() => { var projects = GetFiles("./test/**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreTestSettings { Configuration = configuration }; DotNetCoreTest(project.GetDirectory().FullPath, settings); } }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new [] { "https://api.nuget.org/v3/index.json" } }; DotNetCoreRestore("./src", settings); //DotNetCoreRestore(testsPath, settings); }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var sourcePath = Directory("./src/NancyMusicStore"); var testsPath = Directory("test"); var buildArtifacts = Directory("./artifacts/packages"); Task("Publish") .IsDependentOn("RunTests") .Does(() => { var settings = new DotNetCorePublishSettings { // Framework = "netcoreapp1.0", Configuration = "Release", OutputDirectory = buildArtifacts }; DotNetCorePublish("./src/*", settings); }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration // Runtime = IsRunningOnWindows() ? null : "unix-x64" }; DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("RunTests") .IsDependentOn("Build") .Does(() => { var projects = GetFiles("./test/**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreTestSettings { Configuration = configuration }; DotNetCoreTest(project.GetDirectory().FullPath, settings); } }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new [] { "https://api.nuget.org/v3/index.json" } }; DotNetCoreRestore("./src", settings); //DotNetCoreRestore(testsPath, settings); }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
mit
C#
2a154ef312b0bd576f079cdd7c7c13948f7cd800
remove timing
jefking/King.Service.ServiceBus
Demo/King.Service.ServiceBus.WorkerRole/Queue/QueueForBuffer.cs
Demo/King.Service.ServiceBus.WorkerRole/Queue/QueueForBuffer.cs
namespace King.Service.WorkerRole.Queue { using King.Service.ServiceBus; using King.Service.ServiceBus.Queue; using System; using System.Diagnostics; public class QueueForBuffer : RecurringTask { #region Members private readonly IBusQueueSender client; #endregion #region Constructors public QueueForBuffer(IBusQueueSender client) { this.client = client; } #endregion public override void Run() { var model = new ExampleModel { Identifier = Guid.NewGuid(), Action = "Buffered", }; Trace.TraceInformation("Sending to queue for {0}: '{1}'", model.Action, model.Identifier); client.SendBuffered(model, DateTime.UtcNow.AddSeconds(30)).Wait(); } } }
namespace King.Service.WorkerRole.Queue { using King.Service.ServiceBus; using King.Service.ServiceBus.Queue; using System; using System.Diagnostics; public class QueueForBuffer : RecurringTask { #region Members private readonly IBusQueueSender client; #endregion #region Constructors public QueueForBuffer(IBusQueueSender client) :base(10, 10) { this.client = client; } #endregion public override void Run() { var model = new ExampleModel { Identifier = Guid.NewGuid(), Action = "Buffered", }; Trace.TraceInformation("Sending to queue for {0}: '{1}'", model.Action, model.Identifier); client.SendBuffered(model, DateTime.UtcNow.AddSeconds(30)).Wait(); } } }
mit
C#
310e5d70115401e2eeba9139ed6dab63ab0c55f6
revert testing assembly version
mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,duplicati/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati
Duplicati/GUI/Duplicati.GUI.TrayIcon/Properties/AssemblyInfo.cs
Duplicati/GUI/Duplicati.GUI.TrayIcon/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("Duplicati")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Duplicati Team")] [assembly: AssemblyProduct("Duplicati.GUI.TrayIcon")] [assembly: AssemblyCopyright("LGPL, Copyright © Duplicati Team 2019")] [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("33531def-3214-4568-bfb0-0bdeabe4a798")] // 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("2.0.0.7")] [assembly: AssemblyVersion("2.0.0.7")] [assembly: AssemblyFileVersion("2.0.0.7")]
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("Duplicati")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Duplicati Team")] [assembly: AssemblyProduct("Duplicati.GUI.TrayIcon")] [assembly: AssemblyCopyright("LGPL, Copyright © Duplicati Team 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("33531def-3214-4568-bfb0-0bdeabe4a798")] // 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("2.0.0.7")] [assembly: AssemblyVersion("2.0.4.28")] [assembly: AssemblyFileVersion("2.0.4.28")]
lgpl-2.1
C#
0e710878c8711fa72139968f94e46e5b17e8baed
Fix color problem
ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework
osu.Framework.Android/Graphics/Textures/AndroidTextureLoaderStore.cs
osu.Framework.Android/Graphics/Textures/AndroidTextureLoaderStore.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.Graphics; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using SixLabors.ImageSharp; using System; using System.IO; namespace osu.Framework.Android.Graphics.Textures { internal class AndroidTextureLoaderStore : TextureLoaderStore { public AndroidTextureLoaderStore(IResourceStore<byte[]> store) : base(store) { } protected override Image<TPixel> ImageFromStream<TPixel>(Stream stream) { using (var bitmap = BitmapFactory.DecodeStream(stream)) { var pixels = new int[bitmap.Width * bitmap.Height]; bitmap.GetPixels(pixels, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height); byte[] result = new byte[pixels.Length * sizeof(int)]; Buffer.BlockCopy(pixels, 0, result, 0, result.Length); for (int i = 0; i < pixels.Length; i++) { var b = result[i * 4]; result[i * 4] = result[i * 4 + 2]; result[i * 4 + 2] = b; } bitmap.Recycle(); return Image.LoadPixelData<TPixel>(result, bitmap.Width, bitmap.Height); } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.Graphics; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using SixLabors.ImageSharp; using System; using System.IO; namespace osu.Framework.Android.Graphics.Textures { internal class AndroidTextureLoaderStore : TextureLoaderStore { public AndroidTextureLoaderStore(IResourceStore<byte[]> store) : base(store) { } protected override Image<TPixel> ImageFromStream<TPixel>(Stream stream) { using (var bitmap = BitmapFactory.DecodeStream(stream)) { var pixels = new int[bitmap.Width * bitmap.Height]; bitmap.GetPixels(pixels, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height); byte[] result = new byte[pixels.Length * sizeof(int)]; Buffer.BlockCopy(pixels, 0, result, 0, result.Length); return Image.LoadPixelData<TPixel>(result, bitmap.Width, bitmap.Height); } } } }
mit
C#
5225d8f7df96415b4ad752abd1043f102e7c7cea
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.15.3")] [assembly: AssemblyInformationalVersion("0.15.3")] /* * Version 0.15.3 * * - [FIX] Lets idiomatic-test ignore members of an interface type. */
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.15.2")] [assembly: AssemblyInformationalVersion("0.15.2")] /* * Version 0.15.3 * * - [FIX] Lets idiomatic-test ignore members of an interface type. */
mit
C#
906a5f741776eae1f91d70599d68c74199f7de54
Fix build issue w/ Dev14
crwilcox/PTVS,alanch-ms/PTVS,fjxhkj/PTVS,zooba/PTVS,DinoV/PTVS,ChinaQuants/PTVS,dut3062796s/PTVS,ChinaQuants/PTVS,DEVSENSE/PTVS,alanch-ms/PTVS,huguesv/PTVS,dut3062796s/PTVS,ChinaQuants/PTVS,fivejjs/PTVS,zooba/PTVS,modulexcite/PTVS,fivejjs/PTVS,int19h/PTVS,gomiero/PTVS,int19h/PTVS,jkorell/PTVS,gomiero/PTVS,dut3062796s/PTVS,Habatchii/PTVS,huguesv/PTVS,gomiero/PTVS,xNUTs/PTVS,bolabola/PTVS,huguesv/PTVS,MetSystem/PTVS,modulexcite/PTVS,Habatchii/PTVS,denfromufa/PTVS,MetSystem/PTVS,denfromufa/PTVS,DEVSENSE/PTVS,modulexcite/PTVS,msunardi/PTVS,MetSystem/PTVS,mlorbetske/PTVS,huguesv/PTVS,xNUTs/PTVS,fjxhkj/PTVS,zooba/PTVS,MetSystem/PTVS,gomiero/PTVS,int19h/PTVS,ChinaQuants/PTVS,mlorbetske/PTVS,DinoV/PTVS,fivejjs/PTVS,alanch-ms/PTVS,alanch-ms/PTVS,jkorell/PTVS,bolabola/PTVS,Habatchii/PTVS,fivejjs/PTVS,xNUTs/PTVS,Microsoft/PTVS,christer155/PTVS,DinoV/PTVS,msunardi/PTVS,modulexcite/PTVS,msunardi/PTVS,fivejjs/PTVS,bolabola/PTVS,dut3062796s/PTVS,crwilcox/PTVS,fjxhkj/PTVS,xNUTs/PTVS,DEVSENSE/PTVS,DEVSENSE/PTVS,msunardi/PTVS,christer155/PTVS,Habatchii/PTVS,dut3062796s/PTVS,msunardi/PTVS,crwilcox/PTVS,huguesv/PTVS,modulexcite/PTVS,int19h/PTVS,fjxhkj/PTVS,denfromufa/PTVS,ChinaQuants/PTVS,zooba/PTVS,christer155/PTVS,Microsoft/PTVS,gomiero/PTVS,Habatchii/PTVS,crwilcox/PTVS,DinoV/PTVS,christer155/PTVS,crwilcox/PTVS,DEVSENSE/PTVS,DEVSENSE/PTVS,mlorbetske/PTVS,Microsoft/PTVS,DinoV/PTVS,huguesv/PTVS,Habatchii/PTVS,bolabola/PTVS,christer155/PTVS,xNUTs/PTVS,xNUTs/PTVS,dut3062796s/PTVS,zooba/PTVS,crwilcox/PTVS,ChinaQuants/PTVS,gomiero/PTVS,int19h/PTVS,fivejjs/PTVS,christer155/PTVS,MetSystem/PTVS,msunardi/PTVS,MetSystem/PTVS,int19h/PTVS,denfromufa/PTVS,DinoV/PTVS,zooba/PTVS,Microsoft/PTVS,fjxhkj/PTVS,fjxhkj/PTVS,jkorell/PTVS,mlorbetske/PTVS,mlorbetske/PTVS,jkorell/PTVS,jkorell/PTVS,Microsoft/PTVS,bolabola/PTVS,mlorbetske/PTVS,bolabola/PTVS,denfromufa/PTVS,alanch-ms/PTVS,jkorell/PTVS,denfromufa/PTVS,Microsoft/PTVS,modulexcite/PTVS,alanch-ms/PTVS
Python/Product/PythonTools/PythonTools/Repl/InlineReplAdornment.cs
Python/Product/PythonTools/PythonTools/Repl/InlineReplAdornment.cs
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System.ComponentModel.Composition; using System.Windows; #if DEV14_OR_LATER using Microsoft.VisualStudio.InteractiveWindow; #else using Microsoft.VisualStudio.Repl; #endif using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.PythonTools.Repl { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(IntraTextAdornmentTag))] #if DEV14_OR_LATER [ContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName)] #else [ContentType(ReplConstants.ReplContentTypeName)] #endif internal class InlineReplAdornmentProvider : IViewTaggerProvider { public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag { if (buffer == null || textView == null || typeof(T) != typeof(IntraTextAdornmentTag)) { return null; } return (ITagger<T>)textView.Properties.GetOrCreateSingletonProperty<InlineReplAdornmentManager>( typeof(InlineReplAdornmentManager), () => new InlineReplAdornmentManager(textView) ); } internal static InlineReplAdornmentManager GetManager(ITextView view) { InlineReplAdornmentManager result; if (!view.Properties.TryGetProperty<InlineReplAdornmentManager>(typeof(InlineReplAdornmentManager), out result)) { return null; } return result; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System.ComponentModel.Composition; using System.Windows; #if DEV14_OR_LATER Microsoft.VisualStudio.InteractiveWindow #else using Microsoft.VisualStudio.Repl; #endif using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.PythonTools.Repl { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(IntraTextAdornmentTag))] #if DEV14_OR_LATER [ContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName)] #else [ContentType(ReplConstants.ReplContentTypeName)] #endif internal class InlineReplAdornmentProvider : IViewTaggerProvider { public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag { if (buffer == null || textView == null || typeof(T) != typeof(IntraTextAdornmentTag)) { return null; } return (ITagger<T>)textView.Properties.GetOrCreateSingletonProperty<InlineReplAdornmentManager>( typeof(InlineReplAdornmentManager), () => new InlineReplAdornmentManager(textView) ); } internal static InlineReplAdornmentManager GetManager(ITextView view) { InlineReplAdornmentManager result; if (!view.Properties.TryGetProperty<InlineReplAdornmentManager>(typeof(InlineReplAdornmentManager), out result)) { return null; } return result; } } }
apache-2.0
C#
ce2956fef51eda952e310483585e64959e75e0a2
Add missing license header.
chromium/vs-chromium,chromium/vs-chromium,chromium/vs-chromium,chromium/vs-chromium
src/Core/VsChromiumVersion.cs
src/Core/VsChromiumVersion.cs
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VsChromium.Core { public static class VsChromiumVersion { public const string Product = "0.9.7"; public const string File = Product + ".0"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VsChromium.Core { public static class VsChromiumVersion { public const string Product = "0.9.7"; public const string File = Product + ".0"; } }
bsd-3-clause
C#
142f9b83ddcb9818455f666c680c27f8fa097ad9
Change output path, change screentshot image file name.
sanukin39/UniEditorScreenshot
Assets/UniEditorScreenshot/Editor/CaptureWindow.cs
Assets/UniEditorScreenshot/Editor/CaptureWindow.cs
using UnityEngine; using UnityEditor; using System; public class CaptureWindow : EditorWindow { private string saveFileName = string.Empty; private string saveDirPath = string.Empty; [MenuItem("Window/Screenshot Capture")] private static void Capture() { EditorWindow.GetWindow(typeof(CaptureWindow)).Show(); } private void OnGUI() { EditorGUILayout.LabelField("Output Folder Path : "); EditorGUILayout.LabelField(saveDirPath + "/"); if (string.IsNullOrEmpty(saveDirPath)) { saveDirPath = Application.dataPath + "/.."; } if (GUILayout.Button("Select output directory")) { string path = EditorUtility.OpenFolderPanel("select directory", saveDirPath, Application.dataPath); if (!string.IsNullOrEmpty(path)) { saveDirPath = path; } } if (GUILayout.Button("Open output directory")) { System.Diagnostics.Process.Start(saveDirPath); } // insert blank line GUILayout.Label(""); if (GUILayout.Button("Take screenshot")) { var resolution = GetMainGameViewSize(); int x = (int)resolution.x; int y = (int)resolution.y; var outputPath = saveDirPath + "/" + DateTime.Now.ToString($"{x}x{y}_yyyy_MM_dd_HH_mm_ss") + ".png"; ScreenCapture.CaptureScreenshot(outputPath); Debug.Log("Export scrennshot at " + outputPath); } } public static Vector2 GetMainGameViewSize() { System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor"); System.Reflection.MethodInfo GetSizeOfMainGameView = T.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); System.Object Res = GetSizeOfMainGameView.Invoke(null, null); return (Vector2)Res; } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Collections; public class CaptureWindow : EditorWindow{ private string saveFileName = string.Empty; private string saveDirPath = string.Empty; [MenuItem("Window/Capture Editor")] private static void Capture() { EditorWindow.GetWindow (typeof(CaptureWindow)).Show (); } void OnGUI() { EditorGUILayout.LabelField ("OUTPUT FOLDER PATH:"); EditorGUILayout.LabelField (saveDirPath + "/"); if (string.IsNullOrEmpty (saveDirPath)) { saveDirPath = Application.dataPath; } if (GUILayout.Button("Select output directory")) { string path = EditorUtility.OpenFolderPanel("select directory", saveDirPath, Application.dataPath); if (!string.IsNullOrEmpty(path)) { saveDirPath = path; } } if (GUILayout.Button("Open output directory")) { System.Diagnostics.Process.Start (saveDirPath); } // insert blank line GUILayout.Label (""); if (GUILayout.Button("Take screenshot")) { var outputPath = saveDirPath + "/" + DateTime.Now.ToString ("yyyyMMddHHmmss") + ".png"; ScreenCapture.CaptureScreenshot (outputPath); Debug.Log ("Export scrennshot at " + outputPath); } } }
mit
C#
66383e489482dc8c03c4bc38eda1045e55c14894
Fix bug in script args.
sethreno/schemazen,keith-hall/schemazen,sethreno/schemazen,Zocdoc/schemazen,ruediger-stevens/schemazen
console/Script.cs
console/Script.cs
using System; using System.IO; using System.Security.Cryptography; using model; namespace console { public class Script : DbCommand { protected string DataTables { get; set; } protected string DataTablesPattern { get; set; } public Script() : base( "Script", "Generate scripts for the specified database.") { HasOption( "dataTables=", "A comma separated list of tables to export data from.", o => DataTables = o); HasOption( "dataTablesPattern=", "A regular expression pattern that matches tables to export data from.", o => DataTablesPattern = o); } public override int Run(string[] args) { var db = CreateDatabase(); db.Load(); if (!String.IsNullOrEmpty(DataTables)) { HandleDataTables(db, DataTables); } if (!String.IsNullOrEmpty(DataTablesPattern)) { var tables = db.FindTablesRegEx(DataTablesPattern); foreach (var t in tables) { if (db.DataTables.Contains(t)) continue; db.DataTables.Add(t); } } if (!Overwrite && Directory.Exists(db.Dir)) { Console.Write("{0} already exists do you want to replace it? (Y/N)", db.Dir); var key = Console.ReadKey(); if (key.Key != ConsoleKey.Y) { return 1; } Console.WriteLine(); } db.ScriptToDir(Overwrite); Console.WriteLine("Snapshot successfully created at " + db.Dir); return 0; } private static void HandleDataTables(Database db, string tableNames) { foreach (var value in tableNames.Split(',')) { var schema = "dbo"; var name = value; if (value.Contains(".")) { schema = value.Split('.')[0]; name = value.Split('.')[1]; } var t = db.FindTable(name, schema); if (t == null) { Console.WriteLine( "warning: could not find data table {0}.{1}", schema, name); } if (db.DataTables.Contains(t)) continue; db.DataTables.Add(t); } } } }
using System; using System.IO; using System.Security.Cryptography; using model; namespace console { public class Script : DbCommand { protected string DataTables { get; set; } protected string DataTablesPattern { get; set; } public Script() : base( "Script", "Generate scripts for the specified database.") { HasOption( "dataTables=", "A comma separated list of tables to export data from.", o => DataTables = o); HasOption( "dataTablesPattern=", "A regular expression pattern that matches tables to export data from.", o => DataTables = o); } public override int Run(string[] args) { var db = CreateDatabase(); db.Load(); if (!String.IsNullOrEmpty(DataTables)) { HandleDataTables(db, DataTables); } if (!String.IsNullOrEmpty(DataTablesPattern)) { var tables = db.FindTablesRegEx(DataTablesPattern); foreach (var t in tables) { if (db.DataTables.Contains(t)) continue; db.DataTables.Add(t); } } if (!Overwrite && Directory.Exists(db.Dir)) { Console.Write("{0} already exists do you want to replace it? (Y/N)", db.Dir); var key = Console.ReadKey(); if (key.Key != ConsoleKey.Y) { return 1; } Console.WriteLine(); } db.ScriptToDir(Overwrite); Console.WriteLine("Snapshot successfully created at " + db.Dir); return 0; } private static void HandleDataTables(Database db, string tableNames) { foreach (var value in tableNames.Split(',')) { var schema = "dbo"; var name = value; if (value.Contains(".")) { schema = value.Split('.')[0]; name = value.Split('.')[1]; } var t = db.FindTable(name, schema); if (t == null) { Console.WriteLine( "warning: could not find data table {0}.{1}", schema, name); } if (db.DataTables.Contains(t)) continue; db.DataTables.Add(t); } } } }
mit
C#
00191e98587b93d44d828a75d9e77fcc9a33f490
Add ability to run through commandline w/o GUI
dpuleri/WRW
WinRedditWallpaper/App.xaml.cs
WinRedditWallpaper/App.xaml.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Diagnostics; namespace WinRedditWallpaper { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); string path = WinRedditWallpaper.Properties.Settings.Default.DownloadDirectory; //System.Collections.Specialized.StringCollection string[] subreddits = new string[WinRedditWallpaper.Properties.Settings.Default.SubredditsToDownload.Count]; WinRedditWallpaper.Properties.Settings.Default.SubredditsToDownload.CopyTo(subreddits, 0); Debug.WriteLine(path); foreach (string sub in subreddits) { Debug.WriteLine(sub); } Debug.WriteLine(subreddits.Length); Debug.WriteLine(subreddits == null); if (true) { MainWindow mainWindow = new MainWindow(new PicScraper(subreddits, path)); if (path != "none") { mainWindow.updatePathText(path); } //WallpaperChanger.setDesktopWallpaper(@"C:\\Users\\Daniel\\Desktop\\tmp2"); //Debug.WriteLine(WallpaperChanger.getDesktopWallpaper()); mainWindow.Show(); } else { Debug.WriteLine("wohoo, execute other code"); this.Shutdown(); } } protected override void OnExit(ExitEventArgs e) { base.OnExit(e); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Diagnostics; namespace WinRedditWallpaper { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); string path = WinRedditWallpaper.Properties.Settings.Default.DownloadDirectory; //System.Collections.Specialized.StringCollection string[] subreddits = new string[WinRedditWallpaper.Properties.Settings.Default.SubredditsToDownload.Count]; WinRedditWallpaper.Properties.Settings.Default.SubredditsToDownload.CopyTo(subreddits, 0); Debug.WriteLine(path); foreach (string sub in subreddits) { Debug.WriteLine(sub); } Debug.WriteLine(subreddits.Length); Debug.WriteLine(subreddits == null); MainWindow mainWindow = new MainWindow(new PicScraper(subreddits, path)); if (path != "none") { mainWindow.updatePathText(path); } //WallpaperChanger.setDesktopWallpaper(@"C:\\Users\\Daniel\\Desktop\\tmp2"); //Debug.WriteLine(WallpaperChanger.getDesktopWallpaper()); mainWindow.Show(); } protected override void OnExit(ExitEventArgs e) { base.OnExit(e); } } }
apache-2.0
C#
5548dbdf5b655043778c6d6b9382c07b883af3de
send to queue
jefking/King.Service.ServiceBus
Demo/King.Service.ServiceBus.WorkerRole/Factory.cs
Demo/King.Service.ServiceBus.WorkerRole/Factory.cs
namespace King.Service.ServiceBus { using King.Service.ServiceBus.Queue; using King.Service.WorkerRole; using King.Service.WorkerRole.Queue; using King.Service.WorkerRole.Scalable; using System.Collections.Generic; /// <summary> /// Factory /// </summary> public class Factory : ITaskFactory<Configuration> { /// <summary> /// Load Tasks /// </summary> /// <param name="passthrough"></param> /// <returns></returns> public IEnumerable<IRunnable> Tasks(Configuration config) { //Connections var pollReceiver = new BusQueueReciever(config.PollingName, config.Connection); var scalingQueue = new BusQueueReciever(config.ScalingQueueName, config.Connection); var eventReciever = new BusQueueReciever(config.EventsName, config.Connection); var bufferReciever = new BusQueueReciever(config.BufferedEventsName, config.Connection); //Initialize Service Bus yield return new InitializeBusQueue(pollReceiver); yield return new InitializeBusQueue(scalingQueue); yield return new InitializeBusQueue(eventReciever); yield return new InitializeBusQueue(bufferReciever); yield return new InitializeTopic(config.TopicName, config.Connection); //Polling Dequeue Runner yield return new AdaptiveRunner(new BusDequeue<ExampleModel>(pollReceiver, new ExampleProcessor())); //Task for watching for queue events yield return new BusEvents<ExampleModel>(eventReciever, new EventHandler()); //Task for recieving queue events to specific times yield return new BufferedReciever<ExampleModel>(bufferReciever, new EventHandler()); //Simulate messages being added to queues yield return new QueueForAction(new BusQueueSender(config.PollingName, config.Connection), "Poll"); yield return new QueueForAction(new BusQueueSender(config.EventsName, config.Connection), "Event"); yield return new QueueForAction(new BusQueueSender(config.ScalingQueueName, config.Connection), "Scaling"); yield return new QueueForBuffer(new BusQueueSender(config.BufferedEventsName, config.Connection)); //Auto Scaling Dequeue Task yield return new ScalableQueue(scalingQueue, config); } } }
namespace King.Service.ServiceBus { using King.Service.ServiceBus.Queue; using King.Service.WorkerRole; using King.Service.WorkerRole.Queue; using King.Service.WorkerRole.Scalable; using System.Collections.Generic; /// <summary> /// Factory /// </summary> public class Factory : ITaskFactory<Configuration> { /// <summary> /// Load Tasks /// </summary> /// <param name="passthrough"></param> /// <returns></returns> public IEnumerable<IRunnable> Tasks(Configuration config) { //Connections var pollReceiver = new BusQueueReciever(config.PollingName, config.Connection); var scalingQueue = new BusQueueReciever(config.ScalingQueueName, config.Connection); var eventReciever = new BusQueueReciever(config.EventsName, config.Connection); var bufferReciever = new BusQueueReciever(config.BufferedEventsName, config.Connection); //Initialize Service Bus yield return new InitializeBusQueue(pollReceiver); yield return new InitializeBusQueue(scalingQueue); yield return new InitializeBusQueue(eventReciever); yield return new InitializeBusQueue(bufferReciever); yield return new InitializeTopic(config.TopicName, config.Connection); //Polling Dequeue Runner yield return new AdaptiveRunner(new BusDequeue<ExampleModel>(pollReceiver, new ExampleProcessor())); //Task for watching for queue events yield return new BusEvents<ExampleModel>(eventReciever, new EventHandler()); //Task for recieving queue events to specific times yield return new BufferedReciever<ExampleModel>(bufferReciever, new EventHandler()); //Simulate messages being added to queues yield return new QueueForAction(new BusQueueSender(config.PollingName, config.Connection), "Poll"); yield return new QueueForAction(new BusQueueSender(config.EventsName, config.Connection), "Event"); yield return new QueueForBuffer(new BusQueueSender(config.BufferedEventsName, config.Connection)); //Auto Scaling Dequeue Task yield return new ScalableQueue(scalingQueue, config); } } }
mit
C#
2fc305acf43cccd15bb549335dc4caadd5f77e05
change the images to be with fixed size for more consistent view
SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListCategories.cshtml
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListCategories.cshtml
@model PagedList.IPagedList<AstroPhotoGallery.Models.Category> @using PagedList.Mvc; @using System.Linq; @{ ViewBag.Title = "List"; } <link href="~/Content/PagedList.css" rel="stylesheet" /> <div class="container"> <h2 class="text-center">Browse by categories</h2> <br/> @foreach (var category in Model) { <div class="col-sm-4"> <div class="thumbnail"> @if (category.Pictures.Any(p => p.CategoryId == category.Id)) { <img src="@Url.Content(category.Pictures.Where(p => p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="width: 360px; height:270px" > } else { <img src="~/Content/images/default-gallery-image.jpg" style="width: 360px; height:270px"/> } <div class="caption text-center "> <h4> @Html.ActionLink(string.Format($"{category.Name}({category.Pictures.Count})"), "ListPictures", "Home", new { @categoryId = category.Id }, null) </h4> </div> </div> </div> } </div> Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("ListCategories", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
@model PagedList.IPagedList<AstroPhotoGallery.Models.Category> @using PagedList.Mvc; @using System.Linq; @{ ViewBag.Title = "List"; } <link href="~/Content/PagedList.css" rel="stylesheet" /> <div class="container"> <h2 class="text-center">Browse by categories</h2> <br/> @foreach (var category in Model) { <div class="col-sm-4"> <div class="thumbnail "> @if (category.Pictures.Any(p => p.CategoryId == category.Id)) { <img src="@Url.Content(category.Pictures.Where(p => p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="height:190px;width:350px"> } else { <img src="~/Content/images/default-gallery-image.jpg" style="height:190px;width:350px" /> } <div class="caption text-center "> <h4> @Html.ActionLink(string.Format($"{category.Name}({category.Pictures.Count})"), "ListPictures", "Home", new { @categoryId = category.Id }, null) </h4> </div> </div> </div> } </div> Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("ListCategories", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
mit
C#
c19c819150ea34031b8dd705d892bb272525e50a
Remove comment
glav/CognitiveServicesFluentApi
Glav.CognitiveServices.FluentApi.Core/Configuration/ApiActionType.cs
Glav.CognitiveServices.FluentApi.Core/Configuration/ApiActionType.cs
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace Glav.CognitiveServices.FluentApi.Core.Configuration { public abstract class ApiActionDefinition { protected ApiActionDefinition() { } protected ApiActionDefinition(HttpMethod httpMethod, string apiCategory) { Method = httpMethod; Category = apiCategory; } public HttpMethod Method { get; private set; } public string Category { get; private set; } public string Name { get { return this.GetType().Name; } } public override bool Equals(object obj) { var definition = obj as ApiActionDefinition; return definition != null && EqualityComparer<HttpMethod>.Default.Equals(Method, definition.Method) && Category == definition.Category && Name == definition.GetType().Name; } public override int GetHashCode() { var hashCode = -343711391; hashCode = hashCode * -1521134295 + EqualityComparer<HttpMethod>.Default.GetHashCode(Method); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Category); return hashCode; } public static bool operator ==(ApiActionDefinition definition1, ApiActionDefinition definition2) { return EqualityComparer<ApiActionDefinition>.Default.Equals(definition1, definition2); } public static bool operator !=(ApiActionDefinition definition1, ApiActionDefinition definition2) { return !(definition1 == definition2); } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace Glav.CognitiveServices.FluentApi.Core.Configuration { public abstract class ApiActionDefinition { protected ApiActionDefinition() { } protected ApiActionDefinition(HttpMethod httpMethod, string apiCategory)//, ApiActionType actionType) { Method = httpMethod; Category = apiCategory; } public HttpMethod Method { get; private set; } public string Category { get; private set; } public string Name { get { return this.GetType().Name; } } public override bool Equals(object obj) { var definition = obj as ApiActionDefinition; return definition != null && EqualityComparer<HttpMethod>.Default.Equals(Method, definition.Method) && Category == definition.Category && Name == definition.GetType().Name; } public override int GetHashCode() { var hashCode = -343711391; hashCode = hashCode * -1521134295 + EqualityComparer<HttpMethod>.Default.GetHashCode(Method); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Category); return hashCode; } public static bool operator ==(ApiActionDefinition definition1, ApiActionDefinition definition2) { return EqualityComparer<ApiActionDefinition>.Default.Equals(definition1, definition2); } public static bool operator !=(ApiActionDefinition definition1, ApiActionDefinition definition2) { return !(definition1 == definition2); } } }
mit
C#
c7936a8f7a17ea440146fff3312896bb0174fb9c
Update AssemblyCompany
GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio
GoogleCloudExtension/GoogleCloudExtension/Properties/AssemblyInfo.cs
GoogleCloudExtension/GoogleCloudExtension/Properties/AssemblyInfo.cs
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.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("GoogleCloudExtension")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Cloud")] [assembly: AssemblyProduct("GoogleCloudExtension")] [assembly: AssemblyCopyright("Copyright \u00A9 Google Inc. 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)] // This version number matches the version in the .vsixmanifest. Please update both versions at the // same time. [assembly: AssemblyVersion("2.0.3.0")] [assembly: AssemblyFileVersion("2.0.3.0")] [assembly: InternalsVisibleTo( "GoogleCloudExtensionUnitTests," + "PublicKey=0024000004800000940000000602000000240000525341310004000001000" + "10043207bd13a1e2cbaef14c23664d17eada579bc4111e2f6acea01f6f704a96ae01cff" + "cbf06ee1c8a5c75192ec03378225422f4ceda32499dd8c35d1cc726beac43f7d231bdf5" + "5df8fe3806bf1cabd004a1c3c378da811fb1a237be8896456942bdd33f94d9f6a0f70ba" + "3f864993cb9639627cd6763b7fd2d2781a164331264dc9")] [assembly: InternalsVisibleTo( "DynamicProxyGenAssembly2," + "PublicKey=0024000004800000940000000602000000240000525341310004000001000" + "100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc073" + "4aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195" + "b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf" + "69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.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("GoogleCloudExtension")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc.")] [assembly: AssemblyProduct("GoogleCloudExtension")] [assembly: AssemblyCopyright("Copyright \u00A9 Google Inc. 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)] // This version number matches the version in the .vsixmanifest. Please update both versions at the // same time. [assembly: AssemblyVersion("2.0.3.0")] [assembly: AssemblyFileVersion("2.0.3.0")] [assembly: InternalsVisibleTo( "GoogleCloudExtensionUnitTests," + "PublicKey=0024000004800000940000000602000000240000525341310004000001000" + "10043207bd13a1e2cbaef14c23664d17eada579bc4111e2f6acea01f6f704a96ae01cff" + "cbf06ee1c8a5c75192ec03378225422f4ceda32499dd8c35d1cc726beac43f7d231bdf5" + "5df8fe3806bf1cabd004a1c3c378da811fb1a237be8896456942bdd33f94d9f6a0f70ba" + "3f864993cb9639627cd6763b7fd2d2781a164331264dc9")] [assembly: InternalsVisibleTo( "DynamicProxyGenAssembly2," + "PublicKey=0024000004800000940000000602000000240000525341310004000001000" + "100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc073" + "4aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195" + "b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf" + "69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
apache-2.0
C#
afcc0b99b5e4d647c42a273dad97d2b532091a3c
Fix SourceCodeUrl.
ejball/XmlDocMarkdown,ejball/ArgsReading
tools/Build/Build.cs
tools/Build/Build.cs
using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("ejball", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("ejball", "ejball@gmail.com"), SourceCodeUrl = "https://github.com/ejball/RepoName/tree/master/src", }, }); build.Target("default") .DependsOn("build"); }); }
using System; using Faithlife.Build; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { build.AddDotNetTargets( new DotNetBuildSettings { DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("ejball", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("ejball", "ejball@gmail.com"), SourceCodeUrl = "https://github.com/ejball/ArgsReading/tree/master/src", }, }); build.Target("default") .DependsOn("build"); }); }
mit
C#
7732eef2a24dcd9e029b5fc9d582b61b777e21c7
Implement SynchronousIOManager.GetDirectories
Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
src/Tgstation.Server.Host/Core/SynchronousIOManager.cs
src/Tgstation.Server.Host/Core/SynchronousIOManager.cs
using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class SynchronousIOManager : ISynchronousIOManager { /// <inheritdoc /> public IEnumerable<string> GetDirectories(string path, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); foreach (var I in Directory.EnumerateDirectories(path)) { yield return I; cancellationToken.ThrowIfCancellationRequested(); } } /// <inheritdoc /> public IEnumerable<string> GetFiles(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public byte[] ReadFile(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public bool WriteFileChecked(string path, byte[] data, string previousSha1, CancellationToken cancellationToken) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace Tgstation.Server.Host.Core { /// <inheritdoc /> sealed class SynchronousIOManager : ISynchronousIOManager { /// <inheritdoc /> public IEnumerable<string> GetDirectories(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public IEnumerable<string> GetFiles(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public byte[] ReadFile(string path, CancellationToken cancellationToken) { throw new NotImplementedException(); } /// <inheritdoc /> public bool WriteFileChecked(string path, byte[] data, string previousSha1, CancellationToken cancellationToken) { throw new NotImplementedException(); } } }
agpl-3.0
C#
2b94d8493dbf47e25cd146f92fc27119cd658dad
Update IRavenUnitOfWorkFactory.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/RavenDB/IRavenUnitOfWorkFactory.cs
TIKSN.Core/Data/RavenDB/IRavenUnitOfWorkFactory.cs
namespace TIKSN.Data.RavenDB { public interface IRavenUnitOfWorkFactory<TUnitOfWork> where TUnitOfWork : IUnitOfWork { TUnitOfWork Create(); } }
namespace TIKSN.Data.RavenDB { public interface IRavenUnitOfWorkFactory<TUnitOfWork> where TUnitOfWork : IUnitOfWork { TUnitOfWork Create(); } }
mit
C#
94b98a891bef12393346df7cea9a288954607d4b
allow location to be set externally
Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen
Dashen/AssetInfo.cs
Dashen/AssetInfo.cs
using System; using System.Collections.Generic; using System.Linq; namespace Dashen { public class AssetInfo { private const string SelfClosingFormat = "<{0} {1} />"; private const string NonClosingFormat = "<{0} {1}></{0}>"; public string Tag { get; protected set; } public bool SelfClosing { get; protected set; } public AssetLocations Location { get; set; } private readonly Dictionary<string, string> _attributes; private readonly Lazy<string> _tag; public AssetInfo() { _attributes = new Dictionary<string, string>(); _tag = new Lazy<string>(BuildTag); } public void AddAttribute(string name, string value) { _attributes[name] = value; } private string BuildTag() { var format = SelfClosing ? SelfClosingFormat : NonClosingFormat; return string.Format( format, Tag, BuildAttributes()); } private string BuildAttributes() { var format = "{0}=\"{1}\""; return _attributes .Select(pair => string.Format(format, pair.Key, pair.Value)) .Aggregate((a, c) => a + " " + c); } public override string ToString() { return _tag.Value; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Dashen { public class AssetInfo { private const string SelfClosingFormat = "<{0} {1} />"; private const string NonClosingFormat = "<{0} {1}></{0}>"; public string Tag { get; protected set; } public bool SelfClosing { get; protected set; } public AssetLocations Location { get; protected set; } private readonly Dictionary<string, string> _attributes; private readonly Lazy<string> _tag; public AssetInfo() { _attributes = new Dictionary<string, string>(); _tag = new Lazy<string>(BuildTag); } public void AddAttribute(string name, string value) { _attributes[name] = value; } private string BuildTag() { var format = SelfClosing ? SelfClosingFormat : NonClosingFormat; return string.Format( format, Tag, BuildAttributes()); } private string BuildAttributes() { var format = "{0}=\"{1}\""; return _attributes .Select(pair => string.Format(format, pair.Key, pair.Value)) .Aggregate((a, c) => a + " " + c); } public override string ToString() { return _tag.Value; } } }
lgpl-2.1
C#
fa6740d8c8fb4f893aa895415ea0d91012c9199c
Fix Properties Initialize
dreign/ComBoost,dreign/ComBoost
Wodsoft.ComBoost/ComponentModel/EntityEditModel.cs
Wodsoft.ComBoost/ComponentModel/EntityEditModel.cs
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Metadata; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.ComponentModel { /// <summary> /// Entity edit model. /// </summary> public class EntityEditModel : NotifyBase { /// <summary> /// Get or set the item to edit. /// </summary> public IEntity Item { get { return (IEntity)GetValue("Item"); } set { SetValue("Item", value); } } /// <summary> /// Get or set the properties to edit. /// </summary> public PropertyMetadata[] Properties { get { return (PropertyMetadata[])GetValue("Properties"); } set { SetValue("Properties", value); } } /// <summary> /// Get or set the metadata of entity. /// </summary> public EntityMetadata Metadata { get; set; } } /// <summary> /// Entity edit model. /// </summary> /// <typeparam name="TEntity">Type of Entity.</typeparam> public class EntityEditModel<TEntity> : EntityEditModel where TEntity : IEntity { /// <summary> /// Initialize entity edit model. /// </summary> /// <param name="entity">Entity to edit.</param> public EntityEditModel(TEntity entity) { Item = entity; Metadata = EntityAnalyzer.GetMetadata<TEntity>(); Properties = Metadata.EditProperties; } /// <summary> /// Get or set the properties to edit. /// </summary> public new TEntity Item { get { return (TEntity)base.Item; } set { base.Item = value; } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Metadata; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.ComponentModel { /// <summary> /// Entity edit model. /// </summary> public class EntityEditModel : NotifyBase { /// <summary> /// Get or set the item to edit. /// </summary> public IEntity Item { get { return (IEntity)GetValue("Item"); } set { SetValue("Item", value); } } /// <summary> /// Get or set the properties to edit. /// </summary> public PropertyMetadata[] Properties { get { return (PropertyMetadata[])GetValue("Properties"); } set { SetValue("Properties", value); } } /// <summary> /// Get or set the metadata of entity. /// </summary> public EntityMetadata Metadata { get; set; } } /// <summary> /// Entity edit model. /// </summary> /// <typeparam name="TEntity">Type of Entity.</typeparam> /// <typeparam name="TKey">Type of key of entity.</typeparam> public class EntityEditModel<TEntity> : EntityEditModel where TEntity : IEntity { /// <summary> /// Initialize entity edit model. /// </summary> /// <param name="entity">Entity to edit.</param> public EntityEditModel(TEntity entity) { Item = entity; Metadata = EntityAnalyzer.GetMetadata<TEntity>(); } /// <summary> /// Get or set the properties to edit. /// </summary> public new TEntity Item { get { return (TEntity)base.Item; } set { base.Item = value; } } } }
mit
C#
477a46400c32d04c0e0c3e878ec545cf4d6f631f
Add source documentation for watchlist item.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Get/Watchlist/TraktWatchlistItem.cs
Source/Lib/TraktApiSharp/Objects/Get/Watchlist/TraktWatchlistItem.cs
namespace TraktApiSharp.Objects.Get.Watchlist { using Attributes; using Enums; using Movies; using Newtonsoft.Json; using Shows; using Shows.Episodes; using Shows.Seasons; using System; /// <summary>A Trakt watchlist item, containing a movie, show, season and / or episode and information about it.</summary> public class TraktWatchlistItem { /// <summary>Gets or sets the UTC datetime, when the movie, show, season and / or episode was listed.</summary> [JsonProperty(PropertyName = "listed_at")] public DateTime? ListedAt { get; set; } /// <summary> /// Gets or sets the object type, which this watchlist item contains. /// See also <seealso cref="TraktSyncItemType" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "type")] [JsonConverter(typeof(TraktEnumerationConverter<TraktSyncItemType>))] [Nullable] public TraktSyncItemType Type { get; set; } /// <summary> /// Gets or sets the movie, if <see cref="Type" /> is <see cref="TraktSyncItemType.Movie" />. /// See also <seealso cref="TraktMovie" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "movie")] [Nullable] public TraktMovie Movie { get; set; } /// <summary> /// Gets or sets the show, if <see cref="Type" /> is <see cref="TraktSyncItemType.Show" />. /// May also be set, if <see cref="Type" /> is <see cref="TraktSyncItemType.Episode" /> or /// <see cref="TraktSyncItemType.Season" />. /// <para>See also <seealso cref="TraktShow" />.</para> /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "show")] [Nullable] public TraktShow Show { get; set; } /// <summary> /// Gets or sets the season, if <see cref="Type" /> is <see cref="TraktSyncItemType.Season" />. /// See also <seealso cref="TraktSeason" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "season")] [Nullable] public TraktSeason Season { get; set; } /// <summary> /// Gets or sets the episode, if <see cref="Type" /> is <see cref="TraktSyncItemType.Episode" />. /// See also <seealso cref="TraktEpisode" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "episode")] [Nullable] public TraktEpisode Episode { get; set; } } }
namespace TraktApiSharp.Objects.Get.Watchlist { using Attributes; using Enums; using Movies; using Newtonsoft.Json; using Shows; using Shows.Episodes; using Shows.Seasons; using System; public class TraktWatchlistItem { [JsonProperty(PropertyName = "listed_at")] public DateTime? ListedAt { get; set; } [JsonProperty(PropertyName = "type")] [JsonConverter(typeof(TraktEnumerationConverter<TraktSyncItemType>))] [Nullable] public TraktSyncItemType Type { get; set; } [JsonProperty(PropertyName = "movie")] [Nullable] public TraktMovie Movie { get; set; } [JsonProperty(PropertyName = "show")] [Nullable] public TraktShow Show { get; set; } [JsonProperty(PropertyName = "season")] [Nullable] public TraktSeason Season { get; set; } [JsonProperty(PropertyName = "episode")] [Nullable] public TraktEpisode Episode { get; set; } } }
mit
C#
05de51c0f139d19dd8455200fd1348430745b6e7
Change method to static
tusdotnet/tusdotnet,tusdotnet/tusdotnet,tusdotnet/tusdotnet,tusdotnet/tusdotnet
Source/tusdotnet/Validation/Requirements/UploadLengthForWriteFile.cs
Source/tusdotnet/Validation/Requirements/UploadLengthForWriteFile.cs
using System.Threading.Tasks; using tusdotnet.Adapters; using tusdotnet.Constants; using tusdotnet.Interfaces; using tusdotnet.Models; namespace tusdotnet.Validation.Requirements { internal sealed class UploadLengthForWriteFile : Requirement { public override async Task Validate(ContextAdapter context) { var uploadLengthIsSet = await UploadLengthIsAlreadyPresent(context); var supportsUploadDeferLength = context.Configuration.Store is ITusCreationDeferLengthStore; if (!supportsUploadDeferLength && !uploadLengthIsSet) { throw new TusConfigurationException($"File {context.Request.FileId} does not have an upload length and the current store ({context.Configuration.Store.GetType().FullName}) does not support Upload-Defer-Length so no new upload length can be set"); } if (!UploadLengthIsProvidedInRequest(context.Request) && !uploadLengthIsSet) { await BadRequest($"Header {HeaderConstants.UploadLength} must be specified as this file was created using Upload-Defer-Length"); return; } if (UploadLengthIsProvidedInRequest(context.Request) && uploadLengthIsSet) { await BadRequest($"{HeaderConstants.UploadLength} cannot be updated once set"); } } private static async Task<bool> UploadLengthIsAlreadyPresent(ContextAdapter context) { var fileUploadLength = await context.Configuration.Store.GetUploadLengthAsync(context.Request.FileId, context.CancellationToken); return fileUploadLength != null; } private static bool UploadLengthIsProvidedInRequest(RequestAdapter request) { return request.Headers.ContainsKey(HeaderConstants.UploadLength); } } }
using System.Threading.Tasks; using tusdotnet.Adapters; using tusdotnet.Constants; using tusdotnet.Interfaces; using tusdotnet.Models; namespace tusdotnet.Validation.Requirements { internal sealed class UploadLengthForWriteFile : Requirement { public override async Task Validate(ContextAdapter context) { var uploadLengthIsSet = await UploadLengthIsAlreadyPresent(context); var supportsUploadDeferLength = context.Configuration.Store is ITusCreationDeferLengthStore; if (!supportsUploadDeferLength && !uploadLengthIsSet) { throw new TusConfigurationException($"File {context.Request.FileId} does not have an upload length and the current store ({context.Configuration.Store.GetType().FullName}) does not support Upload-Defer-Length so no new upload length can be set"); } if (!UploadLengthIsProvidedInRequest(context.Request) && !uploadLengthIsSet) { await BadRequest($"Header {HeaderConstants.UploadLength} must be specified as this file was created using Upload-Defer-Length"); return; } if (UploadLengthIsProvidedInRequest(context.Request) && uploadLengthIsSet) { await BadRequest($"{HeaderConstants.UploadLength} cannot be updated once set"); } } private async Task<bool> UploadLengthIsAlreadyPresent(ContextAdapter context) { var fileUploadLength = await context.Configuration.Store.GetUploadLengthAsync(context.Request.FileId, context.CancellationToken); return fileUploadLength != null; } private static bool UploadLengthIsProvidedInRequest(RequestAdapter request) { return request.Headers.ContainsKey(HeaderConstants.UploadLength); } } }
mit
C#
be432a81fb7a12a5a567af165d9ef9c3bca7ba9c
Fix user deletion (#6879)
xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.Users/Views/UserButtons.cshtml
src/OrchardCore.Modules/OrchardCore.Users/Views/UserButtons.cshtml
@model SummaryAdminUserViewModel @using OrchardCore.Entities @using OrchardCore.Users.Models @{ var user = Model.User as User; var currentUser = user.UserName == User.Identity.Name; } <a asp-action="Edit" asp-route-id="@user.Id" class="btn btn-primary btn-sm">@T["Edit"]</a> <a class="btn btn-danger btn-sm @(currentUser ? "disabled" : "")" asp-action="Delete" asp-route-id="@user.Id" itemprop="RemoveUrl UnsafeUrl">@T["Delete"]</a> <a asp-action="EditPassword" asp-route-id="@user.Id" class="btn btn-secondary btn-sm">@T["Edit Password"]</a> @if (!user.EmailConfirmed && Site.As<RegistrationSettings>().UsersMustValidateEmail) { <form method="post" class="d-inline-block"> <input name="id" type="hidden" value="@user.Id" /> <button asp-action="SendVerificationEmail" asp-controller="Registration" class="btn btn-info btn-sm">@T["Send verification email"]</button> </form> }
@model SummaryAdminUserViewModel @using OrchardCore.Entities @using OrchardCore.Users.Models @{ var user = Model.User as User; var currentUser = user.UserName == User.Identity.Name; } <a asp-action="Edit" asp-route-id="@user.Id" class="btn btn-primary btn-sm">@T["Edit"]</a> <a class="btn btn-danger btn-sm @(currentUser ? "disabled" : "")" asp-route-id="@user.Id" itemprop="RemoveUrl UnsafeUrl">@T["Delete"]</a> <a asp-action="EditPassword" asp-route-id="@user.Id" class="btn btn-secondary btn-sm">@T["Edit Password"]</a> @if (!user.EmailConfirmed && Site.As<RegistrationSettings>().UsersMustValidateEmail) { <form method="post" class="d-inline-block"> <input name="id" type="hidden" value="@user.Id" /> <button asp-action="SendVerificationEmail" asp-controller="Registration" class="btn btn-info btn-sm">@T["Send verification email"]</button> </form> }
bsd-3-clause
C#
46c0a998996fae9920c85352d869ed2a19bf2405
Make OnPreKeyEvent isKeyboardShortcut a ref param
Livit/CefSharp,AJDev77/CefSharp,battewr/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,zhangjingpu/CefSharp,VioletLife/CefSharp,dga711/CefSharp,Haraguroicha/CefSharp,Livit/CefSharp,NumbersInternational/CefSharp,VioletLife/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,ruisebastiao/CefSharp,haozhouxu/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,joshvera/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,AJDev77/CefSharp,windygu/CefSharp,Haraguroicha/CefSharp,Haraguroicha/CefSharp,NumbersInternational/CefSharp,VioletLife/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,dga711/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,windygu/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,NumbersInternational/CefSharp,dga711/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,rlmcneary2/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,twxstar/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,windygu/CefSharp,twxstar/CefSharp,battewr/CefSharp,twxstar/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,ruisebastiao/CefSharp,twxstar/CefSharp,battewr/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,yoder/CefSharp,illfang/CefSharp,illfang/CefSharp,joshvera/CefSharp,dga711/CefSharp,gregmartinhtc/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp
CefSharp/IKeyboardHandler.cs
CefSharp/IKeyboardHandler.cs
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IKeyboardHandler { bool OnKeyEvent(IWebBrowser browser, KeyType type, int code, CefEventFlags modifiers, bool isSystemKey); bool OnPreKeyEvent(IWebBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut); } }
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IKeyboardHandler { bool OnKeyEvent(IWebBrowser browser, KeyType type, int code, CefEventFlags modifiers, bool isSystemKey); bool OnPreKeyEvent(IWebBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, bool isKeyboardShortcut); } }
bsd-3-clause
C#
ab36396ecf579adcb1167983fcd6249cb2259945
Add to GLFW
vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSharpGameLibrary/GLFW/GLFW.cs
CSharpGameLibrary/GLFW/GLFW.cs
using System; using System.Collections.Generic; using CSGL.Input; using UGLFW = CSGL.GLFW.Unmanaged.GLFW; namespace CSGL.GLFW { public static class GLFW { public static string Version { get; private set; } public static int VersionMajor { get; private set; } public static int VersionMinor { get; private set; } public static int VersionPatch { get; private set; } public static IList<Monitor> Monitors { get { return Monitor.Monitors; } } public static bool Init() { bool result = UGLFW.Init(); Version = UGLFW.GetVersion(); int major, minor, revision; UGLFW.GetVersion(out major, out minor, out revision); VersionMajor = major; VersionMinor = minor; VersionPatch = revision; Monitor.Init(); return result; } public static void Terminate() { UGLFW.Terminate(); } public static void SwapInterval(int interval) { UGLFW.SwapInterval(interval); } public static void WindowHint(WindowHint hint, int value) { UGLFW.WindowHint(hint, value); } public static void DefaultWindowHints() { UGLFW.DefaultWindowHints(); } public static void PollEvents() { UGLFW.PollEvents(); } } }
using System; using System.Collections.Generic; using CSGL.Input; using glfw = CSGL.GLFW.Unmanaged.GLFW; namespace CSGL.GLFW { public static class GLFW { public static string Version { get; private set; } public static int VersionMajor { get; private set; } public static int VersionMinor { get; private set; } public static int VersionPatch { get; private set; } public static IList<Monitor> Monitors { get { return Monitor.Monitors; } } public static bool Init() { bool result = glfw.Init(); Version = glfw.GetVersion(); int major, minor, revision; glfw.GetVersion(out major, out minor, out revision); VersionMajor = major; VersionMinor = minor; VersionPatch = revision; Monitor.Init(); return result; } public static void Terminate() { glfw.Terminate(); } } }
mit
C#
6338b72e8adfc76ec7e2f1d825420a2815afd0f5
handle debugging both x86/x64
ITGlobal/CefSharp,illfang/CefSharp,yoder/CefSharp,dga711/CefSharp,Livit/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,NumbersInternational/CefSharp,zhangjingpu/CefSharp,wangzheng888520/CefSharp,Livit/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,haozhouxu/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,VioletLife/CefSharp,rover886/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,twxstar/CefSharp,windygu/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,rlmcneary2/CefSharp,twxstar/CefSharp,yoder/CefSharp,gregmartinhtc/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,dga711/CefSharp,twxstar/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,Octopus-ITSM/CefSharp,zhangjingpu/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,windygu/CefSharp,VioletLife/CefSharp,battewr/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,joshvera/CefSharp,battewr/CefSharp,ruisebastiao/CefSharp,wangzheng888520/CefSharp,NumbersInternational/CefSharp,Octopus-ITSM/CefSharp,Livit/CefSharp,Livit/CefSharp,zhangjingpu/CefSharp,rover886/CefSharp,joshvera/CefSharp,haozhouxu/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,dga711/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,VioletLife/CefSharp,windygu/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,haozhouxu/CefSharp,twxstar/CefSharp,rover886/CefSharp,ITGlobal/CefSharp
CefSharp.Example/CefExample.cs
CefSharp.Example/CefExample.cs
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/home"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = false; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; settings.LogSeverity = LogSeverity.Verbose; if (debuggingSubProcess) { var platform = IntPtr.Size == 4 ? "x86" : "x64"; settings.BrowserSubprocessPath = string.Format( "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\{0}\\Debug\\CefSharp.BrowserSubprocess.exe", platform); } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } Cef.RegisterJsObject("bound", new BoundObject()); } } }
using System; using System.Linq; namespace CefSharp.Example { public static class CefExample { public const string DefaultUrl = "custom://cefsharp/home"; // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work. private const bool debuggingSubProcess = false; public static void Init() { var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; settings.LogSeverity = LogSeverity.Verbose; if (debuggingSubProcess) { settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe"; } settings.RegisterScheme(new CefCustomScheme { SchemeName = CefSharpSchemeHandlerFactory.SchemeName, SchemeHandlerFactory = new CefSharpSchemeHandlerFactory() }); if (!Cef.Initialize(settings)) { if (Environment.GetCommandLineArgs().Contains("--type=renderer")) { Environment.Exit(0); } else { return; } } Cef.RegisterJsObject("bound", new BoundObject()); } } }
bsd-3-clause
C#
67d3d6e9d3dbca013c7c6048fa491eda4699fc5c
use statement body
borismod/FinBotApp,idoban/FinBotApp,idoban/FinBotApp,borismod/FinBotApp
FinBot/Engine/BaseAdapter.cs
FinBot/Engine/BaseAdapter.cs
using System.Xml.Linq; using Syn.Bot.Siml; using Syn.Bot.Siml.Interfaces; namespace FinBot.Engine { public abstract class BaseAdapter : IAdapter { public bool IsRecursive { get { return true; } } private string Name { get { return GetType().Name.Replace("Adapter", string.Empty); } } public XName TagName { get { XNamespace ns = "http://finbot.com/namespace#finbot"; return ns + Name; } } public abstract string Evaluate(Context context); } }
using System.Xml.Linq; using Syn.Bot.Siml; using Syn.Bot.Siml.Interfaces; namespace FinBot.Engine { public abstract class BaseAdapter : IAdapter { public bool IsRecursive => true; private string Name { get { return GetType().Name.Replace("Adapter", string.Empty); } } public XName TagName { get { XNamespace ns = "http://finbot.com/namespace#finbot"; return ns + Name; } } public abstract string Evaluate(Context context); } }
mit
C#
a0e52cf92b1b4acdfae7375be41426f1cae5fe67
Update the version and description
Haacked/Scientist.net
src/Scientist/Properties/AssemblyInfo.cs
src/Scientist/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("Scientist")] [assembly: AssemblyDescription("A .NET library for carefully refactoring critical paths. It's a port of GitHub's Ruby Scientist library.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyProduct("Scientist")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("89039ba2-9f7d-4aef-b0a8-46935cf3e678")] // 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: AssemblyInformationalVersionAttribute("1.0.0-alpha3")]
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("Scientist")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Scientist")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("89039ba2-9f7d-4aef-b0a8-46935cf3e678")] // 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: AssemblyInformationalVersionAttribute("1.0.0-alpha2")]
mit
C#
a2469e3b3e38bd5997d94db12d735d80971ff87b
add seo TwitterCards
fguini/leathergoods,fguini/leathergoods,fguini/leathergoods
Shared/Framework/Seo/TwitterCard.cs
Shared/Framework/Seo/TwitterCard.cs
using System; using Framework.Extensions; namespace Framework.Seo { public class TwitterCard { private static string TwCard() { return $"<meta property=\"twitter:card\" content=\"summary\">"; } private static string TwSiteName(string twSiteName) { return $"<meta property=\"twitter:site\" content=\"{twSiteName}\">"; } private static string TwTitle(string twTitle) { return $"<meta property=\"twitter:title\" content=\"{twTitle}\">"; } private static string TwDescription(string twDescription) { string safeDescription = twDescription.StripTags().Truncate(140); return $"<meta property=\"twitter:description\" content=\"{safeDescription}\">"; } private static string TwImage(string twImageUrl) { return $"<meta property=\"twitter:image\" content=\"{twImageUrl}\">"; } private static string TwUrl(string twUrl) { return $"<meta property=\"twitter:url\" content=\"{twUrl}\">"; } public static string Build ( string twSiteName, string twTitle, string twDescription, string twImageUrl, string twUrl ) { return $@" {TwCard()} {TwSiteName(twSiteName)} {TwTitle(twTitle)} {TwDescription(twDescription)} {TwImage(twImageUrl)} {TwUrl(twUrl)}"; } } }
using System; namespace Framework.Seo { public class TwitterCard { } }
mit
C#
089bab89eeebb6a0dfb374645f9300d7d36fa06f
improve error message for l0 test.
kasubram/vsts-agent,kasubram/vsts-agent,kasubram/vsts-agent,Microsoft/vsts-agent,Microsoft/vsts-agent,kasubram/vsts-agent,lkillgore/vsts-agent,lkillgore/vsts-agent,Microsoft/vsts-agent,Microsoft/vsts-agent,lkillgore/vsts-agent,lkillgore/vsts-agent
src/Test/L0/DotnetsdkDownloadScriptL0.cs
src/Test/L0/DotnetsdkDownloadScriptL0.cs
using Xunit; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent.Tests { public sealed class DotnetsdkDownloadScriptL0 { [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async Task EnsureDotnetsdkDownloadScriptUpToDate() { string shDownloadUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.sh"; string ps1DownloadUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1"; using (HttpClient downloadClient = new HttpClient()) { var response = await downloadClient.GetAsync("https://www.bing.com"); if (!response.IsSuccessStatusCode) { return; } string shScript = await downloadClient.GetStringAsync(shDownloadUrl); string ps1Script = await downloadClient.GetStringAsync(ps1DownloadUrl); string existingShScript = File.ReadAllText(Path.Combine(TestUtil.GetSrcPath(), "Misc/dotnet-install.sh")); string existingPs1Script = File.ReadAllText(Path.Combine(TestUtil.GetSrcPath(), "Misc/dotnet-install.ps1")); bool shScriptMatched = string.Equals(shScript.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"), existingShScript.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n")); Assert.True(shScriptMatched, "Fix the test by updating Src/Misc/dotnet-install.sh with content from https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.sh"); bool ps1ScriptMatched = string.Equals(ps1Script.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"), existingPs1Script.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n")); Assert.True(ps1ScriptMatched, "Fix the test by updating Src/Misc/dotnet-install.sh with content from https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1"); } } } }
using Xunit; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent.Tests { public sealed class DotnetsdkDownloadScriptL0 { [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async Task EnsureDotnetsdkDownloadScriptUpToDate() { string shDownloadUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.sh"; string ps1DownloadUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1"; using(HttpClient downloadClient = new HttpClient()) { var response = await downloadClient.GetAsync("https://www.bing.com"); if(!response.IsSuccessStatusCode) { return; } string shScript = await downloadClient.GetStringAsync(shDownloadUrl); string ps1Script = await downloadClient.GetStringAsync(ps1DownloadUrl); string existingShScript = File.ReadAllText(Path.Combine(TestUtil.GetSrcPath(),"Misc/dotnet-install.sh")); string existingPs1Script = File.ReadAllText(Path.Combine(TestUtil.GetSrcPath(),"Misc/dotnet-install.ps1")); Assert.Equal(shScript.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"), existingShScript.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n")); Assert.Equal(ps1Script.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"), existingPs1Script.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n")); } } } }
mit
C#
ecf622999b806a0859bf4686c132a0b055ab712c
Fix missing name change
ahockersten/ScrollsUserMenuInChat
UserMenuInChat.mod/Properties/AssemblyInfo.cs
UserMenuInChat.mod/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("UserMenuInChat")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Anders Hckersten")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
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("RightClickInChat")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Anders Hckersten")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
bsd-2-clause
C#
4a052a67bb8db9e74913bf4ecc67888cf78ae66e
Bump v1.0.23
karronoli/tiny-sato
TinySato/Properties/AssemblyInfo.cs
TinySato/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.23.*")] [assembly: AssemblyFileVersion("1.0.23")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TinySato")] [assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinySato")] [assembly: AssemblyCopyright("Copyright 2016 karronoli")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: [assembly: AssemblyVersion("1.0.22.*")] [assembly: AssemblyFileVersion("1.0.22")]
apache-2.0
C#
6baeb0daf74b66db0de24348149907b2b4a7d87e
test fail commit for appveyor
v-braun/VBR-UnixTime
VBR.UnixTime.Tests/UnixTimeTests.cs
VBR.UnixTime.Tests/UnixTimeTests.cs
using System; using Xunit; namespace VBR{ public class UnixTimeTests{ private readonly string _unixEpochFormat = "1970-01-{0:00}T{1:00}:{2:00}:{3:00}:{4:000}"; private readonly string _assertFormat = "yyyy-MM-ddTHH:mm:ss:fff"; [Fact] public void FromElapsedMillisecondsTest(){ var ms = 300; var actual = UnixTime.FromElapsedMilliseconds(ms); Assert.Equal(string.Format(_unixEpochFormat, 1, 0, 0, 0, ms), actual.ToString(_assertFormat)); } [Fact] public void FromElapsedSecondsTest(){ var s = 64; var actual = UnixTime.FromElapsedSecods(s); Assert.True(false); Assert.Equal(string.Format(_unixEpochFormat, 1, 0, 1, 4, 0), actual.ToString(_assertFormat)); } [Fact] public void FromElapsedMinutesTest(){ var m = 72; var actual = UnixTime.FromElapsedMinutes(m); Assert.Equal(string.Format(_unixEpochFormat, 1, 1, 12, 0, 0), actual.ToString(_assertFormat)); } [Fact] public void FromElapsedMinutesHours(){ var h = 27; var actual = UnixTime.FromElapsedHours(h); Assert.Equal(string.Format(_unixEpochFormat, 2, 3, 0, 0, 0), actual.ToString(_assertFormat)); } } }
using System; using Xunit; namespace VBR{ public class UnixTimeTests{ private readonly string _unixEpochFormat = "1970-01-{0:00}T{1:00}:{2:00}:{3:00}:{4:000}"; private readonly string _assertFormat = "yyyy-MM-ddTHH:mm:ss:fff"; [Fact] public void FromElapsedMillisecondsTest(){ var ms = 300; var actual = UnixTime.FromElapsedMilliseconds(ms); Assert.Equal(string.Format(_unixEpochFormat, 1, 0, 0, 0, ms), actual.ToString(_assertFormat)); } [Fact] public void FromElapsedSecondsTest(){ var s = 64; var actual = UnixTime.FromElapsedSecods(s); Assert.Equal(string.Format(_unixEpochFormat, 1, 0, 1, 4, 0), actual.ToString(_assertFormat)); } [Fact] public void FromElapsedMinutesTest(){ var m = 72; var actual = UnixTime.FromElapsedMinutes(m); Assert.Equal(string.Format(_unixEpochFormat, 1, 1, 12, 0, 0), actual.ToString(_assertFormat)); } [Fact] public void FromElapsedMinutesHours(){ var h = 27; var actual = UnixTime.FromElapsedHours(h); Assert.Equal(string.Format(_unixEpochFormat, 2, 3, 0, 0, 0), actual.ToString(_assertFormat)); } } }
mit
C#
afe7abdb775cc1d12bdaefc5d5f9dbcc2fcdf089
Update ApplicationInsightsTraceTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsTraceTelemeter.cs
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsTraceTelemeter.cs
using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.ApplicationInsights.DataContracts; namespace TIKSN.Analytics.Telemetry { public class ApplicationInsightsTraceTelemeter : ITraceTelemeter { public Task TrackTrace(string message, TelemetrySeverityLevel severityLevel) => this.TrackTraceInternal(message, severityLevel); public Task TrackTrace(string message) => this.TrackTraceInternal(message, null); private Task TrackTraceInternal(string message, TelemetrySeverityLevel? severityLevel) { try { var telemetry = new TraceTelemetry(message); telemetry.SeverityLevel = ApplicationInsightsHelper.ConvertSeverityLevel(severityLevel); ApplicationInsightsHelper.TrackTrace(telemetry); } catch (Exception ex) { Debug.WriteLine(ex); } return Task.FromResult<object>(null); } } }
using Microsoft.ApplicationInsights.DataContracts; using System; using System.Diagnostics; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public class ApplicationInsightsTraceTelemeter : ITraceTelemeter { public Task TrackTrace(string message, TelemetrySeverityLevel severityLevel) { return TrackTraceInternal(message, severityLevel); } public Task TrackTrace(string message) { return TrackTraceInternal(message, null); } private Task TrackTraceInternal(string message, TelemetrySeverityLevel? severityLevel) { try { var telemetry = new TraceTelemetry(message); telemetry.SeverityLevel = ApplicationInsightsHelper.ConvertSeverityLevel(severityLevel); ApplicationInsightsHelper.TrackTrace(telemetry); } catch (Exception ex) { Debug.WriteLine(ex); } return Task.FromResult<object>(null); } } }
mit
C#
e7dee88cae7464f1db814bad2c9cbbd037430e6b
Add HalLinkCollection::HasLink
Xerosigma/halclient
HALClient/HalLinkCollection.cs
HALClient/HalLinkCollection.cs
using System.Collections.Generic; using System.Linq; namespace Ecom.Hal { public class HalLinkCollection : List<HalLink> { public HalLink GetLink(string rel) { return (from link in this where link.Rel == rel select link).FirstOrDefault(); } public bool HasLink(string rel) { return this.Any(l => l.Rel == rel); } } }
using System.Collections.Generic; using System.Linq; namespace Ecom.Hal { public class HalLinkCollection : List<HalLink> { public HalLink GetLink(string rel) { return (from link in this where link.Rel == rel select link).FirstOrDefault(); } } }
apache-2.0
C#
00d444cc9835ad70b88c69b8659cc0d1e1ca15b6
refactor AI
MasakiMuto/LifegameGame
LifegameGame/MinMaxPlayer.cs
LifegameGame/MinMaxPlayer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace LifegameGame { using PointScoreDictionary = Dictionary<Point, float>; public class MinMaxPlayer : Player { public MinMaxPlayer(GameBoard board, CellState side) : base(board, side) { } public override bool Update() { Play(Think(1)); return true; } /// <summary> /// 最善手を考える /// </summary> /// <param name="depth">ツリーを展開する最大深さ</param> /// <returns></returns> Point Think(int depth) { var currentScore = Board.EvalScore(); var watch = new Stopwatch(); watch.Start(); var list = new PointScoreDictionary(); foreach (var p in GetPlayablePoints()) { if (Board.CanPlay(p)) { var b = Board.VirtualPlay(Side, p); float score = Board.EvalScore(); //if (this.Side == CellState.Black) //{ // score *= -1; //} list[p] = score; Board.SetBoardOrigin(); } } var res = this.Side == CellState.White ? GetMaxPoint(list) : GetMinPoint(list); watch.Stop(); Trace.WriteLine("MinMax Thinking Time=" + watch.Elapsed.ToString()); //Trace.WriteLine("I play " + res.Key.ToString()); //Trace.WriteLine(String.Format("Score {0}→{1}", currentScore, res.Value)); return res.Key; } IEnumerable<Point> GetPlayablePoints() { return Enumerable.Range(0, Board.Size).SelectMany(x => Enumerable.Range(0, Board.Size) .Select(y => new Point(x, y)) .Where(p => Board.CanPlay(p)) ); } /// <summary> /// そこに打った時の評価値の計算 /// </summary> /// <param name="p"></param> /// <param name="isMin">minを求めるならtrue</param> float EvalPosition(BoardInstance board, Point p, int depth) { Board.PlayingBoard = board; Debug.Assert(Board.CanPlay(p)); if (depth == 1) { return Board.EvalScore(); } else { } throw new NotImplementedException(); } KeyValuePair<Point, float> GetMaxPoint(PointScoreDictionary dict) { KeyValuePair<Point, float> p = dict.First(); foreach (var item in dict) { if (item.Value > p.Value) { p = item; } } return p; } KeyValuePair<Point, float> GetMinPoint(PointScoreDictionary dict) { KeyValuePair<Point, float> p = dict.First(); foreach (var item in dict) { if (item.Value < p.Value) { p = item; } } return p; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace LifegameGame { using PointScoreDictionary = Dictionary<Point, float>; public class MinMaxPlayer : Player { public MinMaxPlayer(GameBoard board, CellState side) : base(board, side) { } public override bool Update() { Play(Think(1)); return true; } /// <summary> /// /// </summary> /// <param name="depth">ツリーを展開する最大深さ</param> /// <returns></returns> Point Think(int depth) { var currentScore = Board.EvalScore(); var watch = new Stopwatch(); watch.Start(); var list = new PointScoreDictionary(); for (int i = 0; i < Board.Size; i++) { for (int j = 0; j < Board.Size; j++) { var p = new Point(i, j); if (Board.CanPlay(p)) { var b = Board.VirtualPlay(Side, p); float score = Board.EvalScore(); //if (this.Side == CellState.Black) //{ // score *= -1; //} list[p] = score; Board.SetBoardOrigin(); } } } var res = this.Side == CellState.White ? GetMaxPoint(list) : GetMinPoint(list); watch.Stop(); Trace.WriteLine("MinMax Thinking Time=" + watch.Elapsed.ToString()); //Trace.WriteLine("I play " + res.Key.ToString()); //Trace.WriteLine(String.Format("Score {0}→{1}", currentScore, res.Value)); return res.Key; } KeyValuePair<Point, float> GetMaxPoint(PointScoreDictionary dict) { KeyValuePair<Point, float> p = dict.First(); foreach (var item in dict) { if (item.Value > p.Value) { p = item; } } return p; } KeyValuePair<Point, float> GetMinPoint(PointScoreDictionary dict) { KeyValuePair<Point, float> p = dict.First(); foreach (var item in dict) { if (item.Value < p.Value) { p = item; } } return p; } } }
mit
C#
6cfa4403ccb8080b30b52913faf25d733f207103
Fix StyleCop violation
MultimediaSolutionsAg/ServiceBus
source/MMS.ServiceBus/Pipeline/Outgoing/OutgoingPipelineFactory.cs
source/MMS.ServiceBus/Pipeline/Outgoing/OutgoingPipelineFactory.cs
//------------------------------------------------------------------------------- // <copyright file="OutgoingPipelineFactory.cs" company="MMS AG"> // Copyright (c) MMS AG, 2008-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus.Pipeline.Outgoing { using System.Threading.Tasks; using Microsoft.ServiceBus.Messaging; public class OutgoingPipelineFactory : IOutgoingPipelineFactory { private readonly MessagingFactory factory; private readonly IMessageRouter router; private readonly IMessageSerializer serializer; private MessageSender sender; private MessagePublisher publisher; public OutgoingPipelineFactory(MessagingFactory factory, IMessageRouter router, IMessageSerializer serializer) { this.router = router; this.factory = factory; this.serializer = serializer; } public Task WarmupAsync() { this.sender = new MessageSender(this.factory); this.publisher = new MessagePublisher(this.factory); return Task.FromResult(0); } public OutgoingPipeline Create() { var pipeline = new OutgoingPipeline(); pipeline.Logical .Register(new CreateTransportMessageStep()); pipeline.Transport .Register(new SerializeMessageStep(this.serializer)) .Register(new DetermineDestinationStep(this.router)) .Register(new DispatchToTransportStep(this.sender, this.publisher)); return pipeline; } public async Task CooldownAsync() { await this.sender.CloseAsync(); await this.publisher.CloseAsync(); } } }
//------------------------------------------------------------------------------- // <copyright file="OutgoingPipelineFactory.cs" company="MMS AG"> // Copyright (c) MMS AG, 2008-2015 // </copyright> //------------------------------------------------------------------------------- namespace MMS.ServiceBus.Pipeline.Outgoing { using System.Threading.Tasks; using Microsoft.ServiceBus.Messaging; public class OutgoingPipelineFactory : IOutgoingPipelineFactory { private readonly MessagingFactory factory; private readonly IMessageRouter router; private MessageSender sender; private MessagePublisher publisher; private readonly IMessageSerializer serializer; public OutgoingPipelineFactory(MessagingFactory factory, IMessageRouter router, IMessageSerializer serializer) { this.router = router; this.factory = factory; this.serializer = serializer; } public Task WarmupAsync() { this.sender = new MessageSender(this.factory); this.publisher = new MessagePublisher(this.factory); return Task.FromResult(0); } public OutgoingPipeline Create() { var pipeline = new OutgoingPipeline(); pipeline.Logical .Register(new CreateTransportMessageStep()); pipeline.Transport .Register(new SerializeMessageStep(this.serializer)) .Register(new DetermineDestinationStep(this.router)) .Register(new DispatchToTransportStep(this.sender, this.publisher)); return pipeline; } public async Task CooldownAsync() { await this.sender.CloseAsync(); await this.publisher.CloseAsync(); } } }
apache-2.0
C#
dd1fe3b996046a7423b5d813bbb5d59758901be4
fix messagepack serialization
jmenziessmith/TagCache.Redis
src/TagCache.Redis.MessagePack/MessagePackSerializationProvider.cs
src/TagCache.Redis.MessagePack/MessagePackSerializationProvider.cs
using System; using System.IO; using System.Text; using StackExchange.Redis; using TagCache.Redis.Interfaces; using MsgPack.Serialization; namespace TagCache.Redis.MessagePack { public class MessagePackSerializationProvider : ISerializationProvider { public T Deserialize<T>(RedisValue value) where T : class { var type = GetConcreteType<T>(); using (var stream = new MemoryStream(value)) { var deserialized = SerializationContext.Default.GetSerializer(type).Unpack(stream); return deserialized as T; } } public RedisValue Serialize<T>(T value) where T : class { var type = value.GetType(); var serializer = SerializationContext.Default.GetSerializer(type); using (var stream = new MemoryStream()) { serializer.Pack(stream, value); return stream.ToArray(); } } private Type GetConcreteType<T>() { var objectType = typeof (T); if (objectType.IsInterface && typeof (IRedisCacheItem).IsAssignableFrom(objectType)) { Type concreteType = typeof(RedisCacheItem); if (objectType.IsGenericType) { concreteType = typeof(RedisCacheItem<>).MakeGenericType(objectType.GenericTypeArguments); } return concreteType; } return objectType; } } }
using System.IO; using StackExchange.Redis; using TagCache.Redis.Interfaces; using MsgPack.Serialization; namespace TagCache.Redis.MessagePack { public class MessagePackSerializationProvider : ISerializationProvider { public T Deserialize<T>(RedisValue value) where T : class { using (var stream = new MemoryStream(value)) { return SerializationContext.Default.GetSerializer<T>().Unpack(stream); } } public RedisValue Serialize<T>(T value) where T : class { using (var stream = new MemoryStream()) { SerializationContext.Default.GetSerializer<T>().Pack(stream, value); return stream.ToArray(); } } } }
mit
C#
316159ed18bc94d2450d51f85aa232e3e19c44e5
Use placeholder expressions, {nr} doesn't work because of ConfigNode beign weird
LanguagePatches/LanguagePatches-Framework
LanguagePatches/Translation.cs
LanguagePatches/Translation.cs
/** * Language Patches Framework * Translates the game into different Languages * Copyright (c) 2016 Thomas P. * Licensed under the terms of the MIT License */ using System; using System.Text.RegularExpressions; namespace LanguagePatches { /// <summary> /// A class that represents a text translation /// </summary> public class Translation { /// <summary> /// The original message, uses Regex syntax /// </summary> public String text { get; set; } /// <summary> /// The replacement message, uses String.Format syntax /// </summary> public String translation { get; set; } /// <summary> /// Creates a new Translation component from a config node /// </summary> /// <param name="node">The config node where the </param> public Translation(ConfigNode node) { // Check for original text if (!node.HasValue("text")) throw new Exception("The config node is missing the text value!"); // Check for translation if (!node.HasValue("translation")) throw new Exception("The config node is missing the translation value!"); // Assign the new texts text = node.GetValue("text"); translation = node.GetValue("translation"); // Replace variable placeholders translation = Regex.Replace(translation, @"@(\d*)", "{$1}"); } } }
/** * Language Patches Framework * Translates the game into different Languages * Copyright (c) 2016 Thomas P. * Licensed under the terms of the MIT License */ using System; namespace LanguagePatches { /// <summary> /// A class that represents a text translation /// </summary> public class Translation { /// <summary> /// The original message, uses Regex syntax /// </summary> public String text { get; set; } /// <summary> /// The replacement message, uses String.Format syntax /// </summary> public String translation { get; set; } /// <summary> /// Creates a new Translation component from a config node /// </summary> /// <param name="node">The config node where the </param> public Translation(ConfigNode node) { // Check for original text if (!node.HasValue("text")) throw new Exception("The config node is missing the text value!"); // Check for translation if (!node.HasValue("translation")) throw new Exception("The config node is missing the translation value!"); // Assign the new texts text = node.GetValue("text"); translation = node.GetValue("translation"); } } }
mit
C#
40858c4cb7afec09e6a3b4a54b2d2e5c1f6e31f8
Adjust existing test coverage
peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Taiko.Tests/TestSceneTaikoHitObjectSamples.cs
osu.Game.Rulesets.Taiko.Tests/TestSceneTaikoHitObjectSamples.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.Reflection; using NUnit.Framework; using osu.Framework.IO.Stores; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TestSceneTaikoHitObjectSamples : HitObjectSampleTest { protected override Ruleset CreatePlayerRuleset() => new TaikoRuleset(); protected override IResourceStore<byte[]> RulesetResources => new DllResourceStore(Assembly.GetAssembly(typeof(TestSceneTaikoHitObjectSamples))); [TestCase("taiko-normal-hitnormal")] [TestCase("hitnormal")] public void TestDefaultCustomSampleFromBeatmap(string expectedSample) { SetupSkins(expectedSample, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertBeatmapLookup(expectedSample); } [TestCase("taiko-normal-hitnormal")] [TestCase("hitnormal")] public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample) { SetupSkins(string.Empty, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertUserLookup(expectedSample); } [TestCase("taiko-normal-hitnormal2")] public void TestUserSkinLookupIgnoresSampleBank(string unwantedSample) { SetupSkins(string.Empty, unwantedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertNoLookup(unwantedSample); } } }
// 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.Reflection; using NUnit.Framework; using osu.Framework.IO.Stores; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Taiko.Tests { public class TestSceneTaikoHitObjectSamples : HitObjectSampleTest { protected override Ruleset CreatePlayerRuleset() => new TaikoRuleset(); protected override IResourceStore<byte[]> RulesetResources => new DllResourceStore(Assembly.GetAssembly(typeof(TestSceneTaikoHitObjectSamples))); [TestCase("taiko-normal-hitnormal")] [TestCase("normal-hitnormal")] [TestCase("hitnormal")] public void TestDefaultCustomSampleFromBeatmap(string expectedSample) { SetupSkins(expectedSample, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertBeatmapLookup(expectedSample); } [TestCase("taiko-normal-hitnormal")] [TestCase("normal-hitnormal")] [TestCase("hitnormal")] public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample) { SetupSkins(string.Empty, expectedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertUserLookup(expectedSample); } [TestCase("taiko-normal-hitnormal2")] [TestCase("normal-hitnormal2")] public void TestUserSkinLookupIgnoresSampleBank(string unwantedSample) { SetupSkins(string.Empty, unwantedSample); CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu"); AssertNoLookup(unwantedSample); } } }
mit
C#
94a572d3e7aa30a51b745414b67520b6c693ca4f
Update Program.cs
monkey3310/appveyor-shields-badges
AppveyorShieldBadges/Program.cs
AppveyorShieldBadges/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; namespace AppveyorShieldBadges { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .Build(); host.Run(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; namespace AppveyorShieldBadges { public class Program { public static void Main(string[] args) { var host = ;new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .Build(); host.Run(); } } }
mit
C#
48f052b1e3a53aa194fc9048c4d98762e11b5930
redefine LastModifiedDateTime accessor to return nullable DateTime (#228)
poornas/minio-dotnet,poornas/minio-dotnet,minio/minio-dotnet
Minio/DataModel/Item.cs
Minio/DataModel/Item.cs
/* * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Minio.DataModel { [Serializable] public class Item { private string etag; public string Key { get; set; } public string LastModified { get; set; } public string ETag { get { return etag; } set { if (value != null) { etag = value.Replace("\"", ""); } else { etag = null; } } } public UInt64 Size { get; set; } public bool IsDir { get; set; } public DateTime? LastModifiedDateTime { get { DateTime? dt = null; if(!string.IsNullOrEmpty(this.LastModified)) { dt = DateTime.Parse(this.LastModified); } return dt; } } } }
/* * Minio .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Minio.DataModel { [Serializable] public class Item { private string etag; public string Key { get; set; } public string LastModified { get; set; } public string ETag { get { return etag; } set { if (value != null) { etag = value.Replace("\"", ""); } else { etag = null; } } } public UInt64 Size { get; set; } public bool IsDir { get; set; } public DateTime LastModifiedDateTime { get { return DateTime.Parse(this.LastModified); } } } }
apache-2.0
C#
89e276dc1d31ba6a539af7aacfde4527cb8df90c
Sort games in tags when serializing
zr40/steamgames
SteamGames/State.cs
SteamGames/State.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using ProtoBuf; namespace SteamGames { [ProtoContract] internal sealed class State { internal static readonly string BasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SteamGames"); private static readonly string statePath = Path.Combine(BasePath, "state.dat"); private static readonly string savePath = Path.Combine(BasePath, "state new.dat"); [ProtoMember(1)] internal string WebApiKey; [ProtoMember(2)] internal ulong SteamId; [ProtoMember(3)] internal readonly Dictionary<string, List<int>> Tags = new Dictionary<string, List<int>>(); [ProtoMember(4)] internal Dictionary<string, CheckState> TagState = new Dictionary<string, CheckState>(); [ProtoMember(5)] internal readonly Dictionary<string, Filter> Filters; [ProtoMember(6)] internal string SelectedFilter = "All games"; private State() { Filters = new Dictionary<string, Filter>(); } internal static State Load() { if (!Directory.Exists(BasePath)) { Directory.CreateDirectory(BasePath); } if (!Directory.Exists(ImageCache.cachePath)) { Directory.CreateDirectory(ImageCache.cachePath); } if (File.Exists(statePath)) { using (FileStream s = File.OpenRead(statePath)) { return Serializer.Deserialize<State>(s); } } return new State(); } internal void Save() { foreach (string key in Tags.Keys.ToList()) { if (Tags[key].Count == 0) { Tags.Remove(key); } } foreach (string key in TagState.Keys.ToList()) { if (!Tags.ContainsKey(key)) { TagState.Remove(key); } } if (File.Exists(savePath)) File.Delete(savePath); using (FileStream s = File.Open(savePath, FileMode.CreateNew, FileAccess.Write)) { Serializer.Serialize(s, this); } if (File.Exists(statePath)) File.Delete(statePath); File.Move(savePath, statePath); } [ProtoBeforeSerialization] private void Sort() { foreach (var tag in Tags) { tag.Value.Sort(); } } [ProtoAfterDeserialization] private void AfterDeserialization() { CreatePredicates(); CreateAllGamesIfNoFilterExists(); } private void CreatePredicates() { foreach (var filter in Filters) { filter.Value.CreatePredicate(this); } } private void CreateAllGamesIfNoFilterExists() { if (Filters.Count == 0) Filters.Add("All games", new Filter("All games", "true", this)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using ProtoBuf; namespace SteamGames { [ProtoContract] internal sealed class State { internal static readonly string BasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SteamGames"); private static readonly string statePath = Path.Combine(BasePath, "state.dat"); private static readonly string savePath = Path.Combine(BasePath, "state new.dat"); [ProtoMember(1)] internal string WebApiKey; [ProtoMember(2)] internal ulong SteamId; [ProtoMember(3)] internal readonly Dictionary<string, List<int>> Tags = new Dictionary<string, List<int>>(); [ProtoMember(4)] internal Dictionary<string, CheckState> TagState = new Dictionary<string, CheckState>(); [ProtoMember(5)] internal readonly Dictionary<string, Filter> Filters; [ProtoMember(6)] internal string SelectedFilter = "All games"; private State() { Filters = new Dictionary<string, Filter>(); } internal static State Load() { if (!Directory.Exists(BasePath)) { Directory.CreateDirectory(BasePath); } if (!Directory.Exists(ImageCache.cachePath)) { Directory.CreateDirectory(ImageCache.cachePath); } if (File.Exists(statePath)) { using (FileStream s = File.OpenRead(statePath)) { return Serializer.Deserialize<State>(s); } } return new State(); } internal void Save() { foreach (string key in Tags.Keys.ToList()) { if (Tags[key].Count == 0) { Tags.Remove(key); } } foreach (string key in TagState.Keys.ToList()) { if (!Tags.ContainsKey(key)) { TagState.Remove(key); } } if (File.Exists(savePath)) File.Delete(savePath); using (FileStream s = File.Open(savePath, FileMode.CreateNew, FileAccess.Write)) { Serializer.Serialize(s, this); } if (File.Exists(statePath)) File.Delete(statePath); File.Move(savePath, statePath); } [ProtoAfterDeserialization] private void AfterDeserialization() { CreatePredicates(); CreateAllGamesIfNoFilterExists(); } private void CreatePredicates() { foreach (var filter in Filters) { filter.Value.CreatePredicate(this); } } private void CreateAllGamesIfNoFilterExists() { if (Filters.Count == 0) Filters.Add("All games", new Filter("All games", "true", this)); } } }
mit
C#