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
1f21ffdc1ebf58956a267992733a87d9f5c38b6e
Use a case-insensitive comparer for the Filter dictionary on FilterParameters
IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce
src/IntelliTect.Coalesce/Api/Parameters/FilterParameters.cs
src/IntelliTect.Coalesce/Api/Parameters/FilterParameters.cs
using System; using System.Collections.Generic; namespace IntelliTect.Coalesce.Api { public class FilterParameters : DataSourceParameters, IFilterParameters { /// <inheritdoc /> public string Search { get; set; } /// <inheritdoc cref="IFilterParameters.Filter" /> public Dictionary<string, string> Filter { get; set; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); /// <inheritdoc /> IDictionary<string, string> IFilterParameters.Filter => Filter; } }
using System.Collections.Generic; namespace IntelliTect.Coalesce.Api { public class FilterParameters : DataSourceParameters, IFilterParameters { /// <inheritdoc /> public string Search { get; set; } /// <inheritdoc cref="IFilterParameters.Filter" /> public Dictionary<string, string> Filter { get; set; } = new Dictionary<string, string>(); /// <inheritdoc /> IDictionary<string, string> IFilterParameters.Filter => Filter; } }
apache-2.0
C#
22cb71abf74a8fd51f29de2d3cf59e2e81041013
Update version to 1.0.1
TheOtherTimDuncan/EntityFramework.DatabaseMigrator
EntityFramework.DatabaseMigrator/Properties/AssemblyInfo.cs
EntityFramework.DatabaseMigrator/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("EntityFramework.DatabaseMigrator")] [assembly: AssemblyDescription("Entity Framework Migration Helper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TheOtherTimDuncan")] [assembly: AssemblyProduct("EntityFramework.DatabaseMigrator")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ee4f657d-aebe-4835-b454-f61b3424f800")] // 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.1.0")] [assembly: AssemblyFileVersion("1.0.1.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("EntityFramework.DatabaseMigrator")] [assembly: AssemblyDescription("Entity Framework Migration Helper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TheOtherTimDuncan")] [assembly: AssemblyProduct("EntityFramework.DatabaseMigrator")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ee4f657d-aebe-4835-b454-f61b3424f800")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
c8bda522900089452ca47f4c8d82e099cb7e5fc0
allow querying through api
0xFireball/KQAnalytics3,0xFireball/KQAnalytics3,0xFireball/KQAnalytics3
KQAnalytics3/src/KQAnalytics3/Modules/DataQueryApiModule.cs
KQAnalytics3/src/KQAnalytics3/Modules/DataQueryApiModule.cs
using KQAnalytics3.Models.Data; using KQAnalytics3.Services.DataCollection; using Nancy; using Nancy.Security; namespace KQAnalytics3.Modules { public class DataQueryApiModule : NancyModule { public DataQueryApiModule() : base("/api") { // Require stateless auth this.RequiresAuthentication(); // Limit is the max number of log requests to return. Default 100 Get("/query/{limit}", args => { var itemLimit = args.limit ?? 100; return Response.AsJson( (LogRequest[])DataLoggerService.QueryRequests(itemLimit).ToArray() ); }); } } }
using Nancy; namespace KQAnalytics3.Modules { public class DataQueryApiModule : NancyModule { public DataQueryApiModule() { } } }
agpl-3.0
C#
275fa01cf4b09ed634a1b197b03c937c93d9a7d9
return elements ordered by id
pako1337/Content_Man,pako1337/Content_Man
ContentDomain/Factories/ContentElementFactory.cs
ContentDomain/Factories/ContentElementFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContentDomain.Factories { public class ContentElementFactory { public ContentElement Create(string language, ContentType type) { return new ContentElement(-1, Language.Create(language), type); } public ContentElement Create(dynamic dynamicElement) { var contentElement = new ContentElement( dynamicElement.ContentElementId, Language.Create(dynamicElement.DefaultLanguage), (ContentType)dynamicElement.ContentType); if (dynamicElement.TextContents != null) contentElement.AddValues(GetTextContents(dynamicElement)); return contentElement; } public TextContent CreateTextContent(dynamic value) { return new TextContent(Language.Create(value.Language)) { ContentValueId = value.TextContentId, Status = (ContentStatus)value.ContentStatus, Value = value.Value }; } private IEnumerable<TextContent> GetTextContents(dynamic contentElement) { foreach (var value in contentElement.TextContents) yield return CreateTextContent(value); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContentDomain.Factories { public class ContentElementFactory { public ContentElement Create(string language, ContentType type) { return new ContentElement(-1, Language.Create(language), type); } public ContentElement Create(dynamic dynamicElement) { var contentElement = new ContentElement( dynamicElement.ContentElementId, Language.Create(dynamicElement.DefaultLanguage), (ContentType)dynamicElement.ContentType); if (dynamicElement.TextContents != null) foreach (var value in dynamicElement.TextContents) { TextContent text = CreateTextContent(value); contentElement.AddValue(text); } return contentElement; } public TextContent CreateTextContent(dynamic value) { return new TextContent(Language.Create(value.Language)) { ContentValueId = value.TextContentId, Status = (ContentStatus)value.ContentStatus, Value = value.Value }; } } }
mit
C#
60f0470b9acf204b88ac17831b2421c9a9c53bb8
fix add new water meter
NickSerg/water-meter,NickSerg/water-meter,NickSerg/water-meter
WaterMeter/WM.AspNetMvc/Controllers/WaterMeterController.cs
WaterMeter/WM.AspNetMvc/Controllers/WaterMeterController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WM.AspNetMvc.Models; namespace WM.AspNetMvc.Controllers { public class WaterMeterController : Controller { private readonly WaterMeterDataContext waterMeterDataContext; public WaterMeterController() { waterMeterDataContext = new WaterMeterDataContext(); } // GET: WaterMeter public ActionResult Index() { ViewBag.MyHeader = "Water Meter"; return View(waterMeterDataContext.WaterMeters); } [HttpGet] public ActionResult AddWaterMeter() { return View(); } [HttpPost] public ActionResult AddWaterMeter(WaterMeterViewModel model) { if (ModelState.IsValid) { var waterMeter = waterMeterDataContext.WaterMeters.FirstOrDefault(x => x.Period.Month == model.PeriodMonth && x.Period.Year == model.PeriodYear); var isNew = waterMeter == null; if(isNew) waterMeter = new WaterMeter(); waterMeter.Period = new DateTime(model.PeriodYear, model.PeriodMonth, DateTime.DaysInMonth(model.PeriodYear, model.PeriodMonth)); waterMeter.Cold = model.Cold; waterMeter.Hot = model.Hot; if(isNew) waterMeterDataContext.WaterMeters.Add(waterMeter); waterMeterDataContext.SaveChanges(); return RedirectToAction("Index"); } return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WM.AspNetMvc.Models; namespace WM.AspNetMvc.Controllers { public class WaterMeterController : Controller { private readonly WaterMeterDataContext waterMeterDataContext; public WaterMeterController() { waterMeterDataContext = new WaterMeterDataContext(); } // GET: WaterMeter public ActionResult Index() { ViewBag.MyHeader = "Water Meter"; return View(waterMeterDataContext.WaterMeters); } [HttpGet] public ActionResult AddWaterMeter() { return View(); } [HttpPost] public ActionResult AddWaterMeter(WaterMeter waterMeter) { if (ModelState.IsValid) { waterMeterDataContext.WaterMeters.Add(waterMeter); waterMeterDataContext.SaveChanges(); return RedirectToAction("Index"); } return View(); } } }
apache-2.0
C#
cf33d49e1b3523f53b1d0fe6793557dd243a92f2
support for wffm version 2.3
zigor/morph
Rules/Actions/Client/ClientAction.cs
Rules/Actions/Client/ClientAction.cs
namespace Morph.Forms.Rules.Actions.Client { using System.Web.UI; using Sitecore; using Sitecore.Diagnostics; using Sitecore.Forms.Core.Rules; using Sitecore.StringExtensions; /// <summary> /// Defines the client action class. /// </summary> /// <typeparam name="T"></typeparam> public abstract class ClientAction<T> : FieldAction<T> where T : ConditionalRuleContext { #region Methods /// <summary> /// Applies the specified rule context. /// </summary> /// <param name="ruleContext">The rule context.</param> public override void Apply([NotNull] T ruleContext) { Assert.ArgumentNotNull(ruleContext, "ruleContext"); if (ruleContext.Control == null || !ruleContext.Control.Visible) { return; } ruleContext.Control.PreRender += (s, e) => RegisterScript(ruleContext.Control, this.PrepareScript(ruleContext.Control)); } /// <summary> /// Prepares the script. /// </summary> /// <param name="control">The control.</param> /// <returns> /// The script. /// </returns> [CanBeNull] protected abstract string PrepareScript([NotNull] Control control); /// <summary> /// Registers the script. /// </summary> /// <param name="control">The control.</param> /// <param name="script">The script.</param> private static void RegisterScript([NotNull] Control control, [CanBeNull] string script) { Assert.ArgumentNotNull(control, "control"); if (string.IsNullOrEmpty(script)) { return; } var ready = "$scw(document).ready(function(){{{0}}});".FormatWith(script); ScriptManager.RegisterStartupScript(control, typeof(Page), ready, ready, true); } #endregion } }
namespace Morph.Forms.Rules.Actions.Client { using System.Web.UI; using Sitecore; using Sitecore.Diagnostics; using Sitecore.Forms.Core.Rules; using Sitecore.StringExtensions; /// <summary> /// Defines the client action class. /// </summary> /// <typeparam name="T"></typeparam> public abstract class ClientAction<T> : FieldAction<T> where T : ConditionalRuleContext { #region Methods /// <summary> /// Applies the specified rule context. /// </summary> /// <param name="ruleContext">The rule context.</param> public override void Apply([NotNull] T ruleContext) { Assert.ArgumentNotNull(ruleContext, "ruleContext"); if (ruleContext.Control == null || !ruleContext.Control.Visible) { return; } ruleContext.Control.PreRender += (s, e) => RegisterScript(ruleContext.Control, this.PrepareScript(ruleContext.Control)); } /// <summary> /// Prepares the script. /// </summary> /// <param name="control">The control.</param> /// <returns> /// The script. /// </returns> [CanBeNull] protected abstract string PrepareScript([NotNull] Control control); /// <summary> /// Registers the script. /// </summary> /// <param name="control">The control.</param> /// <param name="script">The script.</param> private static void RegisterScript([NotNull] Control control, [CanBeNull] string script) { Assert.ArgumentNotNull(control, "control"); if (string.IsNullOrEmpty(script)) { return; } var ready = "$scwhead.ready(function(){{{0}}});".FormatWith(script); ScriptManager.RegisterStartupScript(control, typeof(Page), ready, ready, true); } #endregion } }
mit
C#
88d1cbdf7c4a242be0dfcea7ecd96b0773972a84
Modify sample application to show details about the posted tweet
misenhower/MicroTweet
SampleApplication/Program.cs
SampleApplication/Program.cs
using System; using Microsoft.SPOT; using MicroTweet; using System.Net; using System.Threading; namespace SampleApplication { public class Program { public static void Main() { // Wait for DHCP while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) Thread.Sleep(50); // Update the current time (since Twitter OAuth API requests require a valid timestamp) DateTime utcTime = Sntp.GetCurrentUtcTime(); Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime); // Set up application and user credentials // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens var appCredentials = new OAuthApplicationCredentials() { ConsumerKey = "YOUR_CONSUMER_KEY_HERE", ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE", }; var userCredentials = new OAuthUserCredentials() { AccessToken = "YOUR_ACCESS_TOKEN", AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET", }; // Create new Twitter client with these credentials var twitter = new TwitterClient(appCredentials, userCredentials); // Send a tweet var tweet = twitter.SendTweet("Trying out MicroTweet!"); if (tweet != null) Debug.Print("Posted tweet with ID: " + tweet.ID); else Debug.Print("Could not send tweet."); } } }
using System; using Microsoft.SPOT; using MicroTweet; using System.Net; using System.Threading; namespace SampleApplication { public class Program { public static void Main() { // Wait for DHCP while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) Thread.Sleep(50); // Update the current time (since Twitter OAuth API requests require a valid timestamp) DateTime utcTime = Sntp.GetCurrentUtcTime(); Microsoft.SPOT.Hardware.Utility.SetLocalTime(utcTime); // Set up application and user credentials // Visit https://apps.twitter.com/ to create a new Twitter application and get API keys/user access tokens var appCredentials = new OAuthApplicationCredentials() { ConsumerKey = "YOUR_CONSUMER_KEY_HERE", ConsumerSecret = "YOUR_CONSUMER_SECRET_HERE", }; var userCredentials = new OAuthUserCredentials() { AccessToken = "YOUR_ACCESS_TOKEN", AccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET", }; // Create new Twitter client with these credentials var twitter = new TwitterClient(appCredentials, userCredentials); // Send a tweet twitter.SendTweet("Trying out MicroTweet!"); } } }
apache-2.0
C#
6e49fb22b4e3c4d769e2dbc446d87f311aa4437d
Bump for v1.0.0
decred/Paymetheus,jrick/Paymetheus
Paymetheus/Properties/AssemblyInfo.cs
Paymetheus/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Paymetheus Decred Wallet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Paymetheus")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyMetadata("Organization", "Decred")] // 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Paymetheus Decred Wallet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Paymetheus")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyMetadata("Organization", "Decred")] // 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")]
isc
C#
c0c4639aaacd7fc29bf4a9ddfbbe135af27a9699
Update AssemblyInfo
ProgTrade/SharpMath
SharpMath/Properties/AssemblyInfo.cs
SharpMath/Properties/AssemblyInfo.cs
// Author: Dominic Beger (Trade/ProgTrade) 2016 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("SharpMath")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpMath")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4706ae0f-30c8-460b-bbbf-5f189be4eb76")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
// Author: Dominic Beger (Trade/ProgTrade) 2016 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("SharpMath")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpMath")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4706ae0f-30c8-460b-bbbf-5f189be4eb76")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
6de0458a902e0b2c18a7ec5819844fd58d0a775d
Add global disable option to FPSDisplay
NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
Assets/Scripts/UI/FPSDisplay.cs
Assets/Scripts/UI/FPSDisplay.cs
using UnityEngine; using System.Collections; public class FPSDisplay : MonoBehaviour { private static bool DisableGlobally = false; float deltaTime = 0.0f; void Start() { if (DisableGlobally) { enabled = false; return; } } void Update() { deltaTime += (Time.deltaTime - deltaTime) * 0.1f; } void OnGUI() { int w = Screen.width, h = Screen.height; GUIStyle style = new GUIStyle(); Rect rect = new Rect(0, 0, w, h * 2 / 100); style.alignment = TextAnchor.UpperLeft; style.fontSize = h * 2 / 100; style.normal.textColor = new Color(0.0f, 0.0f, 0.5f, 1.0f); float msec = deltaTime * 1000.0f; float fps = 1.0f / deltaTime; fps *= Time.timeScale; string text = string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps); GUI.Label(rect, text, style); //float trueFPS = 1f / Time.deltaTime; //if (trueFPS< 50f) //{ // Debug.Log("SLOW FPS: " + trueFPS + " " + Time.deltaTime); //} } }
using UnityEngine; using System.Collections; public class FPSDisplay : MonoBehaviour { float deltaTime = 0.0f; void Update() { deltaTime += (Time.deltaTime - deltaTime) * 0.1f; } void OnGUI() { int w = Screen.width, h = Screen.height; GUIStyle style = new GUIStyle(); Rect rect = new Rect(0, 0, w, h * 2 / 100); style.alignment = TextAnchor.UpperLeft; style.fontSize = h * 2 / 100; style.normal.textColor = new Color(0.0f, 0.0f, 0.5f, 1.0f); float msec = deltaTime * 1000.0f; float fps = 1.0f / deltaTime; fps *= Time.timeScale; string text = string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps); GUI.Label(rect, text, style); //float trueFPS = 1f / Time.deltaTime; //if (trueFPS< 50f) //{ // Debug.Log("SLOW FPS: " + trueFPS + " " + Time.deltaTime); //} } }
mit
C#
7bbd6288b1389be36b01679c030b8f6b76e2be86
Bump version
klesta490/BTDB,karasek/BTDB,Bobris/BTDB
BTDB/Properties/AssemblyInfo.cs
BTDB/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("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright � Boris Letocha 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. 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("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("3.4.0.0")] [assembly: AssemblyFileVersion("3.4.0.0")] [assembly: InternalsVisibleTo("BTDBTest")]
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("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright � Boris Letocha 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. 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("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("3.3.0.0")] [assembly: AssemblyFileVersion("3.3.0.0")] [assembly: InternalsVisibleTo("BTDBTest")]
mit
C#
27a7904955747b713c2dc72be841397c69097d0e
Fix RedistCopy error when building for unsupported platforms
GoeGaming/Steamworks.NET,rlabrecque/Steamworks.NET,Gert-Jan/Steamworks.NET,rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET,Yukinii/Async-Await-Steamworks.NET,rlabrecque/Steamworks.NET,etodd/Steamworks.NET
Editor/Steamworks.NET/RedistCopy.cs
Editor/Steamworks.NET/RedistCopy.cs
// Uncomment this out to disable copying //#define DISABLEREDISTCOPY using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System.IO; public class RedistCopy { [PostProcessBuild] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { #if !DISABLEREDISTCOPY if (target != BuildTarget.StandaloneWindows || target != BuildTarget.StandaloneWindows64 || target != BuildTarget.StandaloneOSXIntel || target != BuildTarget.StandaloneOSXIntel64 || target != BuildTarget.StandaloneOSXUniversal || target != BuildTarget.StandaloneLinux || target != BuildTarget.StandaloneLinux64 || target != BuildTarget.StandaloneLinuxUniversal) { return; } string strProjectName = Path.GetFileNameWithoutExtension(pathToBuiltProject); if (target == BuildTarget.StandaloneWindows64) { CopyFile("steam_api64.dll", "steam_api64.dll", "Assets/Plugins/x86_64", pathToBuiltProject); } else if (target == BuildTarget.StandaloneWindows) { CopyFile("steam_api.dll", "steam_api.dll", "Assets/Plugins/x86", pathToBuiltProject); } string controllerCfg = Path.Combine(Application.dataPath, "controller.vdf"); if (File.Exists(controllerCfg)) { string dir = "_Data"; if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal) { dir = ".app/Contents"; } string strFileDest = Path.Combine(Path.Combine(Path.GetDirectoryName(pathToBuiltProject), strProjectName + dir), "controller.vdf"); File.Copy(controllerCfg, strFileDest); File.SetAttributes(strFileDest, File.GetAttributes(strFileDest) & ~FileAttributes.ReadOnly); if (!File.Exists(strFileDest)) { Debug.LogWarning("[Steamworks.NET] Could not copy controller.vdf into the built project. File.Copy() Failed. Place controller.vdf from the Steamworks SDK in the output dir manually."); } } #endif } static void CopyFile(string filename, string outputfilename, string pathToFile, string pathToBuiltProject) { string strCWD = Directory.GetCurrentDirectory(); string strSource = Path.Combine(Path.Combine(strCWD, pathToFile), filename); string strFileDest = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), outputfilename); if (!File.Exists(strSource)) { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the project root. {0} could not be found in '{1}'. Place {0} from the redist into the project root manually.", filename, pathToFile)); return; } if (File.Exists(strFileDest)) { if (File.GetLastWriteTime(strSource) == File.GetLastWriteTime(strFileDest)) { FileInfo fInfo = new FileInfo(strSource); FileInfo fInfo2 = new FileInfo(strFileDest); if (fInfo.Length == fInfo2.Length) { return; } } } File.Copy(strSource, strFileDest, true); File.SetAttributes(strFileDest, File.GetAttributes(strFileDest) & ~FileAttributes.ReadOnly); if (!File.Exists(strFileDest)) { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the built project. File.Copy() Failed. Place {0} from the redist folder into the output dir manually.", filename)); } } }
// Uncomment this out to disable copying //#define DISABLEREDISTCOPY using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System.IO; public class RedistCopy { [PostProcessBuild] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { #if !DISABLEREDISTCOPY string strProjectName = Path.GetFileNameWithoutExtension(pathToBuiltProject); if (target == BuildTarget.StandaloneWindows64) { CopyFile("steam_api64.dll", "steam_api64.dll", "Assets/Plugins/x86_64", pathToBuiltProject); } else if (target == BuildTarget.StandaloneWindows) { CopyFile("steam_api.dll", "steam_api.dll", "Assets/Plugins/x86", pathToBuiltProject); } string controllerCfg = Path.Combine(Application.dataPath, "controller.vdf"); if (File.Exists(controllerCfg)) { string dir = "_Data"; if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal) { dir = ".app/Contents"; } string strFileDest = Path.Combine(Path.Combine(Path.GetDirectoryName(pathToBuiltProject), strProjectName + dir), "controller.vdf"); File.Copy(controllerCfg, strFileDest); File.SetAttributes(strFileDest, File.GetAttributes(strFileDest) & ~FileAttributes.ReadOnly); if (!File.Exists(strFileDest)) { Debug.LogWarning("[Steamworks.NET] Could not copy controller.vdf into the built project. File.Copy() Failed. Place controller.vdf from the Steamworks SDK in the output dir manually."); } } #endif } static void CopyFile(string filename, string outputfilename, string pathToFile, string pathToBuiltProject) { string strCWD = Directory.GetCurrentDirectory(); string strSource = Path.Combine(Path.Combine(strCWD, pathToFile), filename); string strFileDest = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), outputfilename); if (!File.Exists(strSource)) { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the project root. {0} could not be found in '{1}'. Place {0} from the redist into the project root manually.", filename, pathToFile)); return; } if (File.Exists(strFileDest)) { if (File.GetLastWriteTime(strSource) == File.GetLastWriteTime(strFileDest)) { FileInfo fInfo = new FileInfo(strSource); FileInfo fInfo2 = new FileInfo(strFileDest); if (fInfo.Length == fInfo2.Length) { return; } } } File.Copy(strSource, strFileDest, true); File.SetAttributes(strFileDest, File.GetAttributes(strFileDest) & ~FileAttributes.ReadOnly); if (!File.Exists(strFileDest)) { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the built project. File.Copy() Failed. Place {0} from the redist folder into the output dir manually.", filename)); } } }
mit
C#
b64f7604408dcb3606cb1ddc09b9e306643ecb70
Use new Presign method
carbon/Amazon
src/Amazon.Rds/RdsService.cs
src/Amazon.Rds/RdsService.cs
using System; using System.Net.Http; using System.Threading.Tasks; using Amazon.Security; namespace Amazon.Rds { public sealed class RdsService { private readonly AwsRegion region; private readonly IAwsCredential credential; public RdsService(AwsRegion region, IAwsCredential credential) { this.region = region ?? throw new ArgumentNullException(nameof(region)); this.credential = credential ?? throw new ArgumentNullException(nameof(credential)); } public async Task<AuthenticationToken> GetAuthenticationTokenAsync(GetAuthenticationTokenRequest request) { // Ensure the underlying credential is renewed if (credential.ShouldRenew) { await credential.RenewAsync().ConfigureAwait(false); } var date = DateTime.UtcNow; var scope = new CredentialScope(date, region, AwsService.RdsDb); Uri requestUri = new Uri($"https://{request.HostName}:{request.Port}?Action=connect&DBUser={request.UserName}"); Uri url = new Uri(SignerV4.GetPresignedUrl(credential, scope, date, request.Expires, HttpMethod.Get, requestUri)); return new AuthenticationToken( value : url.Host + ":" + url.Port.ToString() + "/" + url.Query, issued : date, expires : date + request.Expires ); } public AuthenticationToken GetAuthenticationToken(GetAuthenticationTokenRequest request) { return GetAuthenticationTokenAsync(request).GetAwaiter().GetResult(); } } } // http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html
using System; using System.Net.Http; using System.Threading.Tasks; using Amazon.Security; namespace Amazon.Rds { public sealed class RdsService { private readonly AwsRegion region; private readonly IAwsCredential credential; public RdsService(AwsRegion region, IAwsCredential credential) { this.region = region ?? throw new ArgumentNullException(nameof(region)); this.credential = credential ?? throw new ArgumentNullException(nameof(credential)); } public async Task<AuthenticationToken> GetAuthenticationTokenAsync(GetAuthenticationTokenRequest request) { // Ensure the underlying credential is renewed if (credential.ShouldRenew) { await credential.RenewAsync().ConfigureAwait(false); } var date = DateTime.UtcNow; var scope = new CredentialScope(date, region, AwsService.RdsDb); var httpRequest = new HttpRequestMessage( HttpMethod.Get, $"https://{request.HostName}:{request.Port}?Action=connect&DBUser={request.UserName}" ); SignerV4.Default.Presign(credential, scope, date, request.Expires, httpRequest); Uri url = httpRequest.RequestUri; return new AuthenticationToken( value: url.Host + ":" + url.Port.ToString() + "/" + url.Query, issued: date, expires: date + request.Expires ); } public AuthenticationToken GetAuthenticationToken(GetAuthenticationTokenRequest request) { return GetAuthenticationTokenAsync(request).GetAwaiter().GetResult(); } } } // http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html
mit
C#
7ee02c4b38da37f996e740e6821159d3c98ca8f4
Add ScrollTo support to ScrollView
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
Ooui.Forms/Renderers/ScrollViewRenderer.cs
Ooui.Forms/Renderers/ScrollViewRenderer.cs
using System; using System.ComponentModel; using Ooui.Forms.Extensions; using Xamarin.Forms; namespace Ooui.Forms.Renderers { public class ScrollViewRenderer : VisualElementRenderer<ScrollView> { bool disposed = false; protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e) { if (e.OldElement != null) { e.OldElement.ScrollToRequested -= Element_ScrollToRequested; } if (e.NewElement != null) { Style.Overflow = "scroll"; e.NewElement.ScrollToRequested += Element_ScrollToRequested; } base.OnElementChanged (e); } protected override void Dispose (bool disposing) { base.Dispose (disposing); if (disposing && !disposed) { if (Element != null) { Element.ScrollToRequested -= Element_ScrollToRequested; } disposed = true; } } void Element_ScrollToRequested (object sender, ScrollToRequestedEventArgs e) { var oe = (ITemplatedItemsListScrollToRequestedEventArgs)e; var item = oe.Item; var group = oe.Group; if (e.Mode == ScrollToMode.Position) { Send (Ooui.Message.Set (Id, "scrollTop", e.ScrollY)); Send (Ooui.Message.Set (Id, "scrollLeft", e.ScrollX)); } else { switch (e.Position) { case ScrollToPosition.Start: Send (Ooui.Message.Set (Id, "scrollTop", 0)); break; case ScrollToPosition.End: Send (Ooui.Message.Set (Id, "scrollTop", new Ooui.Message.PropertyReference { TargetId = Id, Key = "scrollHeight" })); break; } } } } }
using System; using System.ComponentModel; using Ooui.Forms.Extensions; using Xamarin.Forms; namespace Ooui.Forms.Renderers { public class ScrollViewRenderer : ViewRenderer<ScrollView, Div> { protected override void OnElementChanged (ElementChangedEventArgs<ScrollView> e) { base.OnElementChanged (e); this.Style.Overflow = "scroll"; } protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged (sender, e); } } }
mit
C#
8ac13b076353c675ef417f8c855b3a0fd93dbcd6
Update IUnitOfWorkFactory.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/IUnitOfWorkFactory.cs
TIKSN.Core/Data/IUnitOfWorkFactory.cs
namespace TIKSN.Data { public interface IUnitOfWorkFactory { IUnitOfWork Create(); } }
namespace TIKSN.Data { public interface IUnitOfWorkFactory { IUnitOfWork Create(); } }
mit
C#
1501802fa325e2ab22c28c686a86f732eb528ac5
Make StringExtensions internal
weblinq/WebLinq,weblinq/WebLinq,atifaziz/WebLinq,atifaziz/WebLinq
src/Core/StringExtensions.cs
src/Core/StringExtensions.cs
#region Copyright (c) 2019 Atif Aziz. 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. // #endregion namespace WebLinq { using System; static class StringExtensions { public static bool HasWhiteSpace(this string str) => HasWhiteSpace(str, 0, str.Length); public static bool HasWhiteSpace(this string str, int index, int length) { if (str == null) throw new ArgumentNullException(nameof(str)); if (index < 0 || index >= str.Length) throw new ArgumentOutOfRangeException(nameof(index), index, null); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), length, null); if (index + length > str.Length) throw new ArgumentOutOfRangeException(nameof(index), index, null); for (var i = index; i < length; i++) { if (char.IsWhiteSpace(str, i)) return true; } return false; } } }
#region Copyright (c) 2019 Atif Aziz. 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. // #endregion namespace WebLinq { using System; public static class StringExtensions { public static bool HasWhiteSpace(this string str) => HasWhiteSpace(str, 0, str.Length); public static bool HasWhiteSpace(this string str, int index, int length) { if (str == null) throw new ArgumentNullException(nameof(str)); if (index < 0 || index >= str.Length) throw new ArgumentOutOfRangeException(nameof(index), index, null); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), length, null); if (index + length > str.Length) throw new ArgumentOutOfRangeException(nameof(index), index, null); for (var i = index; i < length; i++) { if (char.IsWhiteSpace(str, i)) return true; } return false; } } }
apache-2.0
C#
e0d4fbf493f3258bd427440de9b9fad0b71a9167
document code
kreeben/resin,kreeben/resin
src/DocumentTable/DocHash.cs
src/DocumentTable/DocHash.cs
using System; namespace DocumentTable { // Note, this object's equatability property is key. Making this into a struct would only led to boxing. public class DocHash : IEquatable<DocHash> { public UInt64 Hash { get; private set; } public bool IsObsolete { get; set; } public DocHash(UInt64 hash) { Hash = hash; IsObsolete = false; } public DocHash(UInt64 hash, bool isObsolete) { Hash = hash; IsObsolete = isObsolete; } public bool Equals(DocHash other) { return other.Hash.Equals(Hash); } } }
using System; namespace DocumentTable { public class DocHash : IEquatable<DocHash> { public UInt64 Hash { get; private set; } public bool IsObsolete { get; set; } public DocHash(UInt64 hash) { Hash = hash; IsObsolete = false; } public DocHash(UInt64 hash, bool isObsolete) { Hash = hash; IsObsolete = isObsolete; } public bool Equals(DocHash other) { return other.Hash.Equals(Hash); } } }
mit
C#
89d695e7160a7e4051369e9cd448b7df2a053f16
simplify test
dennisroche/TestStack.Seleno,TestStack/TestStack.Seleno,random82/TestStack.Seleno,random82/TestStack.Seleno,dennisroche/TestStack.Seleno,TestStack/TestStack.Seleno,bendetat/TestStack.Seleno,bendetat/TestStack.Seleno
src/TestStack.Seleno.Tests/PageObjects/Actions/Executor/When_executing_predicate_script_that_completes_successfuly.cs
src/TestStack.Seleno.Tests/PageObjects/Actions/Executor/When_executing_predicate_script_that_completes_successfuly.cs
using NSubstitute; using OpenQA.Selenium; namespace TestStack.Seleno.Tests.PageObjects.Actions.Executor { class When_executing_predicate_script_that_completes_successfuly : ExecutorSpecification { private const string JqueryIsLoadedScript = "typeof jQuery == 'function'"; public void Given_the_predicate_script_will_return_true_only_the_second_time() { SubstituteFor<IJavaScriptExecutor>() .ExecuteScript("return " + JqueryIsLoadedScript) .Returns(false,true,false); } public void When_executing_predicate_script() { SUT.PredicateScriptAndWaitToComplete(JqueryIsLoadedScript); } public void Then_it_should_execute_the_predicate_script_2_times() { SubstituteFor<IJavaScriptExecutor>() .Received(2) .ExecuteScript("return " + JqueryIsLoadedScript); } } }
using NSubstitute; using OpenQA.Selenium; namespace TestStack.Seleno.Tests.PageObjects.Actions.Executor { class When_executing_predicate_script_that_completes_successfuly : ExecutorSpecification { private const string JqueryIsLoadedScript = "typeof jQuery == 'function'"; private int _index; private readonly bool[] _returnedValues = new [] {false, true, false}; public void Given_the_predicate_script_will_return_true_only_the_second_time() { SubstituteFor<IJavaScriptExecutor>() .ExecuteScript("return " + JqueryIsLoadedScript) .Returns(c => _returnedValues[_index++]); } public void When_executing_predicate_script() { SUT.PredicateScriptAndWaitToComplete(JqueryIsLoadedScript); } public void Then_it_should_execute_the_predicate_script_2_times() { SubstituteFor<IJavaScriptExecutor>() .Received(2) .ExecuteScript("return " + JqueryIsLoadedScript); } } }
mit
C#
1ef73273051107b03a51b35864796f1d4d804715
add comment
toannvqo/dnn_publish
Components/ProductController.cs
Components/ProductController.cs
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("new branch"); Console.WriteLine("shshshshshs"); // fasdfasfd var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
using DotNetNuke.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Christoc.Modules.DNNModule1.Components { public class ProductController { public Product GetProduct(int productId) { Product p; using (IDataContext ctx = DataContext.Instance()) { Console.WriteLine("new branch"); Console.WriteLine("shshshshshs"); var rep = ctx.GetRepository<Product>(); p = rep.GetById(productId); } return p; } public IEnumerable<Product> getAll() { IEnumerable<Product> p; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); p = rep.Get(); } return p; } public void CreateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Insert(p); } } public void DeleteProduct(int productId) { var p = GetProduct(productId); DeleteProduct(p); } public void DeleteProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Delete(p); } } public void UpdateProduct(Product p) { using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<Product>(); rep.Update(p); } } } }
mit
C#
c9d90928c51c55e20a3c68f47097beee30459f5b
remove comment
darvell/Coremero
Coremero/Coremero/CorePlugin.cs
Coremero/Coremero/CorePlugin.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Coremero.Commands; using Coremero.Utilities; namespace Coremero { public class CorePlugin : IPlugin { [Command("echo")] public string Echo(IInvocationContext context, IMessage message) { return string.Join(" ", message.Text.GetCommandArguments()); } [Command("woke")] public string Woke(IInvocationContext context, IMessage message) { return $"👏 {string.Join(" 👏 ", message.Text.ToUpper().GetCommandArguments())} 👏"; } [Command("gc")] public string RunGC(IInvocationContext context, IMessage message) { if (context.User?.Permissions != UserPermission.BotOwner) { return null; } StringBuilder builder = new StringBuilder(); builder.AppendLine($"Pre: {GC.GetTotalMemory(false) / 1024}KB"); GC.Collect(); GC.WaitForPendingFinalizers(); builder.AppendLine($"Post: {GC.GetTotalMemory(false) / 1024}KB"); return builder.ToString(); } public void Dispose() { // ignore } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Coremero.Commands; using Coremero.Utilities; namespace Coremero { public class CorePlugin : IPlugin { [Command("echo")] public string Echo(IInvocationContext context, IMessage message) { return string.Join(" ", message.Text.GetCommandArguments()); } [Command("woke")] public string Woke(IInvocationContext context, IMessage message) { return $"👏 {string.Join(" 👏 ", message.Text.ToUpper().GetCommandArguments())} 👏"; } // TODO: PERM CHECK ASAP! [Command("gc")] public string RunGC(IInvocationContext context, IMessage message) { if (context.User?.Permissions != UserPermission.BotOwner) { return null; } StringBuilder builder = new StringBuilder(); builder.AppendLine($"Pre: {GC.GetTotalMemory(false) / 1024}KB"); GC.Collect(); GC.WaitForPendingFinalizers(); builder.AppendLine($"Post: {GC.GetTotalMemory(false) / 1024}KB"); return builder.ToString(); } public void Dispose() { // ignore } } }
mit
C#
90be15f097cb62d16b15e08289835a9ac1edbd2f
Update demo
sunkaixuan/SqlSugar
Src/Asp.Net/SqlServerTest/Demo/DemoE_CodeFirst.cs
Src/Asp.Net/SqlServerTest/Demo/DemoE_CodeFirst.cs
using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OrmTest { public class DemoE_CodeFirst { public static void Init() { Console.WriteLine(""); Console.WriteLine("#### CodeFirst Start ####"); SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.SqlServer, ConnectionString = Config.ConnectionString3, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true }); db.DbMaintenance.CreateDatabase(@"c:\"); db.CodeFirst.InitTables(typeof(CodeFirstTable1));//Create CodeFirstTable1 db.Insertable(new CodeFirstTable1() { Name = "a", Text="a" }).ExecuteCommand(); var list = db.Queryable<CodeFirstTable1>().ToList(); Console.WriteLine("#### CodeFirst end ####"); } } public class CodeFirstTable1 { [SugarColumn(IsIdentity = true, IsPrimaryKey = true)] public int Id { get; set; } public string Name { get; set; } [SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom public string Text { get; set; } [SugarColumn(IsNullable = true)] public DateTime CreateTime { get; set; } } }
using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OrmTest { public class DemoE_CodeFirst { public static void Init() { Console.WriteLine(""); Console.WriteLine("#### CodeFirst Start ####"); SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.SqlServer, ConnectionString = "server=.;uid=sa;pwd=haosql;database=cCcMyDbBaseTest", InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true }); db.DbMaintenance.CreateDatabase(@"c:\"); db.CodeFirst.InitTables(typeof(CodeFirstTable1));//Create CodeFirstTable1 db.Insertable(new CodeFirstTable1() { Name = "a", Text="a" }).ExecuteCommand(); var list = db.Queryable<CodeFirstTable1>().ToList(); Console.WriteLine("#### CodeFirst end ####"); } } public class CodeFirstTable1 { [SugarColumn(IsIdentity = true, IsPrimaryKey = true)] public int Id { get; set; } public string Name { get; set; } [SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom public string Text { get; set; } [SugarColumn(IsNullable = true)] public DateTime CreateTime { get; set; } } }
apache-2.0
C#
cfbf65d4f76a9f9076cf834c279f9dbfc63595e5
Tweak to method accessibility
boro2g/AlexaCore
AlexaCore/Intents/AlexaIntent.cs
AlexaCore/Intents/AlexaIntent.cs
using System; using System.Collections.Generic; using System.Linq; using Alexa.NET; using Alexa.NET.Request; using Alexa.NET.Response; using AlexaCore.Extensions; namespace AlexaCore.Intents { public abstract class AlexaIntent { protected IntentParameters Parameters; protected Dictionary<string, Slot> Slots { get; private set; } public virtual string IntentName => GetType().Name; protected AlexaIntent(IntentParameters parameters) { Parameters = parameters; } public SkillResponse GetResponse(Dictionary<string, Slot> slots) { Slots = slots; Parameters.Logger.LogLine($"Intent called: {IntentName}"); if (!ValidateSlots(slots)) { return BuildResponse(new PlainTextOutputSpeech { Text = MissingSlotsText() }); } return GetResponseInternal(slots); } public virtual SkillResponse Tell(string message) { return BuildResponse(new PlainTextOutputSpeech {Text = message}); } public virtual SkillResponse BuildResponse(IOutputSpeech outputSpeech) { return ResponseBuilder.Tell(outputSpeech); } protected virtual string MissingSlotsText() { return $"Your request seems to be missing some information. Expected slots are: {RequiredSlots.JoinStringList()}."; } private bool ValidateSlots(Dictionary<string, Slot> slots) { List<string> messages = new List<string>(); foreach (var requiredSlot in RequiredSlots) { if (!slots.ContainsKey(requiredSlot)) { messages.Add($"{IntentName} requires slot {requiredSlot} - it doesn't exist"); } else { var slot = slots[requiredSlot]; if (String.IsNullOrWhiteSpace(slot.Value)) { messages.Add($"{IntentName} requires slot {requiredSlot} - it is empty"); } } } messages.ForEach(Parameters.Logger.LogLine); return !messages.Any(); } protected virtual IEnumerable<string> RequiredSlots => new string[0]; public virtual bool ShouldEndSession { get; set; } = false; protected abstract SkillResponse GetResponseInternal(Dictionary<string, Slot> slots); public virtual CommandDefinition CommandDefinition() { return new CommandDefinition {IntentName = IntentName, ExpectsResponse = this is IntentWithResponse}; } } }
using System; using System.Collections.Generic; using System.Linq; using Alexa.NET; using Alexa.NET.Request; using Alexa.NET.Response; using AlexaCore.Extensions; namespace AlexaCore.Intents { public abstract class AlexaIntent { protected IntentParameters Parameters; protected Dictionary<string, Slot> Slots { get; private set; } public virtual string IntentName => GetType().Name; protected AlexaIntent(IntentParameters parameters) { Parameters = parameters; } public SkillResponse GetResponse(Dictionary<string, Slot> slots) { Slots = slots; Parameters.Logger.LogLine($"Intent called: {IntentName}"); if (!ValidateSlots(slots)) { return BuildResponse(new PlainTextOutputSpeech { Text = MissingSlotsText() }); } return GetResponseInternal(slots); } protected virtual SkillResponse Tell(string message) { return BuildResponse(new PlainTextOutputSpeech {Text = message}); } protected virtual SkillResponse BuildResponse(IOutputSpeech outputSpeech) { return ResponseBuilder.Tell(outputSpeech); } protected virtual string MissingSlotsText() { return $"Your request seems to be missing some information. Expected slots are: {RequiredSlots.JoinStringList()}."; } private bool ValidateSlots(Dictionary<string, Slot> slots) { List<string> messages = new List<string>(); foreach (var requiredSlot in RequiredSlots) { if (!slots.ContainsKey(requiredSlot)) { messages.Add($"{IntentName} requires slot {requiredSlot} - it doesn't exist"); } else { var slot = slots[requiredSlot]; if (String.IsNullOrWhiteSpace(slot.Value)) { messages.Add($"{IntentName} requires slot {requiredSlot} - it is empty"); } } } messages.ForEach(Parameters.Logger.LogLine); return !messages.Any(); } protected virtual IEnumerable<string> RequiredSlots => new string[0]; public virtual bool ShouldEndSession { get; set; } = false; protected abstract SkillResponse GetResponseInternal(Dictionary<string, Slot> slots); public virtual CommandDefinition CommandDefinition() { return new CommandDefinition {IntentName = IntentName, ExpectsResponse = this is IntentWithResponse}; } } }
mit
C#
8e56629f825300a6f6c18904ce9091946352551d
Change the assembly informations
jstuyck/witsmllib
Properties/AssemblyInfo.cs
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("witsmllib")] [assembly: AssemblyDescription("Witsml C# library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Witsmllib")] [assembly: AssemblyCopyright("Apache License, Version 2.0")] [assembly: AssemblyTrademark("Apache License, Version 2.0")] [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("99519b93-8d5d-4e45-a709-66c7577059bc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("nwitsml")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("nwitsml")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [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("99519b93-8d5d-4e45-a709-66c7577059bc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
039f0dd5716d16db57f2f70cc7040d8ed3e80f0d
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
autofac/Autofac.Multitenant
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.Multitenant")] [assembly: ComVisible(false)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.Multitenant")] [assembly: AssemblyDescription("Autofac multitenancy support library.")] [assembly: ComVisible(false)]
mit
C#
b42905bb1c4f87347d36a2c95e99da9417975e8d
bump to version 1.2.4
dnauck/AspSQLProvider,dnauck/AspSQLProvider
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
// // $Id$ // // Copyright 2006 - 2009 Nauck IT KG http://www.nauck-it.de // // Author: // Daniel Nauck <d.nauck(at)nauck-it.de> // // 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.Reflection; using System.Resources; 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("PostgreSQL Provider")] [assembly: AssemblyDescription("PostgreSQL Membership, Role, Profile and Session-State Store Provider for ASP.NET 2.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Nauck IT KG")] [assembly: AssemblyProduct("PostgreSQL Provider")] [assembly: AssemblyCopyright("Copyright 2006 - 2009 Nauck IT KG")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguageAttribute("en")] [assembly: CLSCompliant(true)] // 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("0c7b829a-f6f7-4b4b-9b24-f10eacbbcb93")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.2.4.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
// // $Id$ // // Copyright 2006 - 2009 Nauck IT KG http://www.nauck-it.de // // Author: // Daniel Nauck <d.nauck(at)nauck-it.de> // // 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.Reflection; using System.Resources; 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("PostgreSQL Provider")] [assembly: AssemblyDescription("PostgreSQL Membership, Role, Profile and Session-State Store Provider for ASP.NET 2.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Nauck IT KG")] [assembly: AssemblyProduct("PostgreSQL Provider")] [assembly: AssemblyCopyright("Copyright 2006 - 2009 Nauck IT KG")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguageAttribute("en")] [assembly: CLSCompliant(true)] // 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("0c7b829a-f6f7-4b4b-9b24-f10eacbbcb93")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.2.3.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
db6b684b84b4a8b9f1d28d16c232a2e9b53eb456
Update version to 1.1.1-beta1
bungeemonkee/Transformerizer
Transformerizer/Properties/AssemblyInfo.cs
Transformerizer/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; // 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("Transformerizer")] [assembly: AssemblyDescription("Transformerizer: Parallel transform library for .NET")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Transformerizer")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.1.1.1")] [assembly: AssemblyFileVersion("1.1.1.1")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.1.1-beta1")]
using System.Reflection; using System.Resources; // 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("Transformerizer")] [assembly: AssemblyDescription("Transformerizer: Parallel transform library for .NET")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Transformerizer")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.0.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.0.3")]
mit
C#
3b6a8d803a5507a21e936ae991b8d6fea5a46ef8
Add model binder to binding config
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
WebAPI.API/App_Start/ModelBindingConfig.cs
WebAPI.API/App_Start/ModelBindingConfig.cs
using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using WebAPI.API.ModelBindings.Providers; namespace WebAPI.API { public class ModelBindingConfig { public static void RegisterModelBindings(ServicesContainer services) { services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new ArcGisOnlineOptionsModelBindingProvide()); services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider()); } } }
using System.Web.Http.Controllers; using System.Web.Http.ModelBinding; using WebAPI.API.ModelBindings.Providers; namespace WebAPI.API { public class ModelBindingConfig { public static void RegisterModelBindings(ServicesContainer services) { services.Add(typeof (ModelBinderProvider), new GeocodeOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new RouteMilepostOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new SearchOptionsModelBindingProvider()); services.Add(typeof (ModelBinderProvider), new ReverseMilepostOptionsModelBindingProvider()); } } }
mit
C#
d40a4a6c13ecacede9cc0af353233fc553169016
Remove animator not initialized warning
IGDAStl/gateway2dwest,IGDAStl/gateway2dwest,stlgamedev/gateway2dwest,stlgamedev/gateway2dwest,IGDAStl/gateway2dwest,stlgamedev/gateway2dwest
Assets/Scripts/PlayerMovement.cs
Assets/Scripts/PlayerMovement.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerMovement : MonoBehaviour { public float movementSpeed = 2.0f; public InputHelper inputHelper; public int playerID = 0; //Setting foundation for multiple players Animator animator; Rigidbody2D rb; // Use this for initialization void Start () { animator = GetComponent<Animator> (); //In unity, GetComponent is implicit to the object the script is attached, thus "this" is not needed rb = GetComponent<Rigidbody2D> (); //Gets attached rigidbody2D component } // Update is called once per frame void Update () { Vector2 axis = inputHelper.axisRaw (); //Get's input from helper class. This allows for unit testing as well as changing input while inside of the game. axis = EnsurePlayerNeverMovesFasterThanMaxSpeed (axis); UpdateAnimationStates (axis); rb.velocity = axis * movementSpeed; } private void UpdateAnimationStates (Vector2 axis) { if (Mathf.Abs (axis.x) > Mathf.Abs (axis.y)) { SetAnimationParameters (axis.x, 0.0f); //Sets up walking left/right animation } else if (Mathf.Abs (axis.x) < Mathf.Abs (axis.y)) { SetAnimationParameters (0.0f, axis.y); //Sets up walking up/down animation } else if (axis == Vector2.zero) { //Checking if it's equal to zero will allow animations when sliding against walls to still work SetAnimationParameters (0, 0); //sets up idle animation } } private void SetAnimationParameters (float x, float y) { if (!animator) { animator.SetFloat ("HorizontalMovement", x); animator.SetFloat ("VerticalMovement", y); } } private Vector2 EnsurePlayerNeverMovesFasterThanMaxSpeed (Vector2 axis) { if (Mathf.Abs (axis.magnitude) >= 1) { axis.Normalize (); } return axis; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlayerMovement : MonoBehaviour { public float movementSpeed = 2.0f; public InputHelper inputHelper; public int playerID = 0; //Setting foundation for multiple players Animator animator; Rigidbody2D rb; // Use this for initialization void Start () { animator = GetComponent<Animator> (); //In unity, GetComponent is implicit to the object the script is attached, thus "this" is not needed rb = GetComponent<Rigidbody2D> (); //Gets attached rigidbody2D component } // Update is called once per frame void Update () { Vector2 axis = inputHelper.axisRaw (); //Get's input from helper class. This allows for unit testing as well as changing input while inside of the game. axis = EnsurePlayerNeverMovesFasterThanMaxSpeed (axis); UpdateAnimationStates (axis); rb.velocity = axis * movementSpeed; } private void UpdateAnimationStates (Vector2 axis) { if (Mathf.Abs (axis.x) > Mathf.Abs (axis.y)) { SetAnimationParameters (axis.x, 0.0f); //Sets up walking left/right animation } else if (Mathf.Abs (axis.x) < Mathf.Abs (axis.y)) { SetAnimationParameters (0.0f, axis.y); //Sets up walking up/down animation } else if (axis == Vector2.zero) { //Checking if it's equal to zero will allow animations when sliding against walls to still work SetAnimationParameters (0, 0); //sets up idle animation } } private void SetAnimationParameters (float x, float y) { animator.SetFloat ("HorizontalMovement", x); animator.SetFloat ("VerticalMovement", y); } private Vector2 EnsurePlayerNeverMovesFasterThanMaxSpeed (Vector2 axis) { if (Mathf.Abs (axis.magnitude) >= 1) { axis.Normalize (); } return axis; } }
apache-2.0
C#
1826965ea15fe44ecd590b60f43c72686eb4b51a
Address null ref when we can't get an Undo manager.
mattwar/roslyn,Hosch250/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,aelij/roslyn,jmarolf/roslyn,AmadeusW/roslyn,pdelvo/roslyn,stephentoub/roslyn,agocke/roslyn,pdelvo/roslyn,mattwar/roslyn,TyOverby/roslyn,CyrusNajmabadi/roslyn,Giftednewt/roslyn,mattscheffer/roslyn,drognanar/roslyn,khyperia/roslyn,aelij/roslyn,diryboy/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,tmat/roslyn,KevinRansom/roslyn,jcouv/roslyn,Giftednewt/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,paulvanbrenk/roslyn,DustinCampbell/roslyn,amcasey/roslyn,dpoeschl/roslyn,bkoelman/roslyn,mavasani/roslyn,yeaicc/roslyn,Hosch250/roslyn,diryboy/roslyn,abock/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,lorcanmooney/roslyn,jasonmalinowski/roslyn,Giftednewt/roslyn,AnthonyDGreen/roslyn,CaptainHayashi/roslyn,shyamnamboodiripad/roslyn,zooba/roslyn,amcasey/roslyn,lorcanmooney/roslyn,sharwell/roslyn,brettfo/roslyn,Hosch250/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,KirillOsenkov/roslyn,cston/roslyn,physhi/roslyn,abock/roslyn,KevinRansom/roslyn,yeaicc/roslyn,tmeschter/roslyn,jeffanders/roslyn,dpoeschl/roslyn,CaptainHayashi/roslyn,orthoxerox/roslyn,TyOverby/roslyn,jcouv/roslyn,dotnet/roslyn,tannergooding/roslyn,weltkante/roslyn,agocke/roslyn,drognanar/roslyn,jeffanders/roslyn,CyrusNajmabadi/roslyn,xasx/roslyn,mmitche/roslyn,genlu/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,heejaechang/roslyn,physhi/roslyn,weltkante/roslyn,sharwell/roslyn,bartdesmet/roslyn,khyperia/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,heejaechang/roslyn,zooba/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,abock/roslyn,jamesqo/roslyn,nguerrera/roslyn,mattwar/roslyn,OmarTawfik/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,jeffanders/roslyn,drognanar/roslyn,tmat/roslyn,wvdd007/roslyn,jamesqo/roslyn,mavasani/roslyn,AlekseyTs/roslyn,diryboy/roslyn,xasx/roslyn,panopticoncentral/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,xasx/roslyn,physhi/roslyn,akrisiun/roslyn,aelij/roslyn,eriawan/roslyn,wvdd007/roslyn,MattWindsor91/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,VSadov/roslyn,mgoertz-msft/roslyn,zooba/roslyn,CyrusNajmabadi/roslyn,robinsedlaczek/roslyn,cston/roslyn,tmeschter/roslyn,genlu/roslyn,tvand7093/roslyn,nguerrera/roslyn,bkoelman/roslyn,bartdesmet/roslyn,weltkante/roslyn,amcasey/roslyn,mattscheffer/roslyn,khyperia/roslyn,paulvanbrenk/roslyn,agocke/roslyn,OmarTawfik/roslyn,eriawan/roslyn,jcouv/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,dotnet/roslyn,tmat/roslyn,jasonmalinowski/roslyn,jkotas/roslyn,bartdesmet/roslyn,nguerrera/roslyn,gafter/roslyn,AlekseyTs/roslyn,mmitche/roslyn,MattWindsor91/roslyn,gafter/roslyn,kelltrick/roslyn,srivatsn/roslyn,reaction1989/roslyn,davkean/roslyn,bkoelman/roslyn,DustinCampbell/roslyn,jkotas/roslyn,tvand7093/roslyn,srivatsn/roslyn,wvdd007/roslyn,pdelvo/roslyn,tvand7093/roslyn,panopticoncentral/roslyn,dotnet/roslyn,AlekseyTs/roslyn,mavasani/roslyn,orthoxerox/roslyn,yeaicc/roslyn,kelltrick/roslyn,stephentoub/roslyn,AnthonyDGreen/roslyn,heejaechang/roslyn,gafter/roslyn,kelltrick/roslyn,sharwell/roslyn,tannergooding/roslyn,cston/roslyn,paulvanbrenk/roslyn,robinsedlaczek/roslyn,OmarTawfik/roslyn,TyOverby/roslyn,VSadov/roslyn,lorcanmooney/roslyn,CaptainHayashi/roslyn,ErikSchierboom/roslyn,orthoxerox/roslyn,akrisiun/roslyn,reaction1989/roslyn,robinsedlaczek/roslyn,brettfo/roslyn,jmarolf/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,MichalStrehovsky/roslyn,jkotas/roslyn,davkean/roslyn,brettfo/roslyn,jamesqo/roslyn,DustinCampbell/roslyn,VSadov/roslyn,AmadeusW/roslyn,mattscheffer/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,dpoeschl/roslyn,shyamnamboodiripad/roslyn,akrisiun/roslyn,AnthonyDGreen/roslyn
src/VisualStudio/Core/Def/Utilities/IVsEditorAdaptersFactoryServiceExtensions.cs
src/VisualStudio/Core/Def/Utilities/IVsEditorAdaptersFactoryServiceExtensions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Utilities { internal static class IVsEditorAdaptersFactoryServiceExtensions { public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Workspace workspace, DocumentId contextDocumentId, CancellationToken cancellationToken) { var document = workspace.CurrentSolution.GetDocument(contextDocumentId); var text = document?.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var textSnapshot = text.FindCorrespondingEditorTextSnapshot(); var textBuffer = textSnapshot?.TextBuffer; return editorAdaptersFactoryService.TryGetUndoManager(textBuffer); } public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer) { if (subjectBuffer != null) { var adapter = editorAdaptersFactoryService?.GetBufferAdapter(subjectBuffer); if (adapter != null) { if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager))) { return manager; } } } return null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Utilities { internal static class IVsEditorAdaptersFactoryServiceExtensions { public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, Workspace workspace, DocumentId contextDocumentId, CancellationToken cancellationToken) { var document = workspace.CurrentSolution.GetDocument(contextDocumentId); var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var textSnapshot = text.FindCorrespondingEditorTextSnapshot(); var textBuffer = textSnapshot?.TextBuffer; return editorAdaptersFactoryService.TryGetUndoManager(textBuffer); } public static IOleUndoManager TryGetUndoManager( this IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextBuffer subjectBuffer) { if (subjectBuffer != null) { var adapter = editorAdaptersFactoryService.GetBufferAdapter(subjectBuffer); if (adapter != null) { if (ErrorHandler.Succeeded(adapter.GetUndoManager(out var manager))) { return manager; } } } return null; } } }
mit
C#
ae2a50a6879f201ad9b80c3cf2b77cb7ced5c9c4
upgrade code
pid011/BackupCode
HelloWorld/HelloWorld/HelloWorld.cs
HelloWorld/HelloWorld/HelloWorld.cs
using System; namespace HelloWorld { class Program { static void Main(string[] args) { int num = 4; string result = (num % 2 == 0) ? "even number" : "odd number"; Console.WriteLine(result); //----디버그 모드에서 창이 바로 닫히는 문제를 위한 코드---- Console.ReadKey(); } } }
using System; namespace HelloWorld { class Program { static void Main(string[] args) { int[] numbers = { 1023, 1023, 1034, 1087 }; bool result = !(numbers[0] > numbers[2]) && numbers[0] == numbers[1] && numbers[1] <= numbers[3]; if (result) { Console.WriteLine("맞습니다"); } else { Console.WriteLine("틀립니다"); } //----디버그 모드에서 창이 바로 닫히는 문제를 위한 코드---- Console.ReadKey(); } } }
mit
C#
b362795cfd2ec93268205e93da37ea3506dcd7dc
Hide menu bar if it has no items
PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto
Source/Eto.WinForms/Forms/Menu/MenuBarHandler.cs
Source/Eto.WinForms/Forms/Menu/MenuBarHandler.cs
using SWF = System.Windows.Forms; using Eto.Forms; using System.Collections.Generic; namespace Eto.WinForms { /// <summary> /// Summary description for MenuBarHandler. /// </summary> public class MenuBarHandler : WidgetHandler<SWF.MenuStrip, MenuBar>, MenuBar.IHandler { public MenuBarHandler() { Control = new SWF.MenuStrip { Visible = false }; } #region IMenu Members public void AddMenu(int index, MenuItem item) { Control.Items.Insert(index, (SWF.ToolStripItem)item.ControlObject); Control.Visible = true; } public void RemoveMenu(MenuItem item) { Control.Items.Remove((SWF.ToolStripItem)item.ControlObject); Control.Visible = Control.Items.Count > 0; } public void Clear() { Control.Items.Clear(); Control.Visible = false; } #endregion MenuItem quitItem; public void SetQuitItem(MenuItem item) { item.Order = 1000; if (quitItem != null) ApplicationMenu.Items.Remove(quitItem); else ApplicationMenu.Items.AddSeparator(999); ApplicationMenu.Items.Add(item); quitItem = item; } MenuItem aboutItem; public void SetAboutItem(MenuItem item) { item.Order = 1000; if (aboutItem != null) HelpMenu.Items.Remove(aboutItem); else HelpMenu.Items.AddSeparator(999); HelpMenu.Items.Add(item); aboutItem = item; } public void CreateSystemMenu() { // no system menu items } public void CreateLegacySystemMenu() { } public IEnumerable<Command> GetSystemCommands() { yield break; } public ButtonMenuItem ApplicationMenu { get { return Widget.Items.GetSubmenu("&File", -100); } } public ButtonMenuItem HelpMenu { get { return Widget.Items.GetSubmenu("&Help", 1000); } } } }
using SWF = System.Windows.Forms; using Eto.Forms; using System.Collections.Generic; namespace Eto.WinForms { /// <summary> /// Summary description for MenuBarHandler. /// </summary> public class MenuBarHandler : WidgetHandler<SWF.MenuStrip, MenuBar>, MenuBar.IHandler { public MenuBarHandler() { Control = new SWF.MenuStrip(); } #region IMenu Members public void AddMenu(int index, MenuItem item) { Control.Items.Insert(index, (SWF.ToolStripItem)item.ControlObject); } public void RemoveMenu(MenuItem item) { Control.Items.Remove((SWF.ToolStripItem)item.ControlObject); } public void Clear() { Control.Items.Clear(); } #endregion MenuItem quitItem; public void SetQuitItem(MenuItem item) { item.Order = 1000; if (quitItem != null) ApplicationMenu.Items.Remove(quitItem); else ApplicationMenu.Items.AddSeparator(999); ApplicationMenu.Items.Add(item); quitItem = item; } MenuItem aboutItem; public void SetAboutItem(MenuItem item) { item.Order = 1000; if (aboutItem != null) HelpMenu.Items.Remove(aboutItem); else HelpMenu.Items.AddSeparator(999); HelpMenu.Items.Add(item); aboutItem = item; } public void CreateSystemMenu() { // no system menu items } public void CreateLegacySystemMenu() { } public IEnumerable<Command> GetSystemCommands() { yield break; } public ButtonMenuItem ApplicationMenu { get { return Widget.Items.GetSubmenu("&File", -100); } } public ButtonMenuItem HelpMenu { get { return Widget.Items.GetSubmenu("&Help", 1000); } } } }
bsd-3-clause
C#
da16a09fa9f54c45047239904d9cd2f6c863c951
Change to ratio
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/GameModes/Traitor.cs
UnityProject/Assets/Scripts/GameModes/Traitor.cs
using UnityEngine; using Antagonists; using System.Collections.Generic; using System; [CreateAssetMenu(menuName="ScriptableObjects/GameModes/Traitor")] public class Traitor : GameMode { [Tooltip("Ratio of traitors to player count. A value of 0.2 means there would be " + "2 traitors when there are 10 players.")] [Range(0, 1)] [SerializeField] private float TraitorRatio; /// <summary> /// Set up the station for the game mode /// </summary> public override void SetupRound() { Logger.Log("Setting up traitor round!", Category.GameMode); } /// <summary> /// Begin the round /// </summary> public override void StartRound() { Logger.Log("Starting traitor round!", Category.GameMode); base.StartRound(); } // /// <summary> // /// Check if the round should end yet // /// </summary> // public override void CheckEndCondition() // { // Logger.Log("Check end round conditions!", Category.GameMode); // } // /// <summary> // /// End the round and display any relevant reports // /// </summary> // public override void EndRound() // { // } private List<JobType> LoyalImplanted = new List<JobType> { JobType.CAPTAIN, JobType.HOP, JobType.HOS, JobType.WARDEN, JobType.SECURITY_OFFICER, JobType.DETECTIVE, }; protected override bool ShouldSpawnAntag(PlayerSpawnRequest spawnRequest) { // Populates traitors based on the ratio set return !LoyalImplanted.Contains(spawnRequest.RequestedOccupation.JobType) && AntagManager.Instance.AntagCount <= Math.Floor(PlayerList.Instance.InGamePlayers.Count * TraitorRatio) && PlayerList.Instance.InGamePlayers.Count > 0; } }
using UnityEngine; using Antagonists; using System.Collections.Generic; [CreateAssetMenu(menuName="ScriptableObjects/GameModes/Traitor")] public class Traitor : GameMode { private float TraitorAmount = 0; /// <summary> /// Set up the station for the game mode /// </summary> public override void SetupRound() { Logger.Log("Setting up traitor round!", Category.GameMode); //Populates traitors based on server population if (PlayerList.Instance.InGamePlayers.Count >= 50) { TraitorAmount = 5; } else if (PlayerList.Instance.InGamePlayers.Count >= 30) { TraitorAmount = 4; } else if (PlayerList.Instance.InGamePlayers.Count >= 24) { TraitorAmount = 3; } else if (PlayerList.Instance.InGamePlayers.Count >= 15) { TraitorAmount = 2; } else { TraitorAmount = 1; } } /// <summary> /// Begin the round /// </summary> public override void StartRound() { Logger.Log("Starting traitor round!", Category.GameMode); base.StartRound(); } // /// <summary> // /// Check if the round should end yet // /// </summary> // public override void CheckEndCondition() // { // Logger.Log("Check end round conditions!", Category.GameMode); // } // /// <summary> // /// End the round and display any relevant reports // /// </summary> // public override void EndRound() // { // } private List<JobType> LoyalImplanted = new List<JobType> { JobType.CAPTAIN, JobType.HOP, JobType.HOS, JobType.WARDEN, JobType.SECURITY_OFFICER, JobType.DETECTIVE, }; protected override bool ShouldSpawnAntag(PlayerSpawnRequest spawnRequest) { return !LoyalImplanted.Contains(spawnRequest.RequestedOccupation.JobType) && AntagManager.Instance.AntagCount <= TraitorAmount && PlayerList.Instance.InGamePlayers.Count > 0; } }
agpl-3.0
C#
345430ab39d45f7d47231b080472bb660c364e0a
Fix argon hit target area not being aligned correctly
peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Mania/Skinning/Argon/ArgonHitTarget.cs
osu.Game.Rulesets.Mania/Skinning/Argon/ArgonHitTarget.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Mania.Skinning.Default; using osu.Game.Rulesets.UI.Scrolling; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Skinning.Argon { public class ArgonHitTarget : CompositeDrawable { private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>(); [BackgroundDependencyLoader] private void load(IScrollingInfo scrollingInfo) { RelativeSizeAxes = Axes.X; Height = DefaultNotePiece.NOTE_HEIGHT; InternalChildren = new[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.3f, Blending = BlendingParameters.Additive, Colour = Color4.White }, }; direction.BindTo(scrollingInfo.Direction); direction.BindValueChanged(onDirectionChanged, true); } private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> direction) { Anchor = Origin = direction.NewValue == ScrollingDirection.Up ? Anchor.TopLeft : Anchor.BottomLeft; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Mania.Skinning.Default; using osuTK.Graphics; namespace osu.Game.Rulesets.Mania.Skinning.Argon { public class ArgonHitTarget : CompositeDrawable { [BackgroundDependencyLoader] private void load() { RelativeSizeAxes = Axes.X; Height = DefaultNotePiece.NOTE_HEIGHT; InternalChildren = new[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.3f, Blending = BlendingParameters.Additive, Colour = Color4.White }, }; } } }
mit
C#
26d8f415d65e97e5914656fdeeecfcec33ab7928
check null when sanitizing the log
projectkudu/TryAppService,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/TryAppService,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,fashaikh/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/TryAppService,fashaikh/SimpleWAWS,fashaikh/SimpleWAWS
SimpleWAWS/Trace/SimpleTrace.cs
SimpleWAWS/Trace/SimpleTrace.cs
using Serilog; using SimpleWAWS.Code; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Web; namespace SimpleWAWS.Trace { public static class SimpleTrace { public static ILogger Analytics; public static ILogger Diagnostics; public static void TraceInformation(string message) { System.Diagnostics.Trace.TraceInformation(message); } public static void TraceInformation(string format, params string[] args) { if (args.Length > 0) { args[0] = string.Concat(args[0], "#", ExperimentManager.GetCurrentExperiment(), "$", ExperimentManager.GetCurrentSourceVariation(), "%", CultureInfo.CurrentCulture.EnglishName); } args = args.Select(e => e?.Replace(";", "&semi")).ToArray(); System.Diagnostics.Trace.TraceInformation(format, args); } public static void TraceError(string message) { System.Diagnostics.Trace.TraceError(message); } public static void TraceError(string format, params string[] args) { if (args.Length > 0) { args[0] = string.Concat(args[0], "#", ExperimentManager.GetCurrentExperiment(), "$", ExperimentManager.GetCurrentSourceVariation(), "%", CultureInfo.CurrentCulture.EnglishName); } System.Diagnostics.Trace.TraceError(format, args); } public static void TraceWarning(string message) { System.Diagnostics.Trace.TraceWarning(message); } public static void TraceWarning(string format, params string[] args) { if (args.Length > 0) { args[0] = string.Concat(args[0], "#", ExperimentManager.GetCurrentExperiment(), "$", ExperimentManager.GetCurrentSourceVariation(), "%", CultureInfo.CurrentCulture.EnglishName); } System.Diagnostics.Trace.TraceWarning(format, args); } } }
using Serilog; using SimpleWAWS.Code; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Web; namespace SimpleWAWS.Trace { public static class SimpleTrace { public static ILogger Analytics; public static ILogger Diagnostics; public static void TraceInformation(string message) { System.Diagnostics.Trace.TraceInformation(message); } public static void TraceInformation(string format, params string[] args) { if (args.Length > 0) { args[0] = string.Concat(args[0], "#", ExperimentManager.GetCurrentExperiment(), "$", ExperimentManager.GetCurrentSourceVariation(), "%", CultureInfo.CurrentCulture.EnglishName); } var cleaned = args.Select(e => e.Replace(";", "&semi")); System.Diagnostics.Trace.TraceInformation(format, cleaned); } public static void TraceError(string message) { System.Diagnostics.Trace.TraceError(message); } public static void TraceError(string format, params string[] args) { if (args.Length > 0) { args[0] = string.Concat(args[0], "#", ExperimentManager.GetCurrentExperiment(), "$", ExperimentManager.GetCurrentSourceVariation(), "%", CultureInfo.CurrentCulture.EnglishName); } System.Diagnostics.Trace.TraceError(format, args); } public static void TraceWarning(string message) { System.Diagnostics.Trace.TraceWarning(message); } public static void TraceWarning(string format, params string[] args) { if (args.Length > 0) { args[0] = string.Concat(args[0], "#", ExperimentManager.GetCurrentExperiment(), "$", ExperimentManager.GetCurrentSourceVariation(), "%", CultureInfo.CurrentCulture.EnglishName); } System.Diagnostics.Trace.TraceWarning(format, args); } } }
apache-2.0
C#
8aadc3c92d84f0382b82216f93efeb6a20de3435
Add assembly description
reznet/MusicXml.Net,gerryaobrien/MusicXml.Net,vdaron/MusicXml.Net
MusicXml/Properties/AssemblyInfo.cs
MusicXml/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("MusicXml")] [assembly: AssemblyDescription("MusicXML file parser for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MusicXml")] [assembly: AssemblyCopyright("Copyright © Vincent DARON - Steven Solomon 2008-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("86ac64b2-a7dd-4017-a153-50e1aa397901")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MusicXml")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MusicXml")] [assembly: AssemblyCopyright("Copyright © Vincent DARON - Steven Solomon 2008-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("86ac64b2-a7dd-4017-a153-50e1aa397901")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
bsd-3-clause
C#
23a33d090ec7b81373634af81eff3bbc43eb7436
Enable cmdline output
PingOwin/pingowin
source/PingIt.Cmd/Program.cs
source/PingIt.Cmd/Program.cs
using System.Configuration; using System.Linq; using PingIt.Lib; namespace PingIt.Cmd { class Program { static void Main(string[] args) { var urlsCsv = ConfigurationManager.AppSettings["urls"]; var urls = urlsCsv.Split(';'); var transformer = new SlackMessageTransformer(Level.OK); var outputter = CreateOutputter(); if (args.Length >= 1 && args.First() == "debug") { var debugInfo = transformer.TransformDebugInfo(urls); outputter.SendToOutput(debugInfo); } else { var pinger = new Pinger(new PingConfiguration()); var pingResults = pinger.PingUrls(urls).GetAwaiter().GetResult(); var output = transformer.Transform(pingResults); outputter.SendToOutput(output).GetAwaiter().GetResult(); } } public static IOutput CreateOutputter() { if (ConfigurationManager.AppSettings["output"] == "1") { return new SlackOutputter(new SlackOutputConfig()); } return new ConsoleOutputter(); } public static ITransformResponses CreateTransformer() { return new SlackMessageTransformer(Level.OK); } } }
using System.Configuration; using System.Linq; using PingIt.Lib; namespace PingIt.Cmd { class Program { static void Main(string[] args) { var urlsCsv = ConfigurationManager.AppSettings["urls"]; var urls = urlsCsv.Split(';'); var transformer = new SlackMessageTransformer(Level.OK); var outputter = CreateOutputter(); if (args.Length >= 1 && args.First() == "debug") { var debugInfo = transformer.TransformDebugInfo(urls); outputter.SendToOutput(debugInfo); } else { var pinger = new Pinger(new PingConfiguration()); var pingResults = pinger.PingUrls(urls).GetAwaiter().GetResult(); var output = transformer.Transform(pingResults); outputter.SendToOutput(output); } } public static IOutput CreateOutputter() { if (ConfigurationManager.AppSettings["output"] == "1") { return new SlackOutputter(new SlackOutputConfig()); } return new ConsoleOutputter(); } public static ITransformResponses CreateTransformer() { return new SlackMessageTransformer(Level.OK); } } }
mit
C#
d5f7c73600117acf4b21614637172fdfdb1dd20c
Update table stlye for Bootstrap
Neurothustra/ProductGrid,Neurothustra/ProductGrid,Neurothustra/ProductGrid
ProductGrid/Views/Home/Index.cshtml
ProductGrid/Views/Home/Index.cshtml
@model IEnumerable<ProductGrid.Models.Product> @{ ViewBag.Title = "Index"; //WebGrid displays data on a web page using an HTML table element. //In this instance, I've provided the constructor with a couple of arguments: Model is obviously the data object, //ajaxUpdateContainerId looks in the DOM for the Id container to make dynamic Ajax updates, defaultSort indicates the default //column on which to begin filtering //more info at https://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid(v=vs.111).aspx WebGrid grid = new WebGrid(Model, ajaxUpdateContainerId: "productGrid", defaultSort: "Name"); } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <div id="productGrid"> @*Returns the HTML markup that is used to render the WebGrid instance and using the specified paging options. more information at https://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid.gethtml(v=vs.111).aspx*@ @grid.GetHtml(tableStyle: "table",//from the Bootstrap css headerStyle: "header", footerStyle: "footer", alternatingRowStyle: "alternate", selectedRowStyle: "selected", columns: grid.Columns( //Create the ActionLink to enable linking to other views, such as Details or Edit //More info at https://msdn.microsoft.com/en-us/magazine/hh288075.aspx grid.Column("Name", format: @<text>@Html.ActionLink((string)item.Name, "Edit", "Home", new {id=item.ProductId}, null)</text>), grid.Column("Description", "Description", style: "description"), grid.Column("Quantity", "Quantity") )) </div>
@model IEnumerable<ProductGrid.Models.Product> @{ ViewBag.Title = "Index"; //WebGrid displays data on a web page using an HTML table element. //In this instance, I've provided the constructor with a couple of arguments: Model is obviously the data object, //ajaxUpdateContainerId looks in the DOM for the Id container to make dynamic Ajax updates, defaultSort indicates the default //column on which to begin filtering //more info at https://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid(v=vs.111).aspx WebGrid grid = new WebGrid(Model, ajaxUpdateContainerId: "productGrid", defaultSort: "Name"); } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <div id="productGrid"> @*Returns the HTML markup that is used to render the WebGrid instance and using the specified paging options. more information at https://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid.gethtml(v=vs.111).aspx*@ @grid.GetHtml(tableStyle: "grid", headerStyle: "header", footerStyle: "footer", alternatingRowStyle: "alternate", selectedRowStyle: "selected", columns: grid.Columns( //Create the ActionLink to enable linking to other views, such as Details or Edit //More info at https://msdn.microsoft.com/en-us/magazine/hh288075.aspx grid.Column("Name", format: @<text>@Html.ActionLink((string)item.Name, "Edit", "Home", new {id=item.ProductId}, null)</text>), grid.Column("Description", "Description", style: "description"), grid.Column("Quantity", "Quantity") )) </div>
mit
C#
2da346b68cde29543e44c2cd37f703a2ba6d4ca6
fix sample
mvcguy/AMQ.Wrapper
Example2/MessageStorageService.cs
Example2/MessageStorageService.cs
using System; using System.Collections.Generic; using Apache.NMS; namespace Example2 { public class MessageStorageService : IMessageStorageService { public List<MessageHistoryItem> Store = new List<MessageHistoryItem>(); public MessageHistoryItem GetMessageHistoryItem(string messageId) { return Store.Find(x => x.MessageId.ToString() == messageId); } public MessageHistoryItem AddOrUpdateMessageHistoryItem(IMessage message, bool isProcessed) { var item = GetMessageHistoryItem(message.NMSCorrelationID); if (item != null) { item.MessageProcessed = isProcessed; item.LastProcessedOn = DateTime.Now; item.Redelivered = true; item.RedeliveredCount = item.RedeliveredCount + 1; } else { item = new MessageHistoryItem() { CreatedDatetime = DateTime.Now, LastProcessedOn = DateTime.Now, MessageProcessed = isProcessed, MessageId = new Guid(message.NMSCorrelationID), Redelivered = false, RedeliveredCount = 0, }; Store.Add(item); } return item; } } }
using System; using System.Collections.Generic; using Apache.NMS; namespace Example2 { public class MessageStorageService : IMessageStorageService { public List<MessageHistoryItem> Store = new List<MessageHistoryItem>(); public MessageHistoryItem GetMessageHistoryItem(string messageId) { return Store.Find(x => x.MessageId.ToString() == messageId); } public MessageHistoryItem AddOrUpdateMessageHistoryItem(IMessage message, bool isProcessed) { var item = GetMessageHistoryItem(message.NMSCorrelationID); if (item != null) { item.MessageProcessed = true; item.LastProcessedOn = DateTime.Now; } else { item = new MessageHistoryItem() { CreatedDatetime = DateTime.Now, LastProcessedOn = DateTime.Now, MessageProcessed = false, MessageId = new Guid(message.NMSCorrelationID) }; Store.Add(item); } return item; } } }
apache-2.0
C#
c8900f4f4610519ff6de5ca721ae5649681628cc
Declare array parameter as an IReadOnlyList<T> since the array need not be used as mutable.
EliotJones/fixie,Duohong/fixie,bardoloi/fixie,bardoloi/fixie,fixie/fixie,KevM/fixie,JakeGinnivan/fixie
src/Fixie/ClassExecution.cs
src/Fixie/ClassExecution.cs
using System; using System.Collections.Generic; namespace Fixie { public class ClassExecution { public ClassExecution(ExecutionPlan executionPlan, Type testClass, IReadOnlyList<CaseExecution> caseExecutions) { ExecutionPlan = executionPlan; TestClass = testClass; CaseExecutions = caseExecutions; } public ExecutionPlan ExecutionPlan { get; private set; } public Type TestClass { get; private set; } public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; } public void FailCases(Exception exception) { foreach (var caseExecution in CaseExecutions) caseExecution.Fail(exception); } } }
using System; using System.Collections.Generic; namespace Fixie { public class ClassExecution { public ClassExecution(ExecutionPlan executionPlan, Type testClass, CaseExecution[] caseExecutions) { ExecutionPlan = executionPlan; TestClass = testClass; CaseExecutions = caseExecutions; } public ExecutionPlan ExecutionPlan { get; private set; } public Type TestClass { get; private set; } public IReadOnlyList<CaseExecution> CaseExecutions { get; private set; } public void FailCases(Exception exception) { foreach (var caseExecution in CaseExecutions) caseExecution.Fail(exception); } } }
mit
C#
cde72f385cb18e3d1c6e8ebcd10e6e7177592c57
Refactor to use UseBusDiagnostics extension
tomaszkiewicz/rsb
SampleDiscoverableModule/Program.cs
SampleDiscoverableModule/Program.cs
using System; using System.Threading; using RSB; using RSB.Diagnostics; using RSB.Transports.RabbitMQ; namespace SampleDiscoverableModule { class Program { static void Main(string[] args) { var bus = new Bus(RabbitMqTransport.FromConfigurationFile()); bus.UseBusDiagnostics("SampleDiscoverableModule", diagnostics => { diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () => { Thread.Sleep(6000); return true; }); }); Console.ReadLine(); } } }
using System; using RSB; using RSB.Diagnostics; using RSB.Transports.RabbitMQ; namespace SampleDiscoverableModule { class Program { static void Main(string[] args) { var bus = new Bus(RabbitMqTransport.FromConfigurationFile()); var diagnostics = new BusDiagnostics(bus,"SampleDiscoverableModule"); diagnostics.RegisterSubsystemHealthChecker("sampleSubsystem1", () => true); Console.ReadLine(); } } }
bsd-3-clause
C#
379ca7f133ba53679149d650b3e082b3ca9dda3c
remove unnecessary stream.
sassembla/Autoya,sassembla/Autoya,sassembla/Autoya
Assets/Autoya/Encrypt/RIPEMD160.cs
Assets/Autoya/Encrypt/RIPEMD160.cs
using System.IO; using System.Security.Cryptography; using System.Text; namespace AutoyaFramework.Encrypt.RIPEMD { public static class RIPEMD { private static UTF8Encoding utf8Enc = new UTF8Encoding(); public static string RIPEMD160 (string baseStr, string key) { var sourceBytes = utf8Enc.GetBytes(baseStr); var keyBytes = utf8Enc.GetBytes(key); var ripemd160 = new HMACRIPEMD160(keyBytes); var hashBytes = ripemd160.ComputeHash(sourceBytes); ripemd160.Clear(); var hashStr = string.Empty; foreach (var hashByte in hashBytes) { hashStr += string.Format("{0,0:x2}", hashByte); } return hashStr; } } }
using System.IO; using System.Security.Cryptography; using System.Text; namespace AutoyaFramework.Encrypt.RIPEMD { public static class RIPEMD { private static UTF8Encoding utf8Enc = new UTF8Encoding(); public static string RIPEMD160 (string baseStr, string key) { var sourceBytes = utf8Enc.GetBytes(baseStr); var keyBytes = utf8Enc.GetBytes(key); var ripemd160 = new HMACRIPEMD160(keyBytes); var outStream = new MemoryStream(); var hashBytes = ripemd160.ComputeHash(sourceBytes); ripemd160.Clear(); var hashStr = string.Empty; foreach (var hashByte in hashBytes) { hashStr += string.Format("{0,0:x2}", hashByte); } return hashStr; } } }
mit
C#
7956070a562990a7ac8b3c57861ad725efeb93d1
Include the recording number in the default format
Heufneutje/AudioSharp,Heufneutje/HeufyAudioRecorder
AudioSharp.Config/ConfigHandler.cs
AudioSharp.Config/ConfigHandler.cs
using System; using System.Collections.Generic; using System.IO; using System.Windows.Input; using AudioSharp.Utils; using Newtonsoft.Json; namespace AudioSharp.Config { public class ConfigHandler { public static void SaveConfig(Configuration config) { string json = JsonConvert.SerializeObject(config); File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json); } public static Configuration ReadConfig() { string path = Path.Combine(FileUtils.AppDataFolder, "settings.json"); if (File.Exists(path)) { string json = File.ReadAllText(path); return JsonConvert.DeserializeObject<Configuration>(json); } return new Configuration() { RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), RecordingPrefix = "Recording{n}", NextRecordingNumber = 1, AutoIncrementRecordingNumber = true, OutputFormat = "wav", ShowTrayIcon = true, GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(), RecordingSettingsPanelVisible = true, RecordingOutputPanelVisible = true }; } } }
using System; using System.Collections.Generic; using System.IO; using System.Windows.Input; using AudioSharp.Utils; using Newtonsoft.Json; namespace AudioSharp.Config { public class ConfigHandler { public static void SaveConfig(Configuration config) { string json = JsonConvert.SerializeObject(config); File.WriteAllText(Path.Combine(FileUtils.AppDataFolder, "settings.json"), json); } public static Configuration ReadConfig() { string path = Path.Combine(FileUtils.AppDataFolder, "settings.json"); if (File.Exists(path)) { string json = File.ReadAllText(path); return JsonConvert.DeserializeObject<Configuration>(json); } return new Configuration() { RecordingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), RecordingPrefix = "Recording", NextRecordingNumber = 1, AutoIncrementRecordingNumber = true, OutputFormat = "wav", ShowTrayIcon = true, GlobalHotkeys = new Dictionary<HotkeyUtils.HotkeyType, Tuple<Key, ModifierKeys>>(), RecordingSettingsPanelVisible = true, RecordingOutputPanelVisible = true }; } } }
mit
C#
d22609acea393ea975dff389794f4051752a06ed
Fix parsing of GoAway frame additional data
Redth/HttpTwo,Redth/HttpTwo,Redth/HttpTwo
HttpTwo/Frames/GoAwayFrame.cs
HttpTwo/Frames/GoAwayFrame.cs
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Collections.Specialized; using System.Net.Security; using System.Net.Sockets; using System.Threading.Tasks; using System.Threading; namespace HttpTwo { public class GoAwayFrame : Frame { public uint LastStreamId { get;set; } public uint ErrorCode { get;set; } public byte[] AdditionalDebugData { get; set; } // type=0x7 public override FrameType Type { get { return FrameType.GoAway; } } public override IEnumerable<byte> Payload { get { var data = new List<byte> (); // 1 Bit reserved as unset (0) so let's take the first bit of the next 32 bits and unset it data.AddRange (Util.ConvertToUInt31 (LastStreamId).EnsureBigEndian ()); data.AddRange (BitConverter.GetBytes (ErrorCode).EnsureBigEndian ()); if (AdditionalDebugData != null && AdditionalDebugData.Length > 0) data.AddRange (AdditionalDebugData); return data; } } public override void ParsePayload (byte[] payloadData, FrameHeader frameHeader) { // we need to turn the stream id into a uint var frameStreamIdData = new byte[4]; Array.Copy (payloadData, 0, frameStreamIdData, 0, 4); LastStreamId = Util.ConvertFromUInt31 (frameStreamIdData.EnsureBigEndian ()); var errorCodeData = new byte[4]; Array.Copy (payloadData, 4, errorCodeData, 0, 4); uint errorCode = BitConverter.ToUInt32 (errorCodeData.EnsureBigEndian (), 0); ErrorCode = errorCode; if (payloadData.Length > 8) { AdditionalDebugData = new byte[payloadData.Length - 8]; Array.Copy(payloadData, 8, AdditionalDebugData, 0, payloadData.Length - 8); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Collections.Specialized; using System.Net.Security; using System.Net.Sockets; using System.Threading.Tasks; using System.Threading; namespace HttpTwo { public class GoAwayFrame : Frame { public uint LastStreamId { get;set; } public uint ErrorCode { get;set; } public byte[] AdditionalDebugData { get; set; } // type=0x7 public override FrameType Type { get { return FrameType.GoAway; } } public override IEnumerable<byte> Payload { get { var data = new List<byte> (); // 1 Bit reserved as unset (0) so let's take the first bit of the next 32 bits and unset it data.AddRange (Util.ConvertToUInt31 (LastStreamId).EnsureBigEndian ()); data.AddRange (BitConverter.GetBytes (ErrorCode).EnsureBigEndian ()); if (AdditionalDebugData != null && AdditionalDebugData.Length > 0) data.AddRange (AdditionalDebugData); return data; } } public override void ParsePayload (byte[] payloadData, FrameHeader frameHeader) { // we need to turn the stream id into a uint var frameStreamIdData = new byte[4]; Array.Copy (payloadData, 0, frameStreamIdData, 0, 4); LastStreamId = Util.ConvertFromUInt31 (frameStreamIdData.EnsureBigEndian ()); var errorCodeData = new byte[4]; Array.Copy (payloadData, 4, errorCodeData, 0, 4); uint errorCode = BitConverter.ToUInt32 (errorCodeData.EnsureBigEndian (), 0); ErrorCode = errorCode; if (payloadData.Length > 8) Array.Copy (payloadData, 8, AdditionalDebugData, 0, payloadData.Length - 8); } } }
apache-2.0
C#
eb4a6351706a99a682778e8b8841c80a075dffa8
Split enum test to 4 separate
joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net
JoinRpg.Web.Test/EnumTests.cs
JoinRpg.Web.Test/EnumTests.cs
using JoinRpg.Domain; using JoinRpg.Services.Interfaces; using JoinRpg.TestHelpers; using JoinRpg.Web.Models; using Xunit; namespace JoinRpg.Web.Test { public class EnumTests { [Fact] public void AccessReason() => EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>(); [Fact] public void ProjectFieldType() => EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>(); [Fact] public void ClaimStatus() => EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>(); [Fact] public void FinanceOperation() => EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>(); } }
using JoinRpg.Domain; using JoinRpg.Services.Interfaces; using JoinRpg.TestHelpers; using JoinRpg.Web.Models; using Xunit; namespace JoinRpg.Web.Test { public class EnumTests { [Fact] public void ProblemEnum() { EnumerationTestHelper.CheckEnums<UserExtensions.AccessReason, AccessReason>(); EnumerationTestHelper.CheckEnums<ProjectFieldViewType, DataModel.ProjectFieldType>(); EnumerationTestHelper.CheckEnums<ClaimStatusView, DataModel.Claim.Status>(); EnumerationTestHelper.CheckEnums<FinanceOperationActionView, FinanceOperationAction>(); } } }
mit
C#
cfb1feeae4e00af55f704270033c5a87e1ed4c06
Fix access modifiers
setchi/NotesEditor,setchi/NoteEditor
Assets/Scripts/UndoRedoManager.cs
Assets/Scripts/UndoRedoManager.cs
using System; using System.Collections.Generic; using UniRx; using UniRx.Triggers; using UnityEngine; public class UndoRedoManager : SingletonGameObject<UndoRedoManager> { Stack<Command> undoStack = new Stack<Command>(); Stack<Command> redoStack = new Stack<Command>(); void Awake() { var model = NotesEditorModel.Instance; model.OnLoadedMusicObservable .DelayFrame(1) .Subscribe(_ => { undoStack.Clear(); redoStack.Clear(); }); this.UpdateAsObservable() .Where(_ => KeyInput.CtrlPlus(KeyCode.Z)) .Subscribe(_ => Undo()); this.UpdateAsObservable() .Where(_ => KeyInput.CtrlPlus(KeyCode.Y)) .Subscribe(_ => Redo()); } static public void Do(Command command) { command.Do(); Instance.undoStack.Push(command); Instance.redoStack.Clear(); } void Undo() { if (Instance.undoStack.Count == 0) return; var command = undoStack.Pop(); command.Undo(); redoStack.Push(command); } void Redo() { if (Instance.redoStack.Count == 0) return; var command = redoStack.Pop(); command.Redo(); undoStack.Push(command); } } public class Command { Action doAction; Action redoAction; Action undoAction; public Command(Action doAction, Action undoAction, Action redoAction) { this.doAction = doAction; this.undoAction = undoAction; this.redoAction = redoAction; } public Command(Action doAction, Action undoAction) { this.doAction = doAction; this.undoAction = undoAction; this.redoAction = doAction; } public void Do() { doAction(); } public void Undo() { undoAction(); } public void Redo() { redoAction(); } }
using System; using System.Collections.Generic; using UniRx; using UniRx.Triggers; using UnityEngine; public class UndoRedoManager : SingletonGameObject<UndoRedoManager> { Stack<Command> undoStack = new Stack<Command>(); Stack<Command> redoStack = new Stack<Command>(); void Awake() { var model = NotesEditorModel.Instance; model.OnLoadedMusicObservable .DelayFrame(1) .Subscribe(_ => { undoStack.Clear(); redoStack.Clear(); }); this.UpdateAsObservable() .Where(_ => KeyInput.CtrlPlus(KeyCode.Z)) .Subscribe(_ => Undo()); this.UpdateAsObservable() .Where(_ => KeyInput.CtrlPlus(KeyCode.Y)) .Subscribe(_ => Redo()); } static public void Do(Command command) { command.Do(); Instance.undoStack.Push(command); Instance.redoStack.Clear(); } static public void Undo() { if (Instance.undoStack.Count == 0) return; var command = Instance.undoStack.Pop(); command.Undo(); Instance.redoStack.Push(command); } static public void Redo() { if (Instance.redoStack.Count == 0) return; var command = Instance.redoStack.Pop(); command.Redo(); Instance.undoStack.Push(command); } } public class Command { Action doAction; Action redoAction; Action undoAction; public Command(Action doAction, Action undoAction, Action redoAction) { this.doAction = doAction; this.undoAction = undoAction; this.redoAction = redoAction; } public Command(Action doAction, Action undoAction) { this.doAction = doAction; this.undoAction = undoAction; this.redoAction = doAction; } public void Do() { doAction(); } public void Undo() { undoAction(); } public void Redo() { redoAction(); } }
mit
C#
f0b5e783098cf5d98128655833004c6d9a8b7dcb
Convert NameTransformers to static methods instead of delegates
bretcope/BosunReporter.NET
BosunReporter/NameTransformers.cs
BosunReporter/NameTransformers.cs
using System; using System.Globalization; using System.Linq; namespace BosunReporter { /// <summary> /// Provides a set of commonly useful metric name and tag name/value converters. /// </summary> public static class NameTransformers { // http://stackoverflow.com/questions/18781027/regex-camel-case-to-underscore-ignore-first-occurrence /// <summary> /// Converts CamelCaseNames to Snake_Case_Names. /// </summary> public static string CamelToSnakeCase(string s) { return string.Concat(s.Select((c, i) => i > 0 && char.IsUpper(c) ? "_" + c : c.ToString(CultureInfo.InvariantCulture))); } /// <summary> /// Converts CamelCaseNames to snake_case_names with all lowercase letters. /// </summary> public static string CamelToLowerSnakeCase(string s) { return string.Concat(s.Select((c, i) => { if (char.IsUpper(c)) return i == 0 ? char.ToLowerInvariant(c).ToString(CultureInfo.InvariantCulture) : "_" + char.ToLowerInvariant(c); return c.ToString(CultureInfo.InvariantCulture); })); } /// <summary> /// Sanitizes a metric name or tag name/value by replacing illegal characters with an underscore. /// </summary> public static string Sanitize(string s) { return BosunValidation.InvalidChars.Replace(s, m => { if (m.Index == 0 || m.Index + m.Length == s.Length) // beginning and end of string return ""; return "_"; }); } } }
using System; using System.Globalization; using System.Linq; namespace BosunReporter { /// <summary> /// Provides a set of commonly useful metric name and tag name/value converters. /// </summary> public static class NameTransformers { // http://stackoverflow.com/questions/18781027/regex-camel-case-to-underscore-ignore-first-occurrence /// <summary> /// Converts CamelCaseNames to Snake_Case_Names. /// </summary> public static Func<string, string> CamelToSnakeCase = (s) => string.Concat(s.Select((c, i) => i > 0 && char.IsUpper(c) ? "_" + c : c.ToString(CultureInfo.InvariantCulture))); /// <summary> /// Converts CamelCaseNames to snake_case_names with all lowercase letters. /// </summary> public static Func<string, string> CamelToLowerSnakeCase = (s) => { return string.Concat(s.Select((c, i) => { if (char.IsUpper(c)) return i == 0 ? char.ToLowerInvariant(c).ToString(CultureInfo.InvariantCulture) : "_" + char.ToLowerInvariant(c); return c.ToString(CultureInfo.InvariantCulture); })); }; /// <summary> /// Sanitizes a metric name or tag name/value by replacing illegal characters with an underscore. /// </summary> public static Func<string, string> Sanitize = (s) => { return BosunValidation.InvalidChars.Replace(s, m => { if (m.Index == 0 || m.Index + m.Length == s.Length) // beginning and end of string return ""; return "_"; }); }; } }
mit
C#
3864da3fcbfb045b7d86f703a0d5d95f84b1db1f
Return prefix and byte length
mstrother/BmpListener
src/BmpListener/Bgp/IPAddrPrefix.cs
src/BmpListener/Bgp/IPAddrPrefix.cs
using System; using System.Linq; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { // RFC 4721 4.3 // The Type field indicates the length in bits of the IP address prefix. public int Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public static (IPAddrPrefix prefix, int byteLength) Decode(byte[] data, int offset, AddressFamily afi) { var bitLength = data[offset]; var byteLength = (bitLength + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Array.Copy(data, offset + 1, ipBytes, 0, byteLength); var prefix = new IPAddress(ipBytes); var ipAddrPrefix = new IPAddrPrefix { Length = bitLength, Prefix = prefix }; return (ipAddrPrefix, byteLength + 1); } public static (IPAddrPrefix prefix, int byteLength) Decode(ArraySegment<byte> data, int offset, AddressFamily afi) { byte bitLength = data.First(); var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; offset += data.Offset; return Decode(data.Array, data.Offset, afi); } } }
using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(byte[] data, int offset, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, offset, afi); } internal int ByteLength { get { return 1 + (Length + 7) / 8; } } public int Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public void DecodeFromBytes(byte[] data, int offset, AddressFamily afi = AddressFamily.IP) { Length = data[offset]; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Array.Copy(data, offset + 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } }
mit
C#
01db058f0de8d8c52e88081fbff55112264056fb
fix https://github.com/GregorBiswanger/Electron.NET/issues/2
ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET
ElectronNET.CLI/ProcessHelper.cs
ElectronNET.CLI/ProcessHelper.cs
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace ElectronNET.CLI { public class ProcessHelper { public static void CmdExecute(string command, string workingDirectoryPath, bool output = true, bool waitForExit = true) { using (Process cmd = new Process()) { bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isWindows) { cmd.StartInfo.FileName = "cmd.exe"; } else { // works for OSX and Linux (at least on Ubuntu) cmd.StartInfo.FileName = "bash"; } cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.RedirectStandardError = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.StartInfo.WorkingDirectory = workingDirectoryPath; if (output) { cmd.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); cmd.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data); } cmd.Start(); cmd.BeginOutputReadLine(); cmd.BeginErrorReadLine(); cmd.StandardInput.WriteLine(command); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); if (waitForExit) { cmd.WaitForExit(); } } } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace ElectronNET.CLI { public class ProcessHelper { public static void CmdExecute(string command, string workingDirectoryPath, bool output = true, bool waitForExit = true) { using (Process cmd = new Process()) { bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (isWindows) { cmd.StartInfo.FileName = "cmd.exe"; } else { // works for OSX and Linux (at least on Ubuntu) cmd.StartInfo.FileName = "bash"; } cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.StartInfo.WorkingDirectory = workingDirectoryPath; cmd.Start(); cmd.StandardInput.WriteLine(command); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); if(waitForExit) { cmd.WaitForExit(); } if (output) { Console.WriteLine(cmd.StandardOutput.ReadToEnd()); } } } } }
mit
C#
4fffb2606c9a1d100910dc321492e4d777cfd69f
Update ToolNone.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D/Editor/Tools/ToolNone.cs
src/Core2D/Editor/Tools/ToolNone.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Core2D.Editor.Input; using Core2D.Editor.Tools.Settings; namespace Core2D.Editor.Tools { /// <summary> /// None tool. /// </summary> public class ToolNone : ToolBase { private readonly IServiceProvider _serviceProvider; private ToolSettingsNone _settings; /// <inheritdoc/> public override string Name => "None"; /// <summary> /// Gets or sets the tool settings. /// </summary> public ToolSettingsNone Settings { get { return _settings; } set { Update(ref _settings, value); } } /// <summary> /// Initialize new instance of <see cref="ToolNone"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public ToolNone(IServiceProvider serviceProvider) : base() { _serviceProvider = serviceProvider; _settings = new ToolSettingsNone(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Core2D.Editor.Tools.Settings; namespace Core2D.Editor.Tools { /// <summary> /// None tool. /// </summary> public class ToolNone : ToolBase { private readonly IServiceProvider _serviceProvider; private ToolSettingsNone _settings; /// <inheritdoc/> public override string Name => "None"; /// <summary> /// Gets or sets the tool settings. /// </summary> public ToolSettingsNone Settings { get { return _settings; } set { Update(ref _settings, value); } } /// <summary> /// Initialize new instance of <see cref="ToolNone"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public ToolNone(IServiceProvider serviceProvider) : base() { _serviceProvider = serviceProvider; _settings = new ToolSettingsNone(); } } }
mit
C#
02a8f6f00d7dcce23b4b5b4fd291875389958cfd
Fix memory leak on dev server
sillsdev/LfMerge,sillsdev/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge
src/LfMerge/LanguageDepotProject.cs
src/LfMerge/LanguageDepotProject.cs
// Copyright (c) 2016 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Linq; using MongoDB.Bson; using MongoDB.Driver; using LfMerge.Settings; namespace LfMerge { public class LanguageDepotProject: ILanguageDepotProject { private LfMergeSettingsIni Settings { get; set; } // TODO: Need to grab a MongoConnection as well public LanguageDepotProject(LfMergeSettingsIni settings) { Settings = settings; } public void Initialize(string lfProjectCode) { // TODO: This should use the MongoConnection class instead MongoClient client = new MongoClient("mongodb://" + Settings.MongoDbHostNameAndPort); IMongoDatabase database = client.GetDatabase("scriptureforge"); IMongoCollection<BsonDocument> projectCollection = database.GetCollection<BsonDocument>("projects"); //var userCollection = database.GetCollection<BsonDocument>("users"); var projectFilter = new BsonDocument("projectCode", lfProjectCode); var list = projectCollection.Find(projectFilter).ToList(); var project = list.FirstOrDefault(); if (project == null) throw new ArgumentException("Can't find project code", "lfProjectCode"); BsonValue value, srProjectValue; if (project.TryGetValue("sendReceiveProjectIdentifier", out value)) Identifier = value.AsString; if (project.TryGetValue("sendReceiveProject", out srProjectValue) && (srProjectValue.AsBsonDocument.TryGetValue("repository", out value))) Repository = value.AsString; } public string Identifier { get; private set; } public string Repository { get; private set; } } }
// Copyright (c) 2016 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Linq; using MongoDB.Bson; using MongoDB.Driver; using LfMerge.Settings; namespace LfMerge { public class LanguageDepotProject: ILanguageDepotProject { private LfMergeSettingsIni Settings { get; set; } // TODO: Need to grab a MongoConnection as well public LanguageDepotProject(LfMergeSettingsIni settings) { Settings = settings; } public void Initialize(string lfProjectCode) { // TODO: This should use the MongoConnection class instead MongoClient client = new MongoClient("mongodb://" + Settings.MongoDbHostNameAndPort); IMongoDatabase database = client.GetDatabase("scriptureforge"); IMongoCollection<BsonDocument> projectCollection = database.GetCollection<BsonDocument>("projects"); //var userCollection = database.GetCollection<BsonDocument>("users"); var projectFilter = new BsonDocument("projectCode", lfProjectCode); var list = projectCollection.Find(projectFilter).ToList(); var project = list.FirstOrDefault(); if (project == null) throw new ArgumentException("Can't find project code", "lfProjectCode"); BsonValue value, srProjectValue; if (project.TryGetValue("sendReceiveProject", out srProjectValue) && (srProjectValue.AsBsonDocument.TryGetValue("identifier", out value))) Identifier = value.AsString; if (project.TryGetValue("sendReceiveProject", out srProjectValue) && (srProjectValue.AsBsonDocument.TryGetValue("repository", out value))) Repository = value.AsString; } public string Identifier { get; private set; } public string Repository { get; private set; } } }
mit
C#
ea7f46fcbdd81d287bce2d3df41bdd9b2e8b5108
Add FutureEmployment to data sources.
FrancisGrignon/StephJob,FrancisGrignon/StephJob,FrancisGrignon/StephJob,FrancisGrignon/StephJob,FrancisGrignon/StephJob
src/StephJob/Views/Home/Data.cshtml
src/StephJob/Views/Home/Data.cshtml
@{ ViewData["Title"] = "Data sources"; } <h2>@ViewData["Title"]</h2> <h3>@ViewData["Message"]</h3> http://www.oxfordmartin.ox.ac.uk/downloads/academic/The_Future_of_Employment.pdf
@{ ViewData["Title"] = "Data sources"; } <h2>@ViewData["Title"]</h2> <h3>@ViewData["Message"]</h3>
mit
C#
a4baac7fd12ccb23d08fbb68dd503ad08ad32fc2
remove ctor
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Event/EventBase.cs
src/WeihanLi.Common/Event/EventBase.cs
using Newtonsoft.Json; using System; namespace WeihanLi.Common.Event { public interface IEventBase { /// <summary> /// Event publish time /// </summary> DateTimeOffset EventAt { get; } /// <summary> /// eventId /// </summary> string EventId { get; } } public abstract class EventBase : IEventBase { [JsonProperty] public DateTimeOffset EventAt { get; private set; } [JsonProperty] public string EventId { get; private set; } protected EventBase() { EventId = GuidIdGenerator.Instance.NewId(); EventAt = DateTimeOffset.UtcNow; } protected EventBase(string eventId) { EventId = eventId; EventAt = DateTimeOffset.UtcNow; } } }
using Newtonsoft.Json; using System; namespace WeihanLi.Common.Event { public interface IEventBase { /// <summary> /// Event publish time /// </summary> DateTimeOffset EventAt { get; } /// <summary> /// eventId /// </summary> string EventId { get; } } public abstract class EventBase : IEventBase { [JsonProperty] public DateTimeOffset EventAt { get; private set; } [JsonProperty] public string EventId { get; private set; } protected EventBase() { EventId = GuidIdGenerator.Instance.NewId(); EventAt = DateTimeOffset.UtcNow; } public EventBase(string eventId) { EventId = eventId; EventAt = DateTimeOffset.UtcNow; } [JsonConstructor] public EventBase(string eventId, DateTimeOffset eventAt) { EventId = eventId; EventAt = eventAt; } } }
mit
C#
8ce5c78e9d93695ded65438fdcc224d86b9ccc3c
Fix inconsistent singular/plural naming in keyboard constants.
WolfspiritM/Colore,Sharparam/Colore,danpierce1/Colore,CoraleStudios/Colore
Colore/Razer/Keyboard/Constants.cs
Colore/Razer/Keyboard/Constants.cs
// --------------------------------------------------------------------------------------- // <copyright file="Constants.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Razer.Keyboard { /// <summary> /// The definitions of generic constant values used in the project /// </summary> public static class Constants { /// <summary> /// The maximum number of rows on the keyboard /// </summary> public static readonly Size MaxRows = 6; /// <summary> /// The maximum number of columns on the keyboard /// </summary> public static readonly Size MaxColumns = 22; /// <summary> /// The maximum number of keys on the keyboard /// </summary> public static readonly Size MaxKeys = MaxRows * MaxColumns; /// <summary> /// The maximum number of custom effects based on the maximum keys /// </summary> public static readonly Size MaxCustomEffects = MaxKeys; // <summary> // A grid representation of the keyboard // </summary> //Todo: Speak with Razer to implement //public static readonly Int32 RZKEY_GRID_LAYOUT[MAX_ROW][MAX_COLUMN] = {}; } }
// --------------------------------------------------------------------------------------- // <copyright file="Constants.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Razer.Keyboard { /// <summary> /// The definitions of generic constant values used in the project /// </summary> public static class Constants { /// <summary> /// The maximum number of rows on the keyboard /// </summary> public static readonly Size MaxRow = 6; /// <summary> /// The maximum number of columns on the keyboard /// </summary> public static readonly Size MaxColumn = 22; /// <summary> /// The maximum number of keys on the keyboard /// </summary> public static readonly Size MaxKeys = MaxRow * MaxColumn; /// <summary> /// The maximum number of custom effects based on the maximum keys /// </summary> public static readonly Size MaxCustomEffects = MaxKeys; // <summary> // A grid representation of the keyboard // </summary> //Todo: Speak with Razer to implement //public static readonly Int32 RZKEY_GRID_LAYOUT[MAX_ROW][MAX_COLUMN] = {}; } }
mit
C#
d41952471670f8482f91dc6f09d82f825b4c4a18
Clean up syntax of index page
MrDoomBringer/ISWebTest
ISWebTest/Views/Home/Index.cshtml
ISWebTest/Views/Home/Index.cshtml
 @using ISWebTest.ExtensionMethods; @using ISWebTest.Controllers; <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <div> <a href="@(Url.Action<HomeController>(nameof(HomeController.Analyze)))">TEST</a> </div> </body> </html>
@{ Layout = null; @using ISWebTest.ExtensionMethods; @using ISWebTest.Controllers; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <div> <a href="@{Url.Action<HomeController>(nameof(HomeController.Analyze))}">TEST</a> </div> </body> </html>
mit
C#
f25b48aa887c7d3a6bf3e32d4dad36254cc9a11f
Remove unneeded white space
Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype
src/Glimpse.Web.Common/Framework/MasterRequestRuntime.cs
src/Glimpse.Web.Common/Framework/MasterRequestRuntime.cs
using System; using System.Collections.Generic; using Microsoft.Framework.DependencyInjection; using System.Threading.Tasks; namespace Glimpse.Web { public class MasterRequestRuntime { private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes; private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers; public MasterRequestRuntime(IServiceProvider serviceProvider) { _requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>(); _requestRuntimes.Discover(); _requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>(); _requestHandlers.Discover(); } public async Task Begin(IContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.Begin(context); } } public bool TryGetHandle(IContext context, out IRequestHandler handeler) { foreach (var requestHandler in _requestHandlers) { if (requestHandler.WillHandle(context)) { handeler = requestHandler; return true; } } handeler = null; return false; } public async Task End(IContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.End(context); } } } }
using System; using System.Collections.Generic; using Microsoft.Framework.DependencyInjection; using System.Threading.Tasks; namespace Glimpse.Web { public class MasterRequestRuntime { private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes; private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers; public MasterRequestRuntime(IServiceProvider serviceProvider) { _requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>(); _requestRuntimes.Discover(); _requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>(); _requestHandlers.Discover(); } public async Task Begin(IContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.Begin(context); } } public bool TryGetHandle(IContext context, out IRequestHandler handeler) { foreach (var requestHandler in _requestHandlers) { if (requestHandler.WillHandle(context)) { handeler = requestHandler; return true; } } handeler = null; return false; } public async Task End(IContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.End(context); } } } }
mit
C#
c496146634a76e1001238d7e1ff34eb84ccef8c8
update viewport setting
jcoleson/jcoleson.github.io,jcoleson/jcoleson.github.io,jcoleson/jcoleson.github.io
colesonstatiq/theme/input/_partials/_head.cshtml
colesonstatiq/theme/input/_partials/_head.cshtml
<!--start head--> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" /> <title>@Model.GetString("Title")</title> @Html.Partial("_partials/_favicons") <!--stylesheets <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.2/styles/vs2015.min.css"> --> <link rel="stylesheet" href="assets/css/styles.css"> <link rel="stylesheet" href="assets/css/customstyles.css"> <!--head scripts --> <script src="https://kit.fontawesome.com/96d16fe260.js" crossorigin="anonymous"></script> <!--end head-->
<!--start head--> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@Model.GetString("Title")</title> @Html.Partial("_partials/_favicons") <!--stylesheets <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.2/styles/vs2015.min.css"> --> <link rel="stylesheet" href="assets/css/styles.css"> <link rel="stylesheet" href="assets/css/customstyles.css"> <!--head scripts --> <script src="https://kit.fontawesome.com/96d16fe260.js" crossorigin="anonymous"></script> <!--end head-->
mit
C#
d9397f06cf4f03599a4cd53cb53befed8446088f
Update IsNullConverter.cs
Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/UI/Avalonia/Converters/IsNullConverter.cs
src/Core2D/UI/Avalonia/Converters/IsNullConverter.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Avalonia; using Avalonia.Data.Converters; namespace Core2D.UI.Avalonia.Converters { /// <summary> /// Converts a binding value object from <see cref="object"/> to <see cref="bool"/> True if value is equal to null or <see cref="AvaloniaProperty.UnsetValue"/> otherwise return False. /// </summary> public class IsNullConverter : IValueConverter { /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The type of the target.</param> /// <param name="parameter">A user-defined parameter.</param> /// <param name="culture">The culture to use.</param> /// <returns>The converted value.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value == AvaloniaProperty.UnsetValue || value == null; } /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The type of the target.</param> /// <param name="parameter">A user-defined parameter.</param> /// <param name="culture">The culture to use.</param> /// <returns>The converted value.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia; using Avalonia.Data.Converters; using System; using System.Globalization; namespace Core2D.UI.Avalonia.Converters { /// <summary> /// Converts a binding value object from <see cref="object"/> to <see cref="bool"/> True if value is equal to null or <see cref="AvaloniaProperty.UnsetValue"/> otherwise return False. /// </summary> public class IsNullConverter : IValueConverter { /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The type of the target.</param> /// <param name="parameter">A user-defined parameter.</param> /// <param name="culture">The culture to use.</param> /// <returns>The converted value.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value == AvaloniaProperty.UnsetValue || value == null; } /// <summary> /// Converts a value. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The type of the target.</param> /// <param name="parameter">A user-defined parameter.</param> /// <param name="culture">The culture to use.</param> /// <returns>The converted value.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
mit
C#
aa5cd7b202d2a2c2b7e995eb4a23a6c70011ff63
Make constructor public on DataPortalResult.
MarimerLLC/csla,rockfordlhotka/csla,ronnymgm/csla-light,jonnybee/csla,rockfordlhotka/csla,MarimerLLC/csla,JasonBock/csla,BrettJaner/csla,BrettJaner/csla,jonnybee/csla,ronnymgm/csla-light,JasonBock/csla,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light,MarimerLLC/csla,BrettJaner/csla
cslalightcs/Csla/DataPortalResult.cs
cslalightcs/Csla/DataPortalResult.cs
using System; namespace Csla { /// <summary> /// IDataPortalResult defines the results of DataPortal operation /// </summary> public interface IDataPortalResult { object Object { get; } Exception Error { get; } } /// <summary> /// DataPortalResult defines the results of DataPortal operation. /// It contains object that was received from the server, /// an error (if occurred) and userState - user defined information /// that was passed into data portal on initial request /// </summary> /// <typeparam name="T">Type of object that DataPortal received</typeparam> public class DataPortalResult<T> : EventArgs, IDataPortalResult { /// <summary> /// Object that DataPortal received as a result of current operation /// </summary> public T Object { get; private set; } /// <summary> /// Error that occurred during the DataPotal call. /// This will be null if no errors occurred. /// </summary> public Exception Error { get; private set; } /// <summary> /// User defined information /// that was passed into data portal on initial request /// </summary> public object UserState { get; private set; } /// <summary> /// Create new instance of data portal result /// </summary> /// <param name="obj"> /// Object that DataPortal received as a result of current operation /// </param> /// <param name="ex"> /// Error that occurred during the DataPotal call. /// This will be null if no errors occurred. /// </param> /// <param name="userState"> /// User defined information /// that was passed into data portal on initial request /// </param> public DataPortalResult(T obj, Exception ex, object userState) { this.Object = obj; this.Error = ex; this.UserState = userState; } #region IDataPortalResult Members object IDataPortalResult.Object { get { return this.Object; } } Exception IDataPortalResult.Error { get { return this.Error; } } #endregion } }
using System; namespace Csla { public interface IDataPortalResult { object Object { get; } Exception Error { get; } } public class DataPortalResult<T> : EventArgs, IDataPortalResult { public T Object { get; private set; } public Exception Error { get; private set; } public object UserState { get; private set; } internal DataPortalResult(T obj, Exception ex, object userState) { this.Object = obj; this.Error = ex; this.UserState = userState; } #region IDataPortalResult Members object IDataPortalResult.Object { get { return this.Object; } } Exception IDataPortalResult.Error { get { return this.Error; } } #endregion } }
mit
C#
e8918f2fda760f4354bb4260ebe7bf6f6a76436e
hide locked level buttons
lukaselmer/ethz-game-lab,lukaselmer/ethz-game-lab,lukaselmer/ethz-game-lab
Assets/LevelClickable.cs
Assets/LevelClickable.cs
using UnityEngine; using System.Collections; public class LevelClickable : MonoBehaviour { void Start () { this.renderer.enabled = LevelSelection.CanPlay (name); } }
using UnityEngine; using System.Collections; public class LevelClickable : MonoBehaviour { void Start () { if (!LevelSelection.CanPlay(name)){ this.renderer.enabled = false; } } void AfterUpdate () { } }
mit
C#
6c4b60fc262238df94addfe87accfc8557f25fd8
add max width of y position, player will day when out of screen
endlessz/Flappy-Cube
Assets/Scripts/Player.cs
Assets/Scripts/Player.cs
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class Player : MonoBehaviour { [Header("Movement of the player")] public float jumpHeight; public float forwardSpeed; private Rigidbody2D mainRigidbody2D; void Start() { mainRigidbody2D = GetComponent<Rigidbody2D> (); mainRigidbody2D.isKinematic = true; //Player not fall when in PREGAME states } // Update is called once per frame void Update () { //If Player go out off screen if ((transform.position.y > getMaxWidth() || transform.position.y < -getMaxWidth() ) && GameManager.instance.currentState == GameStates.INGAME) { Dead(); } //When click or touch and in INGAME states if ((Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) && GameManager.instance.currentState == GameStates.INGAME){ Jump(); } //When click or touch and in PREGAME states if ((Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) && GameManager.instance.currentState == GameStates.PREGAME){ mainRigidbody2D.isKinematic = false; GameManager.instance.startGame(); } } private void Jump(){ mainRigidbody2D.velocity = new Vector2(forwardSpeed,jumpHeight); } private void Dead(){ mainRigidbody2D.freezeRotation = false; Debug.Log("Game Over"); } void OnCollisionEnter2D(Collision2D other) { if (other.transform.tag == "Obstacle") { Dead (); } } void OnTriggerEnter2D(Collider2D other){ if (other.tag == "Score") { ObstacleSpawner.instance.spawnObstacle(); Destroy(other.gameObject); } } private float getMaxWidth(){ Vector2 cameraWidth = Camera.main.ScreenToWorldPoint (new Vector2 (Screen.width, Screen.height)); float playerWidth = GetComponent<Renderer>().bounds.extents.y; return cameraWidth.y + playerWidth; } }
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class Player : MonoBehaviour { [Header("Movement of the player")] public float jumpHeight; public float forwardSpeed; private Rigidbody2D mainRigidbody2D; void Start() { mainRigidbody2D = GetComponent<Rigidbody2D> (); } // Update is called once per frame void Update () { if ((Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))){ Jump(); } } void Jump(){ mainRigidbody2D.velocity = new Vector2(forwardSpeed,jumpHeight); } void Dead(){ mainRigidbody2D.freezeRotation = false; Debug.Log("Game Over"); } void OnCollisionEnter2D(Collision2D other) { if (other.transform.tag == "Obstacle") { Dead (); } } void OnTriggerEnter2D(Collider2D other){ if (other.tag == "Score") { ObstacleSpawner.instance.spawnObstacle(); Destroy(other.gameObject); } } }
mit
C#
8e9a906f4831153dd1f1cd39c3f2495fe91322a1
Remove dead code from IResponse
shiftkey/SignalR,shiftkey/SignalR
SignalR/Abstractions/IResponse.cs
SignalR/Abstractions/IResponse.cs
using System.Threading.Tasks; namespace SignalR.Abstractions { public interface IResponse { bool IsClientConnected { get; } string ContentType { get; set; } Task WriteAsync(string data); Task EndAsync(string data); } }
using System.Threading.Tasks; namespace SignalR.Abstractions { public interface IResponse { bool IsClientConnected { get; } string ContentType { get; set; } Task WriteAsync(string data); Task EndAsync(string data); // Task End(); } }
mit
C#
8896392c0339d0c12996d98cd2ee6e9541beb658
fix bockover's buggy code
mono/Mono.Zeroconf,mono/Mono.Zeroconf
src/Mono.Zeroconf.Providers.Avahi/Mono.Zeroconf.Providers.Avahi/ZeroconfProvider.cs
src/Mono.Zeroconf.Providers.Avahi/Mono.Zeroconf.Providers.Avahi/ZeroconfProvider.cs
// // ZeroconfProvider.cs // // Authors: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com) // // 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.Collections; [assembly:Mono.Zeroconf.Providers.ZeroconfProvider(typeof(Mono.Zeroconf.Providers.Avahi.ZeroconfProvider))] namespace Mono.Zeroconf.Providers.Avahi { public class ZeroconfProvider : IZeroconfProvider { public void Initialize() { } public Type ServiceBrowser { get { return typeof(Mono.Zeroconf.Providers.Avahi.ServiceBrowser); } } public Type RegisterService { get { return typeof(Mono.Zeroconf.Providers.Avahi.TxtRecord); } } public Type TxtRecord { get { return null; } } } }
// // ZeroconfProvider.cs // // Authors: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com) // // 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.Collections; [assembly:Mono.Zeroconf.Providers.ZeroconfProvider(typeof(Mono.Zeroconf.Providers.Avahi.ZeroconfProvider))] namespace Mono.Zeroconf.Providers.Avahi { public class ZeroconfProvider : IZeroconfProvider { public void Initialize() { } public Type ServiceBrowser { get { return typeof(Mono.Zeroconf.Avahi.ServiceBrowser); } } public Type RegisterService { get { return typeof(Mono.Zeroconf.Avahi.TxtRecord); } } public Type TxtRecord { get { return null; } } } }
mit
C#
ac18536692c4231160ef2021a73673a5d22d42c5
fix test for new lnk program
qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox
Wox.Test/PluginProgramTest.cs
Wox.Test/PluginProgramTest.cs
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Wox.Core.Plugin; using Wox.Plugin; namespace Wox.Test { [TestFixture] class PluginProgramTest { private Plugin.Program.Main plugin; [OneTimeSetUp] public void Setup() { plugin = new Plugin.Program.Main(); plugin.loadSettings(); Plugin.Program.Main.IndexPrograms(); } [TestCase("powershell", "PowerShell")] [TestCase("note", "Notepad")] [TestCase("this pc", "This PC")] public void Win32Test(string QueryText, string ResultTitle) { Query query = QueryBuilder.Build(QueryText.Trim(), new Dictionary<string, PluginPair>()); Result result = plugin.Query(query).OrderByDescending(r => r.Score).First(); Assert.IsTrue(result.Title.StartsWith(ResultTitle)); } } }
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Wox.Core.Plugin; using Wox.Plugin; namespace Wox.Test { [TestFixture] class PluginProgramTest { private Plugin.Program.Main plugin; [OneTimeSetUp] public void Setup() { plugin = new Plugin.Program.Main(); plugin.loadSettings(); Plugin.Program.Main.IndexPrograms(); } [TestCase("powershell", "PowerShell")] [TestCase("note", "Notepad")] [TestCase("compu", "computer")] public void Win32Test(string QueryText, string ResultTitle) { Query query = QueryBuilder.Build(QueryText.Trim(), new Dictionary<string, PluginPair>()); Result result = plugin.Query(query).OrderByDescending(r => r.Score).First(); Assert.IsTrue(result.Title.StartsWith(ResultTitle)); } } }
mit
C#
34f1f92876f68fa5d82665d6e8bc42d78b38997d
Update ExcelColors.cs
stephanstapel/ZUGFeRD-csharp,stephanstapel/ZUGFeRD-csharp
ZUGFeRDToExcel/ExcelColors.cs
ZUGFeRDToExcel/ExcelColors.cs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZUGFeRDToExcel { public enum ExcelColors { Yellow, Green } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZUGFeRDToExcel { public enum ExcelColors { Yellow, Green } }
apache-2.0
C#
671a24bbf206091ec7abce686e06db132142732c
Print exceptions when selecting invalid interaction
Drenn1/LynnaLab,Drenn1/LynnaLab
LynnaLab/Core/InteractionObject.cs
LynnaLab/Core/InteractionObject.cs
using System; namespace LynnaLab { /// <summary> /// An interaction object. The "index" is the full ID (2 bytes, including subid). /// </summary> public class InteractionObject : GameObject { Data objectData; byte b0,b1,b2; internal InteractionObject(Project p, int i) : base(p, i) { try { objectData = p.GetData("interactionData", ID*3); // If this points to more data, follow the pointer if (objectData.GetNumValues() == 1) { string label = objectData.GetValue(0); objectData = p.GetData(label); int count = SubID; while (count>0 && (objectData.GetIntValue(1)&0x80) == 0) { count--; objectData = objectData.NextData; } } b0 = (byte)objectData.GetIntValue(0); b1 = (byte)objectData.GetIntValue(1); b2 = (byte)objectData.GetIntValue(2); } catch(InvalidLookupException e) { Console.WriteLine(e.ToString()); objectData = null; } catch(FormatException e) { Console.WriteLine(e.ToString()); objectData = null; } } // GameObject properties public override string TypeName { get { return "Interaction"; } } public override ConstantsMapping IDConstantsMapping { get { return Project.InteractionMapping; } } public override bool DataValid { get { return objectData != null; } } public override byte ObjectGfxHeaderIndex { get { return b0; } } public override byte TileIndexBase { get { return (byte)(b1&0x7f); } } public override byte OamFlagsBase { get { return (byte)((b2>>4)&0xf); } } public override byte DefaultAnimationIndex { get { return (byte)(b2&0xf); } } } }
using System; namespace LynnaLab { /// <summary> /// An interaction object. The "index" is the full ID (2 bytes, including subid). /// </summary> public class InteractionObject : GameObject { Data objectData; byte b0,b1,b2; internal InteractionObject(Project p, int i) : base(p, i) { try { objectData = p.GetData("interactionData", ID*3); // If this points to more data, follow the pointer if (objectData.GetNumValues() == 1) { string label = objectData.GetValue(0); objectData = p.GetData(label); int count = SubID; while (count>0 && (objectData.GetIntValue(1)&0x80) == 0) { count--; objectData = objectData.NextData; } } b0 = (byte)objectData.GetIntValue(0); b1 = (byte)objectData.GetIntValue(1); b2 = (byte)objectData.GetIntValue(2); } catch(InvalidLookupException) { objectData = null; } catch(FormatException) { objectData = null; } } // GameObject properties public override string TypeName { get { return "Interaction"; } } public override ConstantsMapping IDConstantsMapping { get { return Project.InteractionMapping; } } public override bool DataValid { get { return objectData != null; } } public override byte ObjectGfxHeaderIndex { get { return b0; } } public override byte TileIndexBase { get { return (byte)(b1&0x7f); } } public override byte OamFlagsBase { get { return (byte)((b2>>4)&0xf); } } public override byte DefaultAnimationIndex { get { return (byte)(b2&0xf); } } } }
mit
C#
8e70d89b2eb8650ad809da87366404aa4aaba33a
Allow to pass JsonSerializerSettings to JsonSerializer (#791)
ar7z1/EasyNetQ,ar7z1/EasyNetQ,zidad/EasyNetQ,micdenny/EasyNetQ,Pliner/EasyNetQ,Pliner/EasyNetQ,zidad/EasyNetQ,EasyNetQ/EasyNetQ
Source/EasyNetQ/JsonSerializer.cs
Source/EasyNetQ/JsonSerializer.cs
using System; using System.Text; using Newtonsoft.Json; namespace EasyNetQ { public class JsonSerializer : ISerializer { private readonly JsonSerializerSettings serializerSettings; public JsonSerializer() { serializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; } public JsonSerializer(JsonSerializerSettings serializerSettings) { this.serializerSettings = serializerSettings; } public byte[] MessageToBytes<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message, serializerSettings)); } public T BytesToMessage<T>(byte[] bytes) { Preconditions.CheckNotNull(bytes, "bytes"); return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes), serializerSettings); } public object BytesToMessage(Type type, byte[] bytes) { Preconditions.CheckNotNull(type, "type"); Preconditions.CheckNotNull(bytes, "bytes"); return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bytes), type, serializerSettings); } } }
using System; using System.Text; using Newtonsoft.Json; namespace EasyNetQ { public class JsonSerializer : ISerializer { private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; public byte[] MessageToBytes<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message, serializerSettings)); } public T BytesToMessage<T>(byte[] bytes) { Preconditions.CheckNotNull(bytes, "bytes"); return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes), serializerSettings); } public object BytesToMessage(Type type, byte[] bytes) { Preconditions.CheckNotNull(bytes, "bytes"); return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bytes), type, serializerSettings); } } }
mit
C#
6bb6915464a65c645bf8e37ed4c960accd669e44
change host
whir1/serilog-sinks-graylog
src/Serilog.Sinks.Graylog.Tests/LoggerConfigurationGrayLogExtensionsFixture.cs
src/Serilog.Sinks.Graylog.Tests/LoggerConfigurationGrayLogExtensionsFixture.cs
using FluentAssertions; using Serilog.Events; using Xunit; namespace Serilog.Sinks.Graylog.Tests { public class LoggerConfigurationGrayLogExtensionsFixture { [Fact] public void CanApplyExtension() { var loggerConfig = new LoggerConfiguration(); loggerConfig.WriteTo.Graylog(new GraylogSinkOptions { MinimumLogEventLevel = LogEventLevel.Information, Facility = "VolkovTestFacility", HostnameOrAdress = "localhost", Port = 12201 }); var logger = loggerConfig.CreateLogger(); logger.Should().NotBeNull(); } } }
using FluentAssertions; using Serilog.Events; using Xunit; namespace Serilog.Sinks.Graylog.Tests { public class LoggerConfigurationGrayLogExtensionsFixture { [Fact] public void CanApplyExtension() { var loggerConfig = new LoggerConfiguration(); loggerConfig.WriteTo.Graylog(new GraylogSinkOptions { MinimumLogEventLevel = LogEventLevel.Information, Facility = "VolkovTestFacility", HostnameOrAdress = "logs.aeroclub.int", Port = 12201 }); var logger = loggerConfig.CreateLogger(); logger.Should().NotBeNull(); } } }
mit
C#
e00364fbed698f8d325a579e69425868206adf12
Fix the ReadOnlyTargetRules warning in Build.cs.
unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv
Source/UnrealCV/UnrealCV.Build.cs
Source/UnrealCV/UnrealCV.Build.cs
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class UnrealCV: ModuleRules { #if WITH_FORWARDED_MODULE_RULES_CTOR public UnrealCV(ReadOnlyTargetRules Target) : base(Target) // 4.16 or better { bEnforceIWYU = false; #else public UnrealCV(TargetInfo Target) //4.15 or lower { #endif // This trick is from https://answers.unrealengine.com/questions/258689/how-to-include-private-header-files-of-other-modul.html string EnginePath = Path.GetFullPath(BuildConfiguration.RelativeEnginePath); PublicIncludePaths.AddRange( new string[] { EnginePath + "Source/Runtime/Launch/Resources", // To get Unreal Engine minor version } ); PrivateIncludePaths.AddRange( new string[] { "UnrealCV/Private/Commands", "UnrealCV/Private/libs", // For 3rd-party libs } ); PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "RenderCore", "Networking", "Sockets", "Slate", "ImageWrapper", "CinematicCamera", "Projects", // Support IPluginManager }); // PrivateDependency only available in Private folder // Reference: https://answers.unrealengine.com/questions/23384/what-is-the-difference-between-publicdependencymod.html if (UEBuildConfiguration.bBuildEditor == true) { PrivateDependencyModuleNames.AddRange( new string[] { "UnrealEd", // To support GetGameWorld } ); } DynamicallyLoadedModuleNames.AddRange( new string[] { "Renderer" } ); } } }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class UnrealCV: ModuleRules { public UnrealCV(TargetInfo Target) { bEnforceIWYU = false; // This trick is from https://answers.unrealengine.com/questions/258689/how-to-include-private-header-files-of-other-modul.html string EnginePath = Path.GetFullPath(BuildConfiguration.RelativeEnginePath); PublicIncludePaths.AddRange( new string[] { EnginePath + "Source/Runtime/Launch/Resources", // To get Unreal Engine minor version } ); PrivateIncludePaths.AddRange( new string[] { "UnrealCV/Private/Commands", "UnrealCV/Private/libs", // For 3rd-party libs } ); PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "RenderCore", "Networking", "Sockets", "Slate", "ImageWrapper", "CinematicCamera", "Projects", // Support IPluginManager }); // PrivateDependency only available in Private folder // Reference: https://answers.unrealengine.com/questions/23384/what-is-the-difference-between-publicdependencymod.html if (UEBuildConfiguration.bBuildEditor == true) { PrivateDependencyModuleNames.AddRange( new string[] { "UnrealEd", // To support GetGameWorld } ); } DynamicallyLoadedModuleNames.AddRange( new string[] { "Renderer" } ); } } }
mit
C#
efe39e43f5338b0cf5d1a1b9deeaa22a788e6267
Remove test the `[NotNull]` move makes irrelevant
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNet.Routing.Tests/RouteOptionsTests.cs
test/Microsoft.AspNet.Routing.Tests/RouteOptionsTests.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; using Xunit; namespace Microsoft.AspNet.Routing.Tests { public class RouteOptionsTests { [Fact] public void ConfigureRouting_ConfiguresOptionsProperly() { // Arrange var services = new ServiceCollection().AddOptions(); // Act services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint))); var serviceProvider = services.BuildServiceProvider(); // Assert var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>(); Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name); } private class TestRouteConstraint : IRouteConstraint { public TestRouteConstraint(string pattern) { Pattern = pattern; } public string Pattern { get; private set; } public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection) { throw new NotImplementedException(); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; using Xunit; namespace Microsoft.AspNet.Routing.Tests { public class RouteOptionsTests { [Fact] public void ConstraintMap_SettingNullValue_Throws() { // Arrange var options = new RouteOptions(); // Act & Assert var ex = Assert.Throws<ArgumentNullException>(() => options.ConstraintMap = null); Assert.Equal("The 'ConstraintMap' property of 'Microsoft.AspNet.Routing.RouteOptions' must not be null." + Environment.NewLine + "Parameter name: value", ex.Message); } [Fact] public void ConfigureRouting_ConfiguresOptionsProperly() { // Arrange var services = new ServiceCollection().AddOptions(); // Act services.ConfigureRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint))); var serviceProvider = services.BuildServiceProvider(); // Assert var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>(); Assert.Equal("TestRouteConstraint", accessor.Options.ConstraintMap["foo"].Name); } private class TestRouteConstraint : IRouteConstraint { public TestRouteConstraint(string pattern) { Pattern = pattern; } public string Pattern { get; private set; } public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection) { throw new NotImplementedException(); } } } }
apache-2.0
C#
d324a2fda62f0b6b0d6ea2498b5443b96cfe39f4
Set NukeLoopWait and AegisLoopWait to 0 as per sztanpet.
destinygg/bot
Dbot.Utility/Settings.cs
Dbot.Utility/Settings.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dbot.Utility { public static class Settings { public const int MessageLogSize = 200; // aka context size public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10); public const int SelfSpamSimilarity = 75; public const int LongSpamSimilarity = 75; public const int SelfSpamContextLength = 15; public const int LongSpamContextLength = 26; public const int LongSpamMinimumLength = 40; public const int LongSpamLongerBanMultiplier = 3; public const double NukeStringDelta = 0.7; public const int NukeLoopWait = 0; public const int AegisLoopWait = 0; public const int NukeDefaultDuration = 30; public static bool IsMono; public static string Timezone; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dbot.Utility { public static class Settings { public const int MessageLogSize = 200; // aka context size public static readonly TimeSpan UserCommandInterval = TimeSpan.FromSeconds(10); public const int SelfSpamSimilarity = 75; public const int LongSpamSimilarity = 75; public const int SelfSpamContextLength = 15; public const int LongSpamContextLength = 26; public const int LongSpamMinimumLength = 40; public const int LongSpamLongerBanMultiplier = 3; public const double NukeStringDelta = 0.7; public const int NukeLoopWait = 2000; public const int AegisLoopWait = 250; public const int NukeDefaultDuration = 30; public static bool IsMono; public static string Timezone; } }
mit
C#
df83ee7a585ec02ce3fdff3aa1ab6f89f6377348
Insert guid functionality
kbilsted/NppPluginGuidHelper
GuidHelper/InsertGuid.cs
GuidHelper/InsertGuid.cs
using System; using System.Collections.Generic; using System.Linq; namespace Kbg.NppPluginNET.GuidHelper { class InsertGuid { private readonly IScintillaGateway scintilla; public InsertGuid(IScintillaGateway scintilla) { this.scintilla = scintilla; } public void Execute() { scintilla.BeginUndoAction(); var selections = GetSelections(); var sumChanges = InsertGuids(selections); scintilla.EndUndoAction(); var first = selections.First(); var totalDelta = new Position(sumChanges + first.Item2); scintilla.GotoPos(first.Item1 + totalDelta); } private int InsertGuids(Tuple<Position, int>[] selections) { var sumChanges = selections.Sum(x => { scintilla.DeleteRange(x.Item1, x.Item2); scintilla.InsertText(x.Item1, Guid.NewGuid().ToString()); return GuidHelperConstants.Regexlength - x.Item2; }); return sumChanges; } private Tuple<Position, int>[] GetSelections() { var selectionsCount = scintilla.GetSelections(); var selections = new List<Tuple<Position, int>>(selectionsCount); for (int i = 0; i < selectionsCount; i++) { var selectionStart = scintilla.GetSelectionNStart(i); var delta = (scintilla.GetSelectionNEnd(i) - selectionStart).Value; selections.Add(Tuple.Create(selectionStart, delta)); } return selections.OrderByDescending(x => x.Item1.Value).ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kbg.NppPluginNET; namespace GuidHelper { class InsertGuid { private readonly ScintillaGateway scintilla; public InsertGuid(ScintillaGateway scintilla) { this.scintilla = scintilla; } public void Execute() { scintilla.BeginUndoAction(); var selections = GetSelections(); var sumChanges = InsertGuids(selections); scintilla.EndUndoAction(); var first = selections.First(); var totalDelta = new Position(sumChanges + first.Item2); scintilla.GotoPos(first.Item1 + totalDelta); } private int InsertGuids(Tuple<Position, int>[] selections) { var sumChanges = selections.Sum(x => { scintilla.DeleteRange(x.Item1, x.Item2); scintilla.InsertText(x.Item1, Guid.NewGuid().ToString()); return GuidHelperConstants.Regexlength - x.Item2; }); return sumChanges; } private Tuple<Position, int>[] GetSelections() { var selectionsCount = scintilla.GetSelections(); var selections = new List<Tuple<Position, int>>(selectionsCount); for (int i = 0; i < selectionsCount; i++) { var selectionStart = scintilla.GetSelectionNStart(i); var delta = (scintilla.GetSelectionNEnd(i) - selectionStart).Value; selections.Add(Tuple.Create(selectionStart, delta)); } return selections.OrderByDescending(x => x.Item1.Value).ToArray(); } } }
apache-2.0
C#
76e332325c0fd715f39378ead7011d20544fe321
Update InsertingOLEObjects.cs
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/DrawingObjects/OLE/InsertingOLEObjects.cs
Examples/CSharp/DrawingObjects/OLE/InsertingOLEObjects.cs
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.DrawingObjects.OLE { public class InsertingOLEObjects { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiate a new Workbook. Workbook workbook = new Workbook(); //Get the first worksheet. Worksheet sheet = workbook.Worksheets[0]; //Define a string variable to store the image path. string ImageUrl = dataDir + "logo.jpg"; //Get the picture into the streams. FileStream fs = File.OpenRead(ImageUrl); //Define a byte array. byte[] imageData = new Byte[fs.Length]; //Obtain the picture into the array of bytes from streams. fs.Read(imageData, 0, imageData.Length); //Close the stream. fs.Close(); //Get an excel file path in a variable. string path = dataDir + "book1.xls"; //Get the file into the streams. fs = File.OpenRead(path); //Define an array of bytes. byte[] objectData = new Byte[fs.Length]; //Store the file from streams. fs.Read(objectData, 0, objectData.Length); //Close the stream. fs.Close(); //Add an Ole object into the worksheet with the image //shown in MS Excel. sheet.OleObjects.Add(14, 3, 200, 220, imageData); //Set embedded ole object data. sheet.OleObjects[0].ObjectData = objectData; //Save the excel file workbook.Save(dataDir + "output.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.DrawingObjects.OLE { public class InsertingOLEObjects { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); //Instantiate a new Workbook. Workbook workbook = new Workbook(); //Get the first worksheet. Worksheet sheet = workbook.Worksheets[0]; //Define a string variable to store the image path. string ImageUrl = dataDir + "logo.jpg"; //Get the picture into the streams. FileStream fs = File.OpenRead(ImageUrl); //Define a byte array. byte[] imageData = new Byte[fs.Length]; //Obtain the picture into the array of bytes from streams. fs.Read(imageData, 0, imageData.Length); //Close the stream. fs.Close(); //Get an excel file path in a variable. string path = dataDir + "book1.xls"; //Get the file into the streams. fs = File.OpenRead(path); //Define an array of bytes. byte[] objectData = new Byte[fs.Length]; //Store the file from streams. fs.Read(objectData, 0, objectData.Length); //Close the stream. fs.Close(); //Add an Ole object into the worksheet with the image //shown in MS Excel. sheet.OleObjects.Add(14, 3, 200, 220, imageData); //Set embedded ole object data. sheet.OleObjects[0].ObjectData = objectData; //Save the excel file workbook.Save(dataDir + "output.out.xls"); } } }
mit
C#
5f312326a072e15e58296c77dcfae9f827cb182a
update to 2.2.0
unvell/ReoGrid,unvell/ReoGrid
ReoGrid/Properties/AssemblyInfo.cs
ReoGrid/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("ReoGrid")] [assembly: AssemblyDescription(".NET Spreadsheet Control")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("unvell.com")] [assembly: AssemblyProduct("ReoGrid")] [assembly: AssemblyCopyright("Copyright © 2012-2020 unvell.com, All Rights Seserved.")] [assembly: AssemblyTrademark("ReoGrid.NET")] [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("a9997b8f-e41f-4358-98a9-876e2354c0b9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.0.0")] [assembly: AssemblyFileVersion("2.2.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("ReoGrid")] [assembly: AssemblyDescription(".NET Spreadsheet Control")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("unvell.com")] [assembly: AssemblyProduct("ReoGrid")] [assembly: AssemblyCopyright("Copyright © 2012-2016 unvell.com, All Rights Seserved.")] [assembly: AssemblyTrademark("ReoGrid.NET")] [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("a9997b8f-e41f-4358-98a9-876e2354c0b9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
mit
C#
664ccc329bf961ae54104574bfd24ce26ba4b97c
Update CreateImages.cs
sts-CAD-Software/PCB-Investigator-Scripts
Editing/CreateImages.cs
Editing/CreateImages.cs
// Autor support@easylogix.de // www.pcb-investigator.com // SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html // SDK http://www.pcb-investigator.com/en/sdk-participate // Create images of layers. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { string FileLocation = @"C:\Temp\"; public PScript() { } public void Execute(IPCBIWindow mainWindowPCBI) { IStep step = mainWindowPCBI.GetCurrentStep(); if (step == null) return; ICMPLayer layerCMPsTop = step.GetCMPLayer(true); //exisits the compnenent layer? if (layerCMPsTop == null) return; foreach (string layername in step.GetAllLayerNames()) { List<ILayer> layers = new List<ILayer>(); layers.Add(step.GetLayer(layername)); SaveImageFromComponent(step, layers, FileLocation); } //something went wrong? string errorLog = IAutomation.GetErrorLog(); if (errorLog.Length > 0) System.Diagnostics.Debug.WriteLine(errorLog); } public void SaveImageFromComponent( IStep step, List<ILayer> layers, string FileLocation) { if (layers.Count == 0) return; RectangleF boundsRelevantCMP = layers[0].GetBounds(); boundsRelevantCMP.Inflate(100, 100); //show a little bit of the area around the component //create the image and save it as png PCBI.Automation.IStep.BitmapResultClass imageClass = step.GetBitmap(layers, boundsRelevantCMP, 500, 500); if (imageClass != null) imageClass.Image.Save(FileLocation + layers[0].GetLayerName() + ".png", System.Drawing.Imaging.ImageFormat.Png); } } }
// Autor support@easylogix.de // www.pcb-investigator.com // SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html // SDK http://www.pcb-investigator.com/en/sdk-participate // Create images of layers. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow mainWindowPCBI) { IStep step = mainWindowPCBI.GetCurrentStep(); if (step == null) return; ICMPLayer layerCMPsTop = step.GetCMPLayer(true); //exisits the compnenent layer? if (layerCMPsTop == null) return; foreach (string layername in step.GetAllLayerNames()) { List<ILayer> layers = new List<ILayer>(); layers.Add(step.GetLayer(layername)); SaveImageFromComponent(step, layers, @"C:\E\tests\"); } //something went wrong? string errorLog = IAutomation.GetErrorLog(); if (errorLog.Length > 0) System.Diagnostics.Debug.WriteLine(errorLog); } public void SaveImageFromComponent( IStep step, List<ILayer> layers, string FileLocation) { if (layers.Count == 0) return; RectangleF boundsRelevantCMP = layers[0].GetBounds(); boundsRelevantCMP.Inflate(100, 100); //show a little bit of the area around the component //create the image and save it as png PCBI.Automation.IStep.BitmapResultClass imageClass = step.GetBitmap(layers, boundsRelevantCMP, 500, 500); if (imageClass != null) imageClass.Image.Save(FileLocation + layers[0].GetLayerName() + ".png", System.Drawing.Imaging.ImageFormat.Png); } } }
bsd-3-clause
C#
48655eb1a21113c9aebe9d16a48e5b1eb6aba48f
Convert to NFluent
magicmonty/pickles,ludwigjossieaux/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,blorgbeard/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,irfanah/pickles,picklesdoc/pickles,blorgbeard/pickles,magicmonty/pickles,blorgbeard/pickles,dirkrombauts/pickles,blorgbeard/pickles,picklesdoc/pickles,dirkrombauts/pickles,irfanah/pickles,irfanah/pickles,magicmonty/pickles,picklesdoc/pickles,magicmonty/pickles,irfanah/pickles
src/Pickles/Pickles.Test/DocumentationBuilders/DHTML/WhenDoingSomeIntegrationTests.cs
src/Pickles/Pickles.Test/DocumentationBuilders/DHTML/WhenDoingSomeIntegrationTests.cs
using NFluent; using NUnit.Framework; using PicklesDoc.Pickles.DocumentationBuilders.DHTML; namespace PicklesDoc.Pickles.Test.DocumentationBuilders.DHTML { [TestFixture] public class WhenDoingSomeIntegrationTests : BaseFixture { [Test] public void TestTheResourceWriter() { var conf = new Configuration(); conf.OutputFolder = FileSystem.DirectoryInfo.FromDirectoryName(@"d:\output"); var resourceWriter = new DhtmlResourceWriter(FileSystem); resourceWriter.WriteTo(conf.OutputFolder.FullName); } [Test] public void CanAddFunctionWrapperAroundJson() { string filePath = @"d:\output\pickledFeatures.json"; FileSystem.AddFile(filePath, "\r\n[]\r\n"); var jsonTweaker = new JsonTweaker(FileSystem); jsonTweaker.AddJsonPWrapperTo(filePath); var expected = "jsonPWrapper (\r\n[]\r\n);"; var actual = FileSystem.File.ReadAllText(filePath); Check.That(actual).IsEqualTo(expected); } [Test] public void CanRenameJsonFile() { string oldfilePath = @"d:\output\pickledFeatures.json"; string newFilePath = @"d:\output\pickledFeatures.js"; FileSystem.AddFile(oldfilePath, "test data"); var jsonTweaker = new JsonTweaker(FileSystem); jsonTweaker.RenameFileTo(oldfilePath, newFilePath); var doesNewPathExist = FileSystem.File.Exists(newFilePath); Check.That(doesNewPathExist).IsTrue(); var doesOldPathExist = FileSystem.File.Exists(oldfilePath); Check.That(doesOldPathExist).IsFalse(); } } }
using NUnit.Framework; using PicklesDoc.Pickles.DocumentationBuilders.DHTML; namespace PicklesDoc.Pickles.Test.DocumentationBuilders.DHTML { [TestFixture] public class WhenDoingSomeIntegrationTests : BaseFixture { [Test] public void TestTheResourceWriter() { var conf = new Configuration(); conf.OutputFolder = FileSystem.DirectoryInfo.FromDirectoryName(@"d:\output"); var resourceWriter = new DhtmlResourceWriter(FileSystem); resourceWriter.WriteTo(conf.OutputFolder.FullName); } [Test] public void CanAddFunctionWrapperAroundJson() { string filePath = @"d:\output\pickledFeatures.json"; FileSystem.AddFile(filePath, "\r\n[]\r\n"); var jsonTweaker = new JsonTweaker(FileSystem); jsonTweaker.AddJsonPWrapperTo(filePath); var expected = "jsonPWrapper (\r\n[]\r\n);"; Assert.AreEqual(expected, FileSystem.File.ReadAllText(filePath)); } [Test] public void CanRenameJsonFile() { string oldfilePath = @"d:\output\pickledFeatures.json"; string newFilePath = @"d:\output\pickledFeatures.js"; FileSystem.AddFile(oldfilePath, "test data"); var jsonTweaker = new JsonTweaker(FileSystem); jsonTweaker.RenameFileTo(oldfilePath, newFilePath); Assert.IsTrue(FileSystem.File.Exists(newFilePath)); Assert.IsFalse(FileSystem.File.Exists(oldfilePath)); } } }
apache-2.0
C#
f63b14980792982802f4bbca46f39ed3a9f18da5
Use ObservableCollection
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
src/Core2D.Serializer.Newtonsoft/ProjectContractResolver.cs
src/Core2D.Serializer.Newtonsoft/ProjectContractResolver.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; namespace Core2D.Serializer.Newtonsoft { /// <inheritdoc/> internal class ProjectContractResolver : DefaultContractResolver { /// <inheritdoc/> public override JsonContract ResolveContract(Type type) { if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return base .ResolveContract(typeof(ObservableCollection<>) .MakeGenericType(type.GenericTypeArguments[0])); } return base.ResolveContract(type); } /// <inheritdoc/> protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { return base.CreateProperties(type, memberSerialization).Where(p => p.Writable).ToList(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; namespace Core2D.Serializer.Newtonsoft { /// <inheritdoc/> internal class ProjectContractResolver : DefaultContractResolver { /// <inheritdoc/> public override JsonContract ResolveContract(Type type) { if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return base .ResolveContract(typeof(ImmutableArray<>) .MakeGenericType(type.GenericTypeArguments[0])); } return base.ResolveContract(type); } /// <inheritdoc/> protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { return base.CreateProperties(type, memberSerialization).Where(p => p.Writable).ToList(); } } }
mit
C#
ec240f09156e065952188c7677bcca1a6f7f118d
Add Signalr to owin pipeline like other middlewares.
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
Foundation/Server/Foundation.Api/Middlewares/Signalr/SignalRMiddlewareConfiguration.cs
Foundation/Server/Foundation.Api/Middlewares/Signalr/SignalRMiddlewareConfiguration.cs
using System; using Foundation.Api.Contracts; using Foundation.Api.Middlewares.SignalR.Contracts; using Foundation.Core.Contracts; using Microsoft.AspNet.SignalR; using Owin; using System.Collections.Generic; using System.Linq; namespace Foundation.Api.Middlewares.SignalR { public class SignalRMiddlewareConfiguration : IOwinMiddlewareConfiguration { private readonly IAppEnvironmentProvider _appEnvironmentProvider; private readonly IEnumerable<ISignalRConfiguration> _SignalRScaleoutConfigurations; private readonly Microsoft.AspNet.SignalR.IDependencyResolver _dependencyResolver; protected SignalRMiddlewareConfiguration() { } public SignalRMiddlewareConfiguration(Microsoft.AspNet.SignalR.IDependencyResolver dependencyResolver, IAppEnvironmentProvider appEnvironmentProvider, IEnumerable<ISignalRConfiguration> SignalRScaleoutConfigurations = null) { if (appEnvironmentProvider == null) throw new ArgumentNullException(nameof(appEnvironmentProvider)); if (dependencyResolver == null) throw new ArgumentNullException(nameof(dependencyResolver)); _appEnvironmentProvider = appEnvironmentProvider; _dependencyResolver = dependencyResolver; _SignalRScaleoutConfigurations = SignalRScaleoutConfigurations; } public virtual void Configure(IAppBuilder owinApp) { if (owinApp == null) throw new ArgumentNullException(nameof(owinApp)); HubConfiguration SignalRConfig = new HubConfiguration { EnableDetailedErrors = _appEnvironmentProvider.GetActiveAppEnvironment().DebugMode == true, EnableJavaScriptProxies = true, EnableJSONP = false, Resolver = _dependencyResolver }; _SignalRScaleoutConfigurations.ToList() .ForEach(cnfg => { cnfg.Configure(SignalRConfig); }); owinApp.Map("/signalr", innerOwinApp => { innerOwinApp.RunSignalR(SignalRConfig); }); } } }
using System; using Foundation.Api.Contracts; using Foundation.Api.Middlewares.SignalR.Contracts; using Foundation.Core.Contracts; using Microsoft.AspNet.SignalR; using Owin; using System.Collections.Generic; using System.Linq; namespace Foundation.Api.Middlewares.SignalR { public class SignalRMiddlewareConfiguration : IOwinMiddlewareConfiguration { private readonly IAppEnvironmentProvider _appEnvironmentProvider; private readonly IEnumerable<ISignalRConfiguration> _SignalRScaleoutConfigurations; private readonly Microsoft.AspNet.SignalR.IDependencyResolver _dependencyResolver; protected SignalRMiddlewareConfiguration() { } public SignalRMiddlewareConfiguration(Microsoft.AspNet.SignalR.IDependencyResolver dependencyResolver, IAppEnvironmentProvider appEnvironmentProvider, IEnumerable<ISignalRConfiguration> SignalRScaleoutConfigurations = null) { if (appEnvironmentProvider == null) throw new ArgumentNullException(nameof(appEnvironmentProvider)); if (dependencyResolver == null) throw new ArgumentNullException(nameof(dependencyResolver)); _appEnvironmentProvider = appEnvironmentProvider; _dependencyResolver = dependencyResolver; _SignalRScaleoutConfigurations = SignalRScaleoutConfigurations; } public virtual void Configure(IAppBuilder owinApp) { if (owinApp == null) throw new ArgumentNullException(nameof(owinApp)); HubConfiguration SignalRConfig = new HubConfiguration { EnableDetailedErrors = _appEnvironmentProvider.GetActiveAppEnvironment().DebugMode == true, EnableJavaScriptProxies = true, EnableJSONP = false, Resolver = _dependencyResolver }; _SignalRScaleoutConfigurations.ToList() .ForEach(cnfg => { cnfg.Configure(SignalRConfig); }); owinApp.MapSignalR("/SignalR", SignalRConfig); } } }
mit
C#
bde0d06af1d08557bd334b2a21bc2284a2105b34
Update version to 1.2.0
TheOtherTimDuncan/TOTD-Mailer
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("The Other Tim Duncan")] [assembly: AssemblyProduct("TOTD Mailer")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] // 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.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("The Other Tim Duncan")] [assembly: AssemblyProduct("TOTD Mailer")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
mit
C#
5d07d32c11413d0f5fe35a7449cfb11b4a200dc4
Add OS version telemetry
MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps
Source/Actions/Microsoft.Deployment.Actions.OnPremise/WinNT/ValidateAdminPrivileges.cs
Source/Actions/Microsoft.Deployment.Actions.OnPremise/WinNT/ValidateAdminPrivileges.cs
using System.ComponentModel.Composition; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.Deployment.Common.ActionModel; using Microsoft.Deployment.Common.Actions; using Microsoft.Deployment.Common.Helpers; using Microsoft.Win32; using System; namespace Microsoft.Deployment.Actions.OnPremise.WinNT { // Should not run impersonated [Export(typeof(IAction))] public class ValidateAdminPrivileges : BaseAction { public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request) { string osVersion = null; string productName = null; string installationType = null; try { osVersion = Environment.OSVersion.Version.ToString(); using (RegistryKey k = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")) { object v = k.GetValue("CurrentMajorVersionNumber"); if (v != null) { osVersion = Convert.ToString(v); v = k.GetValue("CurrentMinorVersionNumber"); if (v != null) { osVersion += '.' + Convert.ToString(v); v = k.GetValue("CurrentBuildNumber") ?? k.GetValue("CurrentBuild"); if (v != null) { osVersion += '.' + Convert.ToString(v); } } } productName = (string)k.GetValue("ProductName"); installationType = (string)k.GetValue("InstallationType"); } } catch { // Do nothing, I could not read the OS version and will rely on what .Net says } request.Logger.LogEvent("OSVersion", new System.Collections.Generic.Dictionary<string, string> { { nameof(osVersion), osVersion }, { nameof(productName), productName }, { nameof(installationType), installationType } }); WindowsPrincipal current = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return current.IsInRole(WindowsBuiltInRole.Administrator) ? new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()) : new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "NotAdmin"); } } }
using System.ComponentModel.Composition; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.Deployment.Common.ActionModel; using Microsoft.Deployment.Common.Actions; using Microsoft.Deployment.Common.Helpers; namespace Microsoft.Deployment.Actions.OnPremise.WinNT { // Should not run impersonated [Export(typeof(IAction))] public class ValidateAdminPrivileges : BaseAction { public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request) { WindowsPrincipal current = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return current.IsInRole(WindowsBuiltInRole.Administrator) ? new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()) : new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "NotAdmin"); } } }
mit
C#
20a50ddb6e0639adc5980a4e2c6c85ad2c4d13aa
Add missing `OverlayColourProvider` in test scene
ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game.Tests/Visual/UserInterface/TestSceneFirstRunScreenUIScale.cs
osu.Game.Tests/Visual/UserInterface/TestSceneFirstRunScreenUIScale.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Screens; using osu.Game.Overlays; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene { [Cached] private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple); public TestSceneFirstRunScreenUIScale() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenUIScale()); }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Screens; using osu.Game.Overlays.FirstRunSetup; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneFirstRunScreenUIScale : OsuManualInputManagerTestScene { public TestSceneFirstRunScreenUIScale() { AddStep("load screen", () => { Child = new ScreenStack(new ScreenUIScale()); }); } } }
mit
C#
e1f1fba8b13f65bcdfdf06700e1da1fa98b93d56
Add GetError
dv-lebedev/statistics
Statistics/BasicFuncs.cs
Statistics/BasicFuncs.cs
/* Copyright 2015 Denis Lebedev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Linq; namespace Statistics { public static class BasicFuncs { public static decimal[] GetError(decimal[] values) { decimal[] result = new decimal[values.Length - 1]; for (int i = 1; i < values.Length; i++) { result[i - 1] = values[i] - values[i - 1]; } return result; } public static decimal GetStandardDeviation(decimal[] values) { if (values == null) throw new ArgumentNullException("values"); double[] arr = values.Select(i => (double)i).ToArray(); double result = 0; double average = arr.Average(); for (int i = 0; i < arr.Length; i++) { result += Math.Pow(arr[i] - average, 2); } return (decimal)Math.Sqrt(result /= (arr.Length -1 )); } public static decimal MultiplyArrays(decimal[] x, decimal[] y) { if (x == null) throw new ArgumentNullException("x"); if (y == null) throw new ArgumentNullException("y"); if (x.Length != y.Length) throw new DifferentLengthException(); decimal result = 0; for (int i = 0; i < x.Length; i++) { result += x[i] * y[i]; } return result; } public static decimal PowArray(decimal[] values) { if (values == null) throw new ArgumentNullException("values"); double result = 0; for (int i = 0; i < values.Length; i++) { result += Math.Pow((double)values[i], 2); } return (decimal)result; } } }
/* Copyright 2015 Denis Lebedev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Linq; namespace Statistics { public static class BasicFuncs { public static decimal GetStandardDeviation(decimal[] values) { if (values == null) throw new ArgumentNullException("values"); double[] arr = values.Select(i => (double)i).ToArray(); double result = 0; double average = arr.Average(); for (int i = 0; i < arr.Length; i++) { result += Math.Pow(arr[i] - average, 2); } return (decimal)Math.Sqrt(result /= (arr.Length -1 )); } public static decimal MultiplyArrays(decimal[] x, decimal[] y) { if (x == null) throw new ArgumentNullException("x"); if (y == null) throw new ArgumentNullException("y"); if (x.Length != y.Length) throw new DifferentLengthException(); decimal result = 0; for (int i = 0; i < x.Length; i++) { result += x[i] * y[i]; } return result; } public static decimal PowArray(decimal[] values) { if (values == null) throw new ArgumentNullException("values"); double result = 0; for (int i = 0; i < values.Length; i++) { result += Math.Pow((double)values[i], 2); } return (decimal)result; } } }
apache-2.0
C#
ecde94b623d7f03f911133fdc574781cfa104525
add ProductInfo tag type
Alexx999/SwfSharp
SwfSharp/Tags/TagType.cs
SwfSharp/Tags/TagType.cs
namespace SwfSharp.Tags { public enum TagType { End = 0, ShowFrame = 1, DefineShape = 2, PlaceObject = 4, RemoveObject = 5, DefineBits = 6, DefineButton = 7, JPEGTables = 8, SetBackgroundColor = 9, DefineFont = 10, DefineText = 11, DoAction = 12, DefineFontInfo = 13, DefineSound = 14, StartSound = 15, DefineButtonSound = 17, SoundStreamHead = 18, SoundStreamBlock = 19, DefineBitsLossless = 20, DefineBitsJPEG2 = 21, DefineShape2 = 22, DefineButtonCxform = 23, Protect = 24, PlaceObject2 = 26, RemoveObject2 = 28, DefineShape3 = 32, DefineText2 = 33, DefineButton2 = 34, DefineBitsJPEG3 = 35, DefineBitsLossless2 = 36, DefineEditText = 37, DefineSprite = 39, ProductInfo = 41, FrameLabel = 43, SoundStreamHead2 = 45, DefineMorphShape = 46, DefineFont2 = 48, ExportAssets = 56, ImportAssets = 57, EnableDebugger = 58, DoInitAction = 59, DefineVideoStream = 60, VideoFrame = 61, DefineFontInfo2 = 62, EnableDebugger2 = 64, ScriptLimits = 65, SetTabIndex = 66, FileAttributes = 69, PlaceObject3 = 70, ImportAssets2 = 71, DefineFontAlignZones = 73, CSMTextSetting = 74, DefineFont3 = 75, SymbolClass = 76, Metadata = 77, DefineScalingGrid = 78, DoABC = 82, DefineShape4 = 83, DefineMorphShape2 = 84, DefineSceneAndFrameLabelData = 86, DefineBinaryData = 87, DefineFontName = 88, StartSound2 = 89, DefineBitsJPEG4 = 90, DefineFont4 = 91, EnableTelemetry = 93, } }
namespace SwfSharp.Tags { public enum TagType { End = 0, ShowFrame = 1, DefineShape = 2, PlaceObject = 4, RemoveObject = 5, DefineBits = 6, DefineButton = 7, JPEGTables = 8, SetBackgroundColor = 9, DefineFont = 10, DefineText = 11, DoAction = 12, DefineFontInfo = 13, DefineSound = 14, StartSound = 15, DefineButtonSound = 17, SoundStreamHead = 18, SoundStreamBlock = 19, DefineBitsLossless = 20, DefineBitsJPEG2 = 21, DefineShape2 = 22, DefineButtonCxform = 23, Protect = 24, PlaceObject2 = 26, RemoveObject2 = 28, DefineShape3 = 32, DefineText2 = 33, DefineButton2 = 34, DefineBitsJPEG3 = 35, DefineBitsLossless2 = 36, DefineEditText = 37, DefineSprite = 39, FrameLabel = 43, SoundStreamHead2 = 45, DefineMorphShape = 46, DefineFont2 = 48, ExportAssets = 56, ImportAssets = 57, EnableDebugger = 58, DoInitAction = 59, DefineVideoStream = 60, VideoFrame = 61, DefineFontInfo2 = 62, EnableDebugger2 = 64, ScriptLimits = 65, SetTabIndex = 66, FileAttributes = 69, PlaceObject3 = 70, ImportAssets2 = 71, DefineFontAlignZones = 73, CSMTextSetting = 74, DefineFont3 = 75, SymbolClass = 76, Metadata = 77, DefineScalingGrid = 78, DoABC = 82, DefineShape4 = 83, DefineMorphShape2 = 84, DefineSceneAndFrameLabelData = 86, DefineBinaryData = 87, DefineFontName = 88, StartSound2 = 89, DefineBitsJPEG4 = 90, DefineFont4 = 91, EnableTelemetry = 93, } }
mit
C#
6ef848c6489f428a5f2f57f9196a96ee2aa9a8b9
Use expected in tests for F.Always
farity/farity
Farity.Tests/AlwaysTests.cs
Farity.Tests/AlwaysTests.cs
using Xunit; namespace Farity.Tests { public class AlwaysTests { [Fact] public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways() { const int expected = 42; var answerToLifeUniverseAndEverything = F.Always(expected); Assert.Equal(expected, answerToLifeUniverseAndEverything()); Assert.Equal(expected, answerToLifeUniverseAndEverything(1)); Assert.Equal(expected, answerToLifeUniverseAndEverything("string", null)); Assert.Equal(expected, answerToLifeUniverseAndEverything(null, "str", 3)); Assert.Equal(expected, answerToLifeUniverseAndEverything(null, null, null, null)); } } }
using Xunit; namespace Farity.Tests { public class AlwaysTests { [Fact] public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways() { var answerToLifeUniverseAndEverything = F.Always(42); var answer = answerToLifeUniverseAndEverything(); Assert.Equal(answer, answerToLifeUniverseAndEverything()); Assert.Equal(answer, answerToLifeUniverseAndEverything(1)); Assert.Equal(answer, answerToLifeUniverseAndEverything("string", null)); Assert.Equal(answer, answerToLifeUniverseAndEverything(null, "str", 3)); Assert.Equal(answer, answerToLifeUniverseAndEverything(null, null, null, null)); } } }
mit
C#
cb69ee2b23c0b36385c1c23c92f2f27ad44edcec
fix deprecated method use
Pathoschild/StardewMods
NoDebugMode/ModEntry.cs
NoDebugMode/ModEntry.cs
using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; namespace Pathoschild.Stardew.NoDebugMode { /// <summary>The mod entry point.</summary> public class ModEntry : Mod { /********* ** Public methods *********/ /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { GameEvents.QuarterSecondTick += (sender, e) => this.SuppressGameDebug(); } /********* ** Protected methods *********/ /// <summary>Immediately suppress the game's debug mode if it's enabled.</summary> private void SuppressGameDebug() { if (Game1.debugMode) { Game1.debugMode = false; this.Monitor.Log("No Debug Mode suppressed SMAPI F2 debug mode."); } } } }
using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; namespace Pathoschild.Stardew.NoDebugMode { /// <summary>The mod entry point.</summary> public class ModEntry : Mod { /********* ** Public methods *********/ /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { GameEvents.QuarterSecondTick += (sender, e) => this.SuppressGameDebug(); } /********* ** Protected methods *********/ /// <summary>Immediately suppress the game's debug mode if it's enabled.</summary> private void SuppressGameDebug() { if (Game1.debugMode) { Game1.debugMode = false; Log.Debug("No Debug Mode suppressed SMAPI F2 debug mode."); } } } }
mit
C#
027a53126659a0119f9443ac1e72e48ffa4ff86c
Edit program cs
eklnc/TwitterStream
TwitterStream/Program.cs
TwitterStream/Program.cs
using System; using System.Net; using TwitterStream.Tables; namespace TwitterStream { class Program { static void Main(string[] args) { //using (var context = new TwitterStreamContext()) //{ // TwitterStream stream = new TwitterStream(context); // try // { // stream.Start(); // } // catch (WebException ex) // { // Console.WriteLine("***HATA ALINDI ***: " + ex.Message + "\n\n"); // stream.InsertError(ex); // } //} } } }
using System; using System.Net; using TwitterStream.Tables; namespace TwitterStream { class Program { static void Main(string[] args) { using (var context = new TwitterStreamContext()) { TwitterStream stream = new TwitterStream(context); try { stream.Start(); } catch (WebException ex) { Console.WriteLine("***HATA ALINDI ***: " + ex.Message + "\n\n"); stream.InsertError(ex); } } } } }
mit
C#
b2b8abdf2719b73d687799949dfed63fa79935dc
fix typo
Catel/Catel.Fody
src/Catel.Fody.Attributes/ArgumentAttributes/InheritsFromAttribute.cs
src/Catel.Fody.Attributes/ArgumentAttributes/InheritsFromAttribute.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InheritsFromAttribute.cs" company="Catel development team"> // Copyright (c) 2008 - 2013 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Fody { using System; /// <summary> /// Inherits from attribute. /// </summary> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public class InheritsFromAttribute : Attribute { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="InheritsFromAttribute"/> class. /// </summary> /// <param name="type">The type.</param> public InheritsFromAttribute(Type type) { } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InherithsFromAttribute.cs" company="Catel development team"> // Copyright (c) 2008 - 2013 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Fody { using System; /// <summary> /// Inherits from attribute. /// </summary> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public class InheritsFromAttribute : Attribute { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="InheritsFromAttribute"/> class. /// </summary> /// <param name="type">The type.</param> public InheritsFromAttribute(Type type) { } #endregion } }
mit
C#
98e07be0aa23d12a06e22055d5f5f6e1e5a32515
Rename variable to increase clearity
blorgbeard/pickles,picklesdoc/pickles,magicmonty/pickles,picklesdoc/pickles,blorgbeard/pickles,magicmonty/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles,blorgbeard/pickles,magicmonty/pickles,dirkrombauts/pickles,picklesdoc/pickles,dirkrombauts/pickles,blorgbeard/pickles,dirkrombauts/pickles,magicmonty/pickles
src/Pickles/Pickles.Test/DocumentationBuilders/JSON/AutomationLayer/StepDefinitions.cs
src/Pickles/Pickles.Test/DocumentationBuilders/JSON/AutomationLayer/StepDefinitions.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Autofac; using NFluent; using NGenerics.DataStructures.Trees; using PicklesDoc.Pickles.DirectoryCrawler; using PicklesDoc.Pickles.DocumentationBuilders.HTML; using PicklesDoc.Pickles.DocumentationBuilders.JSON; using PicklesDoc.Pickles.ObjectModel; using PicklesDoc.Pickles.Test.DocumentationBuilders.HTML.AutomationLayer; using TechTalk.SpecFlow; namespace PicklesDoc.Pickles.Test.DocumentationBuilders.JSON.AutomationLayer { [Binding] [Scope(Tag = "json")] public sealed class StepDefinitions : BaseFixture /* God object antipattern */ { private GeneralTree<INode> nodes; // For additional details on SpecFlow step definitions see http://go.specflow.org/doc-stepdef [Given("I have this feature description")] public void IHaveThisFeatureDescription(string featureDescription) { FeatureParser parser = new FeatureParser(base.FileSystem); var feature = parser.Parse(new StringReader(featureDescription)); this.nodes = new GeneralTree<INode>(new FeatureNode(base.FileSystem.DirectoryInfo.FromDirectoryName(@"c:\output\"), string.Empty, feature)); } [When(@"I generate the documentation")] public void WhenIGenerateTheJsonDocumentation() { var configuration = base.Container.Resolve<Configuration>(); configuration.OutputFolder = base.FileSystem.DirectoryInfo.FromDirectoryName(@"c:\output\"); var jsonDocumentationBuilder = base.Container.Resolve<JSONDocumentationBuilder>(); jsonDocumentationBuilder.Build(this.nodes); } [Then("the JSON file should contain")] public void ThenTheResultShouldBe(string expectedResult) { var actualResult = base.FileSystem.File.ReadAllText(@"c:\output\pickledFeatures.json"); actualResult = actualResult.Replace("{", "{{").Replace("}", "}}"); expectedResult = expectedResult.Replace("{", "{{").Replace("}", "}}"); Check.That(actualResult).Contains(expectedResult); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Autofac; using NFluent; using NGenerics.DataStructures.Trees; using PicklesDoc.Pickles.DirectoryCrawler; using PicklesDoc.Pickles.DocumentationBuilders.HTML; using PicklesDoc.Pickles.DocumentationBuilders.JSON; using PicklesDoc.Pickles.ObjectModel; using PicklesDoc.Pickles.Test.DocumentationBuilders.HTML.AutomationLayer; using TechTalk.SpecFlow; namespace PicklesDoc.Pickles.Test.DocumentationBuilders.JSON.AutomationLayer { [Binding] [Scope(Tag = "json")] public sealed class StepDefinitions : BaseFixture /* God object antipattern */ { private GeneralTree<INode> nodes; // For additional details on SpecFlow step definitions see http://go.specflow.org/doc-stepdef [Given("I have this feature description")] public void IHaveThisFeatureDescription(string featureDescription) { FeatureParser parser = new FeatureParser(base.FileSystem); var feature = parser.Parse(new StringReader(featureDescription)); this.nodes = new GeneralTree<INode>(new FeatureNode(base.FileSystem.DirectoryInfo.FromDirectoryName(@"c:\output\"), string.Empty, feature)); } [When(@"I generate the documentation")] public void WhenIGenerateTheJsonDocumentation() { var configuration = base.Container.Resolve<Configuration>(); configuration.OutputFolder = base.FileSystem.DirectoryInfo.FromDirectoryName(@"c:\output\"); var jsonDocumentationBuilder = base.Container.Resolve<JSONDocumentationBuilder>(); jsonDocumentationBuilder.Build(this.nodes); } [Then("the JSON file should contain")] public void ThenTheResultShouldBe(string result) { var actualResult = base.FileSystem.File.ReadAllText(@"c:\output\pickledFeatures.json"); actualResult = actualResult.Replace("{", "{{").Replace("}", "}}"); result = result.Replace("{", "{{").Replace("}", "}}"); Check.That(actualResult).Contains(result); } } }
apache-2.0
C#
a69b4a75535c94f174fe1a520d6f69b7cbcfe3e5
Tidy up a bit,
orionrobots/Bounce,orionrobots/Bounce
MainUi/MainUi/BlocklyLua.cs
MainUi/MainUi/BlocklyLua.cs
using CefSharp; using CefSharp.WinForms; using System; using System.IO; using System.Threading.Tasks; using System.Windows.Forms; namespace MainUi { // Render the blockly lua web component. // Handle getting: // Saving // Loading // Get Lua Code // Printing? class BlocklyLua { private IBrowser _br; public BlocklyLua(ChromiumWebBrowser br) { _br = br.GetBrowser(); } public static Uri GetAddress() { string appDir = Path.GetDirectoryName(Application.ExecutablePath); return new Uri(Path.Combine(appDir, "BlocklyMcu", "blocklyLua.html")); } public async Task<string> GetCode() { // This will get the lua code to send to our device. JavascriptResponse r = await _br.MainFrame.EvaluateScriptAsync("Blockly.Lua.workspaceToCode(workspace);"); if(! r.Success ) { throw new OperationCanceledException(r.Message); } return r.Result.ToString(); } public async Task SaveDocument(Stream output) { JavascriptResponse r = await _br.FocusedFrame.EvaluateScriptAsync("export_document();"); var sw = new StreamWriter(output); sw.Write(r.Result.ToString()); sw.Flush(); } internal void InitiateLoad() { _br.FocusedFrame.EvaluateScriptAsync("load_document();"); } } }
using CefSharp; using CefSharp.WinForms; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MainUi { // Render the blockly lua web component. // Handle getting: // Saving // Loading // Get Lua Code // Printing? class BlocklyLua { private IBrowser _br; public BlocklyLua(ChromiumWebBrowser br) { _br = br.GetBrowser(); } public static Uri GetAddress() { string appDir = Path.GetDirectoryName(Application.ExecutablePath); return new Uri(Path.Combine(appDir, "BlocklyMcu", "blocklyLua.html")); } public async Task<string> GetCode() { // This will get the lua code to send to our device. JavascriptResponse r = await _br.MainFrame.EvaluateScriptAsync("Blockly.Lua.workspaceToCode(workspace);"); if(! r.Success ) { throw new OperationCanceledException(r.Message); } return r.Result.ToString(); } public async Task SaveDocument(Stream output) { JavascriptResponse r = await _br.FocusedFrame.EvaluateScriptAsync("export_document();"); var sw = new StreamWriter(output); sw.Write(r.Result.ToString()); sw.Flush(); } internal void InitiateLoad() { _br.FocusedFrame.EvaluateScriptAsync("load_document();"); } } }
apache-2.0
C#
28d9cb4a7715d5fce30396e46e38a9fd6f069d09
check if parent icon exists
PavelMaca/WoT-PogsIconSet
Icon.cs
Icon.cs
using Phobos.WoT; using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using WotPogsIconSet.Layers; using WotPogsIconSet.Utils; using System.IO; namespace WotPogsIconSet { public class Icon : IDisposable { public const int WIDTH = 80; public const int HEIGHT = 24; protected Graphics g; protected Bitmap image; public Icon() { // create new image image = new Bitmap(WIDTH, HEIGHT, PixelFormat.Format32bppArgb); prepareGraphics(); } public Icon(string parentFile) { // use existing image if (!File.Exists(parentFile)) { throw new Exception("Výchozí vrstva neexistuje."); } image = new Bitmap(ImageTools.loadFromFile(parentFile)); prepareGraphics(); } protected void prepareGraphics() { image.SetResolution(72.0f, 72.0f); // fix DPI g = Graphics.FromImage(image); g.PageUnit = GraphicsUnit.Pixel; g.SmoothingMode = SmoothingMode.None; g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel; g.TextContrast = 0; } public void Save(string outputFile) { g.Flush(); image.Save(outputFile, ImageFormat.Png); } public void Apply(Layer layer, TankStats tankStats) { try { layer(g, tankStats); } catch (Exception e) { Console.WriteLine("Error during appling layer: " + layer.Method); Console.WriteLine(e.Message + "\n"); } } public void Dispose() { g.Dispose(); image.Dispose(); } } }
using Phobos.WoT; using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using WotPogsIconSet.Layers; using WotPogsIconSet.Utils; namespace WotPogsIconSet { public class Icon : IDisposable { public const int WIDTH = 80; public const int HEIGHT = 24; protected Graphics g; protected Bitmap image; public Icon() { // create new image image = new Bitmap(WIDTH, HEIGHT, PixelFormat.Format32bppArgb); prepareGraphics(); } public Icon(string parentFile) { // use existing image image = new Bitmap(ImageTools.loadFromFile(parentFile)); prepareGraphics(); } protected void prepareGraphics() { image.SetResolution(72.0f, 72.0f); // fix DPI g = Graphics.FromImage(image); g.PageUnit = GraphicsUnit.Pixel; g.SmoothingMode = SmoothingMode.None; g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel; g.TextContrast = 0; } public void Save(string outputFile) { g.Flush(); image.Save(outputFile, ImageFormat.Png); } public void Apply(Layer layer, TankStats tankStats) { try { layer(g, tankStats); } catch (Exception e) { Console.WriteLine("Error during appling layer: " + layer.Method); Console.WriteLine(e.Message + "\n"); } } public void Dispose() { g.Dispose(); image.Dispose(); } } }
bsd-3-clause
C#
d847728e0237b215cd5ffdeeb36df81ff5c71ae1
Disable XSS filter
06b/Emperor-Imports,06b/Emperor-Imports
src/EmperorImports/Bootstrapper.cs
src/EmperorImports/Bootstrapper.cs
using Nancy; using Nancy.Elmah; using Nancy.Bootstrapper; using Nancy.TinyIoc; namespace EmperorImports { public class Bootstrapper : DefaultNancyBootstrapper { protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); /// <summary> /// Elmah Logging - Enable Exception logging with select HttpStatusCode logging /// </summary> //Note: Elmah left unsecured purposely. Elmahlogging.Enable(pipelines, "elmah", new string[0], new HttpStatusCode[] { HttpStatusCode.NotFound, HttpStatusCode.InsufficientStorage, }); } protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); pipelines.AfterRequest.AddItemToEndOfPipeline(c => { //Disable XSS filter c.Response.Headers["X-XSS-Protection"] = "0"; }); } } }
using Nancy; using Nancy.Elmah; using Nancy.Bootstrapper; using Nancy.TinyIoc; namespace EmperorImports { public class Bootstrapper : DefaultNancyBootstrapper { protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); /// <summary> /// Elmah Logging - Enable Exception logging with select HttpStatusCode logging /// </summary> //Note: Elmah left unsecured purposely. Elmahlogging.Enable(pipelines, "elmah", new string[0], new HttpStatusCode[] { HttpStatusCode.NotFound, HttpStatusCode.InsufficientStorage, }); } } }
mit
C#
3a85f31d6cc293e302c35ac83988e45d28f9f65e
Make GroupsClient API V3 compatible
marska/habitrpg-api-dotnet-client
src/HabitRPG.Client/Model/Group.cs
src/HabitRPG.Client/Model/Group.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace HabitRPG.Client.Model { public class Group { /// <summary> /// DataType is String because the Tavern has the GroupId: habitrpg /// </summary> [JsonProperty("_id")] public string Id { get; set; } [JsonProperty("balance")] public double Balance { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("leader")] public Member Leader { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("memberCount")] public int MemberCount { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("logo")] public string Logo { get; set; } [JsonProperty("quest")] public Quest Quest { get; set; } [JsonProperty("chat")] public List<ChatMessage> Chat { get; set; } [JsonProperty("members")] public List<Member> Members { get; set; } [JsonProperty("challengeCount")] public int ChallengeCount { get; set; } [JsonProperty("challenges")] public List<Challenge> Challenges { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace HabitRPG.Client.Model { public class Group { /// <summary> /// DataType is String because the Tavern has the GroupId: habitrpg /// </summary> [JsonProperty("_id")] public string Id { get; set; } [JsonProperty("balance")] public double Balance { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("leader")] public Guid Leader { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("memberCount")] public int MemberCount { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("logo")] public string Logo { get; set; } [JsonProperty("quest")] public Quest Quest { get; set; } [JsonProperty("chat")] public List<ChatMessage> Chat { get; set; } [JsonProperty("members")] public List<Member> Members { get; set; } [JsonProperty("challengeCount")] public int ChallengeCount { get; set; } [JsonProperty("challenges")] public List<Challenge> Challenges { get; set; } } }
apache-2.0
C#
efda9ad960a1c1813c09952fa133d7c3fc980878
remove redundant attribute postfix
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.WebApp/Startup.cs
NinjaHive.WebApp/Startup.cs
using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(NinjaHive.WebApp.Startup))] namespace NinjaHive.WebApp { public partial class Startup { public void Configuration(IAppBuilder app) { var container = Bootstrapper.Initialize(app); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, container); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ConfigureAuth(app, container); } } }
using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(NinjaHive.WebApp.Startup))] namespace NinjaHive.WebApp { public partial class Startup { public void Configuration(IAppBuilder app) { var container = Bootstrapper.Initialize(app); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, container); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ConfigureAuth(app, container); } } }
apache-2.0
C#
a52636ec2509cd64cf9a828ec234b980c3758777
Add compiled to regex
deeja/Pigeon
Pigeon.Zipper/FileFinder.cs
Pigeon.Zipper/FileFinder.cs
namespace Pigeon.Zipper { using System; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; public class FileFinder { private readonly string logDirectory; /// <summary> /// First group is the date, second is the time /// </summary> static readonly Regex DateRegex = new Regex(@"\.(2[01][123][0-9][0-1][0-9][0-3][0-9])\.([0-2][0-9][0-5][0-9][0-5][0-9]){0,1}", RegexOptions.Compiled); public FileFinder(string logDirectory) { this.logDirectory = logDirectory; } public string[] FindLogFiles(DateTime start, DateTime end) { if (end < start) { throw new ArgumentException("Start date should be before end date", nameof(start)); } var files = Directory.GetFiles(this.logDirectory); return files.Where(this.HasDate) .Select(s => new { file = s, date = this.GetDate(s) }) .Where(arg => arg.date >= start) .Where(arg => arg.date < end) .Select(arg => arg.file).ToArray(); } private bool HasDate(string fileName) { return DateRegex.IsMatch(fileName); } private DateTime GetDate(string filename) { var match = DateRegex.Match(filename); var dateSection = match.Groups[1].Captures[0].Value; if (this.HasTime(match)) { var timeSection = match.Groups[2].Captures[0].Value; return DateTime.ParseExact(dateSection + timeSection, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); } return DateTime.ParseExact(dateSection, "yyyyMMdd", CultureInfo.InvariantCulture); } private bool HasTime(Match match) { return match.Groups[2].Captures.Count == 1; } } }
namespace Pigeon.Zipper { using System; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Serialization.Configuration; using Sitecore.Diagnostics; public class FileFinder { private readonly string logDirectory; /// <summary> /// First group is the date, second is the time /// </summary> static readonly Regex DateRegex = new Regex(@"\.(2[01][123][0-9][0-1][0-9][0-3][0-9])\.([0-2][0-9][0-5][0-9][0-5][0-9]){0,1}"); public FileFinder(string logDirectory) { this.logDirectory = logDirectory; } public string[] FindLogFiles(DateTime start, DateTime end) { if (end < start) { throw new ArgumentException("Start date should be before end date", nameof(start)); } var files = Directory.GetFiles(this.logDirectory); return files.Where(this.HasDate) .Select(s => new { file = s, date = this.GetDate(s) }) .Where(arg => arg.date >= start) .Where(arg => arg.date < end) .Select(arg => arg.file).ToArray(); } private bool HasDate(string fileName) { return DateRegex.IsMatch(fileName); } private DateTime GetDate(string filename) { var match = DateRegex.Match(filename); var dateSection = match.Groups[1].Captures[0].Value; if (this.HasTime(match)) { var timeSection = match.Groups[2].Captures[0].Value; return DateTime.ParseExact(dateSection + timeSection, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); } return DateTime.ParseExact(dateSection, "yyyyMMdd", CultureInfo.InvariantCulture); } private bool HasTime(Match match) { return match.Groups[2].Captures.Count == 1; } } }
mit
C#
0c4ea4beb102d0df710c94472a2fc92ed8e36e20
Allow dynamic recompilation of beatmap panel testcase
smoogipoo/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,EVAST9919/osu,EVAST9919/osu,smoogipooo/osu
osu.Game.Tournament.Tests/TestCaseBeatmapPanel.cs
osu.Game.Tournament.Tests/TestCaseBeatmapPanel.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Rulesets; using osu.Game.Tests.Visual; using osu.Game.Tournament.Components; namespace osu.Game.Tournament.Tests { public class TestCaseBeatmapPanel : OsuTestCase { [Resolved] private APIAccess api { get; set; } = null; [Resolved] private RulesetStore rulesets { get; set; } = null; public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(TournamentBeatmapPanel), }; [BackgroundDependencyLoader] private void load() { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 }); req.Success += success; api.Queue(req); } private void success(APIBeatmap apiBeatmap) { var beatmap = apiBeatmap.ToBeatmap(rulesets); Add(new TournamentBeatmapPanel(beatmap) { Anchor = Anchor.Centre, Origin = Anchor.Centre }); } } }
// 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.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Rulesets; using osu.Game.Tests.Visual; using osu.Game.Tournament.Components; namespace osu.Game.Tournament.Tests { public class TestCaseBeatmapPanel : OsuTestCase { [Resolved] private APIAccess api { get; set; } = null; [Resolved] private RulesetStore rulesets { get; set; } = null; [BackgroundDependencyLoader] private void load() { var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 1091460 }); req.Success += success; api.Queue(req); } private void success(APIBeatmap apiBeatmap) { var beatmap = apiBeatmap.ToBeatmap(rulesets); Add(new TournamentBeatmapPanel(beatmap) { Anchor = Anchor.Centre, Origin = Anchor.Centre }); } } }
mit
C#
347fd38f00c06d47c807c7b8f921e2c17674a746
Fix order of high-frequency messages on file queues
modulexcite/lokad-cqrs
Framework/Lokad.Cqrs.Portable/Feature.FilePartition/FileQueueWriter.cs
Framework/Lokad.Cqrs.Portable/Feature.FilePartition/FileQueueWriter.cs
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using System.IO; using System.Threading; using Lokad.Cqrs.Core.Outbox; namespace Lokad.Cqrs.Feature.FilePartition { public sealed class FileQueueWriter : IQueueWriter { readonly DirectoryInfo _folder; readonly IEnvelopeStreamer _streamer; public string Name { get; private set; } public readonly string Suffix ; public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer) { _folder = folder; _streamer = streamer; Name = name; Suffix = Guid.NewGuid().ToString().Substring(0, 4); } static long UniversalCounter; public void PutMessage(ImmutableEnvelope envelope) { var id = Interlocked.Increment(ref UniversalCounter); var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss}-{1:00000000}-{2}", envelope.CreatedOnUtc, id, Suffix); var full = Path.Combine(_folder.FullName, fileName); var data = _streamer.SaveEnvelopeData(envelope); File.WriteAllBytes(full, data); } } }
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using System.IO; using Lokad.Cqrs.Core.Outbox; namespace Lokad.Cqrs.Feature.FilePartition { public sealed class FileQueueWriter : IQueueWriter { readonly DirectoryInfo _folder; readonly IEnvelopeStreamer _streamer; public string Name { get; private set; } public FileQueueWriter(DirectoryInfo folder, string name, IEnvelopeStreamer streamer) { _folder = folder; _streamer = streamer; Name = name; } public void PutMessage(ImmutableEnvelope envelope) { var fileName = string.Format("{0:yyyy-MM-dd-HH-mm-ss-ffff}-{1}", envelope.CreatedOnUtc, Guid.NewGuid()); var full = Path.Combine(_folder.FullName, fileName); var data = _streamer.SaveEnvelopeData(envelope); File.WriteAllBytes(full, data); } } }
bsd-3-clause
C#
29d5451c7f4d4d358a5b1cc9aac3381bfe2b120a
Fix upload size limit.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
backend/src/Squidex.Web/AssetRequestSizeLimitAttribute.cs
backend/src/Squidex.Web/AssetRequestSizeLimitAttribute.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Squidex.Domain.Apps.Entities.Assets; namespace Squidex.Web { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public sealed class AssetRequestSizeLimitAttribute : Attribute, IAuthorizationFilter, IRequestSizePolicy, IOrderedFilter { public int Order { get; } = 900; public void OnAuthorization(AuthorizationFilterContext context) { var assetOptions = context.HttpContext.RequestServices.GetService<IOptions<AssetOptions>>(); var maxRequestBodySizeFeature = context.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>(); if (maxRequestBodySizeFeature?.IsReadOnly == false) { if (assetOptions?.Value.MaxSize > 0) { maxRequestBodySizeFeature.MaxRequestBodySize = assetOptions.Value.MaxSize; } else { maxRequestBodySizeFeature.MaxRequestBodySize = null; } } if (assetOptions?.Value.MaxSize > 0) { var options = new FormOptions { MultipartBodyLengthLimit = assetOptions.Value.MaxSize }; context.HttpContext.Features.Set<IFormFeature>(new FormFeature(context.HttpContext.Request, options)); } } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Squidex.Domain.Apps.Entities.Assets; namespace Squidex.Web { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public sealed class AssetRequestSizeLimitAttribute : Attribute, IAuthorizationFilter, IRequestSizePolicy { public void OnAuthorization(AuthorizationFilterContext context) { var assetOptions = context.HttpContext.RequestServices.GetService<IOptions<AssetOptions>>(); var maxRequestBodySizeFeature = context.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>(); if (maxRequestBodySizeFeature?.IsReadOnly == false) { if (assetOptions?.Value.MaxSize > 0) { maxRequestBodySizeFeature.MaxRequestBodySize = assetOptions.Value.MaxSize; } else { maxRequestBodySizeFeature.MaxRequestBodySize = null; } } } } }
mit
C#
8fc2b5c17b70607d4891ac88b1522a035f409e6c
Update SingleEntryCurrencyConversionCompositionStrategy.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/SingleEntryCurrencyConversionCompositionStrategy.cs
TIKSN.Core/Finance/SingleEntryCurrencyConversionCompositionStrategy.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TIKSN.Finance.Helpers; namespace TIKSN.Finance { public class SingleEntryCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy { public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConverters(converters, baseMoney.Currency, counterCurrency, asOn, cancellationToken); var converter = filteredConverters.Single(); return await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken); } public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConverters(converters, pair, asOn, cancellationToken); var converter = filteredConverters.Single(); return await converter.GetExchangeRateAsync(pair, asOn, cancellationToken); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TIKSN.Finance.Helpers; namespace TIKSN.Finance { public class SingleEntryCurrencyConversionCompositionStrategy : ICurrencyConversionCompositionStrategy { public async Task<Money> ConvertCurrencyAsync(Money baseMoney, IEnumerable<ICurrencyConverter> converters, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConverters(converters, baseMoney.Currency, counterCurrency, asOn, cancellationToken); var converter = filteredConverters.Single(); return await converter.ConvertCurrencyAsync(baseMoney, counterCurrency, asOn, cancellationToken); } public async Task<decimal> GetExchangeRateAsync(IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn, CancellationToken cancellationToken) { var filteredConverters = await CurrencyHelper.FilterConverters(converters, pair, asOn, cancellationToken); var converter = filteredConverters.Single(); return await converter.GetExchangeRateAsync(pair, asOn,cancellationToken); } } }
mit
C#
6e4eacf00618184cdab88d262a1865cf8306fc8b
Fix RequirePermissionAttribute
Nanabell/NoAdsHere
NoAdsHere/Common/Preconditions/RequirePermissionAttribute.cs
NoAdsHere/Common/Preconditions/RequirePermissionAttribute.cs
using System; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using NoAdsHere.Database; using NoAdsHere.Database.Models.Global; namespace NoAdsHere.Common.Preconditions { public class RequirePermissionAttribute : PreconditionAttribute { private readonly AccessLevel _level; public RequirePermissionAttribute(AccessLevel level) { _level = level; } public override async Task<PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services) { var level = await GetLevel(context, services.GetService<MongoClient>()); return level >= _level ? PreconditionResult.FromSuccess() : PreconditionResult.FromError($"Insufficient permissions! Required level: {_level}"); } private static async Task<AccessLevel> GetLevel(ICommandContext context, MongoClient mongo) { if (context.User.IsBot) return AccessLevel.Blocked; var application = await context.Client.GetApplicationInfoAsync(); if (application.Owner.Id == context.User.Id) return AccessLevel.God; var masters = await mongo.GetCollection<Master>(context.Client).GetMastersAsync(); if (masters.Any(master => master.UserId == context.User.Id)) return AccessLevel.Master; if (!(context.User is IGuildUser guildUser)) return AccessLevel.Private; if (context.Guild.OwnerId == context.User.Id) return AccessLevel.Owner; if (guildUser.GuildPermissions.Administrator) return AccessLevel.Admin; if (guildUser.GuildPermissions.BanMembers) return AccessLevel.HighModerator; return guildUser.GuildPermissions.ManageMessages ? AccessLevel.Moderator : AccessLevel.User; } } }
using System; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using NoAdsHere.Database; using NoAdsHere.Database.Models.Settings; namespace NoAdsHere.Common.Preconditions { public class RequirePermissionAttribute : PreconditionAttribute { private readonly AccessLevel _level; public RequirePermissionAttribute(AccessLevel level) { _level = level; } public override async Task<PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services) { var level = await GetLevel(context, services.GetService<MongoClient>()); return level >= _level ? PreconditionResult.FromSuccess() : PreconditionResult.FromError($"Insufficient permissions! Required level: {_level}"); } private static async Task<AccessLevel> GetLevel(ICommandContext context, MongoClient mongo) { if (context.User.IsBot) return AccessLevel.Blocked; var application = await context.Client.GetApplicationInfoAsync(); if (application.Owner.Id == context.User.Id) return AccessLevel.God; var masters = await mongo.GetCollection<Master>(context.Client).GetMastersAsync(); if (masters.Any(master => master.UserId == context.User.Id)) return AccessLevel.Master; if (context.Guild == null) return AccessLevel.Private; if (context.Guild.OwnerId == context.User.Id) return AccessLevel.Owner; var guildUser = context.User as IGuildUser; if (guildUser == null) return AccessLevel.Private; if (guildUser.GuildPermissions.Administrator) return AccessLevel.Admin; if (guildUser.GuildPermissions.BanMembers) return AccessLevel.HighModerator; return guildUser.GuildPermissions.ManageMessages ? AccessLevel.Moderator : AccessLevel.User; } } }
mit
C#
9b683cbc79fa9e3dbe7db3edfe0ffd383668fba0
Update LambdaConverter.cs
he-dev/Reusable,he-dev/Reusable
Reusable.Utilities.JsonNet/src/Converters/LambdaConverter.cs
Reusable.Utilities.JsonNet/src/Converters/LambdaConverter.cs
using System; using Newtonsoft.Json; namespace Reusable.Utilities.JsonNet.Converters { public delegate object WriteJsonCallback<in T>(T value); public class LambdaConverter<T> : JsonConverter<T> { private readonly WriteJsonCallback<T> _writeJsonCallback; public LambdaConverter(WriteJsonCallback<T> writeJsonCallback) { _writeJsonCallback = writeJsonCallback; } public static LambdaConverter<T> Create(WriteJsonCallback<T> convert) => new LambdaConverter<T>(convert); public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer) { serializer.Serialize(writer, _writeJsonCallback(value)); } public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer) { throw new NotImplementedException(); } } }
using System; using Newtonsoft.Json; namespace Reusable.Utilities.JsonNet.Converters { public delegate object WriteJsonCallback<in T>(T value); public class LambdaConverter<T> : JsonConverter<T> { private readonly WriteJsonCallback<T> _writeJsonCallback; public LambdaConverter(WriteJsonCallback<T> writeJsonCallback) { _writeJsonCallback = writeJsonCallback; } public static LambdaConverter<T> Create(WriteJsonCallback<T> convert) => new LambdaConverter<T>(convert); public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer) { serializer.Serialize(writer, _writeJsonCallback(value)); } public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer) { throw new NotImplementedException(); } } }
mit
C#
5b42a1e223ab03e8ad3bafe7363f93aa02dbda2c
Make Prelude functions extensible.
alldne/school,alldne/school
School/Evaluator/Prelude.cs
School/Evaluator/Prelude.cs
using System; using System.Collections.Generic; using System.Linq; namespace School.Evaluator { public static class Prelude { private static Dictionary<string, Value> Dict; public static Value Lookup(string name) { if (Dict.ContainsKey(name)) return Dict[name]; else return UnitValue.Singleton; } public static void Register(string name, Func<Value, Value> fun) { Dict.Add(name, new FunValue1(fun)); } public static void Register(string name, Func<Value, Value, Value> fun) { Dict.Add(name, new FunValue2(fun)); } public static void Register(string name, Func<Value, Value, Value, Value> fun) { Dict.Add(name, new FunValue3(fun)); } private static Value WriteLine(Value value) { Console.WriteLine(value.ToString()); return UnitValue.Singleton; } private static Value ReadInt(Value value) { string line = Console.ReadLine(); return new IntValue(Int32.Parse(line)); } private static Value Pow(Value aValue, Value bValue) { IntValue a = aValue as IntValue; IntValue b = bValue as IntValue; if (a == null || b == null) throw new RuntimeTypeError("int expected"); return new IntValue((int)Math.Pow(a.Value, b.Value)); } private static Value Fold(Value listValue, Value seedValue, Value funValue) { ListValue list = listValue as ListValue; if (list == null) throw new RuntimeTypeError("list expected"); FunValue fun = funValue as FunValue; if (fun == null) throw new RuntimeTypeError("fun expected"); return list.Elements.Aggregate(seedValue, fun.Apply); } static Prelude() { Dict = new Dictionary<string, Value>(); Register("writeLine", WriteLine); Register("readInt", ReadInt); Register("pow", Pow); Register("fold", Fold); } } }
using System; using System.Collections.Generic; using System.Linq; namespace School.Evaluator { public static class Prelude { private static Dictionary<string, Value> Dict = new Dictionary<string, Value>() { { "writeLine", new FunValue1(WriteLine) }, { "readInt", new FunValue1(ReadInt) }, { "pow", new FunValue2(Pow) }, { "fold", new FunValue3(Fold) } }; public static Value Lookup(string name) { if (Dict.ContainsKey(name)) return Dict[name]; else return UnitValue.Singleton; } private static Value WriteLine(Value value) { Console.WriteLine(value.ToString()); return UnitValue.Singleton; } private static Value ReadInt(Value value) { string line = Console.ReadLine(); return new IntValue(Int32.Parse(line)); } private static Value Pow(Value aValue, Value bValue) { IntValue a = aValue as IntValue; IntValue b = bValue as IntValue; if (a == null || b == null) throw new RuntimeTypeError("int expected"); return new IntValue((int)Math.Pow(a.Value, b.Value)); } private static Value Fold(Value listValue, Value seedValue, Value funValue) { ListValue list = listValue as ListValue; if (list == null) throw new RuntimeTypeError("list expected"); FunValue fun = funValue as FunValue; if (fun == null) throw new RuntimeTypeError("fun expected"); return list.Elements.Aggregate(seedValue, fun.Apply); } } }
apache-2.0
C#