content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// ***************************************************************************** // // © Component Factory Pty Ltd, 2006 - 2016. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.471.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Windows.Forms; namespace ExpandingHeaderGroupsStack { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
31.833333
81
0.542408
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.471
Source/Demos/Non-NuGet/Krypton Toolkit Examples/Expanding HeaderGroups (Stack)/Program.cs
958
C#
// // Encog(tm) Core v3.3 - .Net Version (unit test) // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System.IO; using Encog.Util.Normalize.Input; using Encog.Util.Normalize.Output; using Encog.Util.Normalize.Target; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Encog.Util.Normalize { [TestClass] public class TestNormCSV { public static readonly double[][] ARRAY_2D = { new[] {1.0, 2.0, 3.0, 4.0, 5.0}, new[] {6.0, 7.0, 8.0, 9.0, 10.0} }; public static TempDir TEMP_DIR = new TempDir(); public static FileInfo FILENAME1 = TEMP_DIR.CreateFile("norm1.csv"); public static FileInfo FILENAME2 = TEMP_DIR.CreateFile("norm2.csv"); private void Generate(string filename) { IInputField a; IInputField b; IInputField c; IInputField d; IInputField e; var norm = new DataNormalization(); norm.Report = new NullStatusReportable(); norm.AddInputField(a = new InputFieldArray2D(false, ARRAY_2D, 0)); norm.AddInputField(b = new InputFieldArray2D(false, ARRAY_2D, 1)); norm.AddInputField(c = new InputFieldArray2D(false, ARRAY_2D, 2)); norm.AddInputField(d = new InputFieldArray2D(false, ARRAY_2D, 3)); norm.AddInputField(e = new InputFieldArray2D(false, ARRAY_2D, 4)); norm.AddOutputField(new OutputFieldDirect(a)); norm.AddOutputField(new OutputFieldDirect(b)); norm.AddOutputField(new OutputFieldDirect(c)); norm.AddOutputField(new OutputFieldDirect(d)); norm.AddOutputField(new OutputFieldDirect(e)); norm.Storage = new NormalizationStorageCSV(filename.ToString()); norm.Process(); } public DataNormalization Create(string filename, double[][] outputArray) { IInputField a; IInputField b; IInputField c; IInputField d; IInputField e; var norm = new DataNormalization(); norm.Report = new NullStatusReportable(); norm.Storage = new NormalizationStorageCSV(filename.ToString()); norm.AddInputField(a = new InputFieldCSV(false, filename.ToString(), 0)); norm.AddInputField(b = new InputFieldCSV(false, filename.ToString(), 1)); norm.AddInputField(c = new InputFieldCSV(false, filename.ToString(), 2)); norm.AddInputField(d = new InputFieldCSV(false, filename.ToString(), 3)); norm.AddInputField(e = new InputFieldCSV(false, filename.ToString(), 4)); norm.AddOutputField(new OutputFieldRangeMapped(a, 0.1, 0.9)); norm.AddOutputField(new OutputFieldRangeMapped(b, 0.1, 0.9)); norm.AddOutputField(new OutputFieldRangeMapped(c, 0.1, 0.9)); norm.AddOutputField(new OutputFieldRangeMapped(d, 0.1, 0.9)); norm.AddOutputField(new OutputFieldRangeMapped(e, 0.1, 0.9)); norm.Storage = new NormalizationStorageArray2D(outputArray); return norm; } [TestMethod] public void TestGenerateAndLoad() { var outputArray = EngineArray.AllocateDouble2D(2, 5); Generate(FILENAME1.ToString()); DataNormalization norm = Create(FILENAME1.ToString(),outputArray); norm.Process(); Check(norm); } [TestMethod] public void TestGenerateAndLoadSerial() { double[][] outputArray = EngineArray.AllocateDouble2D(2, 5); Generate(FILENAME2.ToString()); DataNormalization norm = Create(FILENAME2.ToString(),outputArray); norm = (DataNormalization) SerializeRoundTrip.RoundTrip(norm); norm.Process(); Check(norm); } private void Check(DataNormalization norm) { IInputField a = norm.InputFields[0]; IInputField b = norm.InputFields[1]; Assert.AreEqual(1.0, a.Min, 0.1); Assert.AreEqual(6.0, a.Max, 0.1); Assert.AreEqual(2.0, b.Min, 0.1); Assert.AreEqual(7.0, b.Max, 0.1); double[][] outputArray = ((NormalizationStorageArray2D) norm.Storage).GetArray(); for (int i = 0; i < 5; i++) { Assert.AreEqual(0.1, outputArray[0][i], 0.1); Assert.AreEqual(0.9, outputArray[1][i], 0.1); } } } }
41.931818
94
0.587895
[ "BSD-3-Clause" ]
asad4237/encog-dotnet-core
encog-core-test/Util/Normalize/TestNormCSV.cs
5,535
C#
namespace SimpleErrorHandler { using System; using XmlWriter = System.Xml.XmlWriter; using XmlReader = System.Xml.XmlReader; /// <summary> /// Defines methods to convert an object to and from its XML representation. /// </summary> public interface IXmlExportable { /// <summary> /// Reads the object state from its XML representation. /// </summary> void FromXml(XmlReader r); /// <summary> /// Writes the XML representation of the object. /// </summary> void ToXml(XmlWriter w); } }
26.608696
81
0.576797
[ "MIT" ]
ahsteele/ahsteele-ysod
App/StackExchange.SimpleErrorHandler/SimpleErrorHandler/IXmlExportable.cs
612
C#
using System; namespace Erni.Mobile.Services.Logging { public interface ILoggingService { void TrackEvent<T>(string eventName, T message); void TrackEvent(string eventName, string message); void TrackEvent(string eventName); void Debug(string message); void Warning(string message); void Error(Exception exception); } }
19.35
58
0.664083
[ "MIT" ]
ERNI-Academy/starterkit-mobile-application
src/CrossPlatform/Xamarin/Erni.Mobile/Services/Logging/ILoggingService.cs
389
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.Scroll1 { public partial class Scroll1YamlTests { [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class BasicScroll1Tests : YamlTestsBase { [Test] public void BasicScroll1Test() { //do indices.create this.Do(()=> _client.IndicesCreate("test_scroll", null)); //do index _body = new { foo= "bar" }; this.Do(()=> _client.Index("test_scroll", "test", "42", _body)); //do indices.refresh this.Do(()=> _client.IndicesRefreshForAll()); //do search _body = new { query= new { match_all= new {} } }; this.Do(()=> _client.Search("test_scroll", _body, nv=>nv .Add("search_type", @"scan") .Add("scroll", @"1m") )); //set scroll_id = _response._scroll_id; var scroll_id = _response._scroll_id; //do scroll this.Do(()=> _client.ScrollGet((string)scroll_id)); //match _response.hits.total: this.IsMatch(_response.hits.total, 1); //match _response.hits.hits[0]._id: this.IsMatch(_response.hits.hits[0]._id, 42); } } } }
20.777778
68
0.643239
[ "MIT" ]
amitstefen/elasticsearch-net
src/Tests/Elasticsearch.Net.Integration.Yaml/scroll/10_basic.yaml.cs
1,309
C#
//////////////////////////////////////////////////////////////////////////////////////////// // This is Generated Code // You should not modify this code as it may be overwritten. Use Partial classes instead // Generated By Generative Objects //////////////////////////////////////////////////////////////////////////////////////////// using GenerativeObjects.Practices.LayerSupportClasses.Features.Security.Common; using GenerativeObjects.Practices.ORMSupportClasses; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Solid.Feature.Security.Common; namespace Solid.Features.Security { public interface ILocationAuthorizations : IEntityAuthorizations { } }
37.25
93
0.606711
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
walteralmeida/GOForSolidVisitedPlacesApplication
Solid/GeneratedCode/Features/Security/DataLayer/ILocationAuthorizations.cs
747
C#
#pragma checksum "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d4ce53cc0e0315b99d6d2b58424160f27e68401a" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(InfnetFV_Core.Pages.Projects.Pages_Projects_Detail), @"mvc.1.0.razor-page", @"/Pages/Projects/Detail.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.RazorPageAttribute(@"/Pages/Projects/Detail.cshtml", typeof(InfnetFV_Core.Pages.Projects.Pages_Projects_Detail), @"{id:int}")] namespace InfnetFV_Core.Pages.Projects { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\_ViewImports.cshtml" using InfnetFV_Core; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute("RouteTemplate", "{id:int}")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d4ce53cc0e0315b99d6d2b58424160f27e68401a", @"/Pages/Projects/Detail.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3242a00c4945873b1ed9a28a405569a3e2469a66", @"/Pages/_ViewImports.cshtml")] public class Pages_Projects_Detail : global::Microsoft.AspNetCore.Mvc.RazorPages.Page { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("submit"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-default"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page-handler", "Back", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page-handler", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page-handler", "Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "Search", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Filter", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "get", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./Solution/Detail", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("style", new global::Microsoft.AspNetCore.Html.HtmlString("float: right"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page-handler", "CreateSolution", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 3 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" ViewData["Title"] = "Detail"; Layout = "~/Pages/Shared/_Layout.cshtml"; #line default #line hidden BeginContext(156, 157, true); WriteLiteral("\r\n<h1>Project</h1>\r\n <div>\r\n <div class=\"panel panel-primary\">\r\n <div class=\"panel-heading\">\r\n <span class=\"panel-title\">"); EndContext(); BeginContext(314, 18, false); #line 12 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" Write(Model.Project.Name); #line default #line hidden EndContext(); BeginContext(332, 74, true); WriteLiteral("</span>\r\n <div class=\"headerButtons\">\r\n "); EndContext(); BeginContext(406, 587, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a8447", async() => { BeginContext(426, 26, true); WriteLiteral("\r\n "); EndContext(); BeginContext(452, 152, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a8854", async() => { BeginContext(522, 73, true); WriteLiteral("\r\n <span>Back</span>\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.PageHandler = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(604, 26, true); WriteLiteral("\r\n "); EndContext(); BeginContext(630, 152, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a10609", async() => { BeginContext(700, 73, true); WriteLiteral("\r\n <span>Edit</span>\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.PageHandler = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(782, 26, true); WriteLiteral("\r\n "); EndContext(); BeginContext(808, 156, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a12365", async() => { BeginContext(880, 75, true); WriteLiteral("\r\n <span>Delete</span>\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.PageHandler = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(964, 22, true); WriteLiteral("\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_5.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(993, 264, true); WriteLiteral(@" </div> </div> <div class=""panel-body""> <div class=""clearfix""> <div class=""objectData""> <div class=""smallStateBox active""> <span>"); EndContext(); BeginContext(1258, 19, false); #line 31 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" Write(Model.Project.State); #line default #line hidden EndContext(); BeginContext(1277, 316, true); WriteLiteral(@"</span> </div> </div> <div class=""objectData""> <div class=""title""> <span>ID</span> </div> <div class=""value""> <span>"); EndContext(); BeginContext(1594, 16, false); #line 39 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" Write(Model.Project.Id); #line default #line hidden EndContext(); BeginContext(1610, 325, true); WriteLiteral(@"</span> </div> </div> <div class=""objectData""> <div class=""title""> <span>Description</span> </div> <div class=""value""> <span>"); EndContext(); BeginContext(1936, 25, false); #line 47 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" Write(Model.Project.Description); #line default #line hidden EndContext(); BeginContext(1961, 322, true); WriteLiteral(@"</span> </div> </div> <div class=""objectData""> <div class=""title""> <span>Deadline</span> </div> <div class=""value""> <span>"); EndContext(); BeginContext(2284, 25, false); #line 55 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" Write(Model.Project.DateTimeEnd); #line default #line hidden EndContext(); BeginContext(2309, 331, true); WriteLiteral(@"</span> </div> </div> </div> </div> </div> <div class=""posRel panel panel-info""> <div class=""panel-heading""> <span>Project solution</span> <div class=""headerButtons""> "); EndContext(); BeginContext(2640, 500, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a18458", async() => { BeginContext(2659, 26, true); WriteLiteral("\r\n "); EndContext(); BeginContext(2685, 104, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("select", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a18868", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper.Name = (string)__tagHelperAttribute_6.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); #line 67 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper.Items = Html.GetEnumSelectList<InfnetFV_Core.Models.Enum.Solution>(); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-items", __Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper.Items, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2789, 26, true); WriteLiteral("\r\n "); EndContext(); BeginContext(2815, 81, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a20715", async() => { BeginContext(2881, 6, true); WriteLiteral("Filter"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.Action = (string)__tagHelperAttribute_7.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2896, 237, true); WriteLiteral("\r\n <!--\r\n <button type=\"submit\" class=\"btn btn-default\">\r\n <span>Filter</span>\r\n </button>\r\n -->\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_8.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(3140, 635, true); WriteLiteral(@" </div> </div> <div class=""panel-body""> <table class=""table table-striped table-bordered table-hover""> <thead> <tr> <th> <span>Name</span> </th> <th> <span>State</span> </th> <th width=""10%""> </th> </tr> </thead> <tbody> "); EndContext(); #line 92 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" foreach (var solution in Model.SolutionsFilter) { if (solution.IdProject == Model.Project.Id) { #line default #line hidden BeginContext(3980, 78, true); WriteLiteral(" <tr>\r\n <td>"); EndContext(); BeginContext(4059, 13, false); #line 97 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" Write(solution.Name); #line default #line hidden EndContext(); BeginContext(4072, 47, true); WriteLiteral("</td>\r\n <td>"); EndContext(); BeginContext(4120, 14, false); #line 98 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" Write(solution.State); #line default #line hidden EndContext(); BeginContext(4134, 89, true); WriteLiteral("</td>\r\n <td>\r\n "); EndContext(); BeginContext(4223, 70, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a25927", async() => { BeginContext(4283, 6, true); WriteLiteral("Detail"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_9.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #line 100 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" WriteLiteral(solution.Id); #line default #line hidden __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(4293, 84, true); WriteLiteral("\r\n </td>\r\n </tr>\r\n"); EndContext(); #line 103 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" } } #line default #line hidden BeginContext(4435, 94, true); WriteLiteral(" </tbody>\r\n </table>\r\n </div>\r\n </div>\r\n\r\n"); EndContext(); #line 110 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" bool butCreateSolDisable = false; if (Model.Project.State == Models.Enum.Project.Completed) { butCreateSolDisable = true; } #line default #line hidden BeginContext(4745, 10, true); WriteLiteral("\r\n "); EndContext(); BeginContext(4755, 196, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a29263", async() => { BeginContext(4775, 14, true); WriteLiteral("\r\n "); EndContext(); BeginContext(4789, 145, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4ce53cc0e0315b99d6d2b58424160f27e68401a29661", async() => { BeginContext(4898, 27, true); WriteLiteral("Create new project solution"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "disabled", 1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line 119 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" AddHtmlAttributeValue("", 4821, butCreateSolDisable, 4821, 20, false); #line default #line hidden EndAddHtmlAttributeValues(__tagHelperExecutionContext); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10); __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.PageHandler = (string)__tagHelperAttribute_11.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_11); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(4934, 10, true); WriteLiteral("\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_5.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(4951, 16, true); WriteLiteral("\r\n </div>\r\n\r\n"); EndContext(); DefineSection("Scripts", async() => { BeginContext(4985, 2, true); WriteLiteral("\r\n"); EndContext(); #line 124 "C:\Users\Filip Vrba\Documents\GitHub\InfnetFV-Core\InfnetFV-Core\Pages\Projects\Detail.cshtml" await Html.RenderPartialAsync("_ValidationScriptsPartial"); #line default #line hidden } ); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<InfnetFV_Core.Pages.Projects.DetailModel> Html { get; private set; } public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<InfnetFV_Core.Pages.Projects.DetailModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<InfnetFV_Core.Pages.Projects.DetailModel>)PageContext?.ViewData; public InfnetFV_Core.Pages.Projects.DetailModel Model => ViewData.Model; } } #pragma warning restore 1591
65.249524
353
0.653433
[ "MIT" ]
filipvrba/InfnetFV-Core
InfnetFV-Core/obj/Debug/netcoreapp2.2/Razor/Pages/Projects/Detail.g.cshtml.cs
34,256
C#
using System; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Threading; using SimpleRemote.Controls.Dragablz.Core; using SimpleRemote.Controls.Dragablz.Dockablz; using SimpleRemote.Controls.Dragablz.Referenceless; namespace SimpleRemote.Controls.Dragablz { /// <summary> /// It is not necessary to use a <see cref="DragablzWindow"/> to gain tab dragging features. /// What this Window does is allow a quick way to remove the Window border, and support transparency whilst /// dragging. /// </summary> [TemplatePart(Name = WindowSurfaceGridPartName, Type = typeof(Grid))] [TemplatePart(Name = WindowRestoreThumbPartName, Type = typeof(Thumb))] [TemplatePart(Name = WindowResizeThumbPartName, Type = typeof(Thumb))] public class DragablzWindow : Window { public const string WindowSurfaceGridPartName = "PART_WindowSurface"; public const string WindowRestoreThumbPartName = "PART_WindowRestoreThumb"; public const string WindowResizeThumbPartName = "PART_WindowResizeThumb"; private readonly SerialDisposable _templateSubscription = new SerialDisposable(); public static RoutedCommand CloseWindowCommand = new RoutedCommand(); public static RoutedCommand RestoreWindowCommand = new RoutedCommand(); public static RoutedCommand MaximizeWindowCommand = new RoutedCommand(); public static RoutedCommand MinimizeWindowCommand = new RoutedCommand(); private const int ResizeMargin = 4; private Size _sizeWhenResizeBegan; private Point _screenMousePointWhenResizeBegan; private Point _windowLocationPointWhenResizeBegan; private SizeGrip _resizeType; private static SizeGrip[] _leftMode = new[] { SizeGrip.TopLeft, SizeGrip.Left, SizeGrip.BottomLeft }; private static SizeGrip[] _rightMode = new[] { SizeGrip.TopRight, SizeGrip.Right, SizeGrip.BottomRight }; private static SizeGrip[] _topMode = new[] { SizeGrip.TopLeft, SizeGrip.Top, SizeGrip.TopRight }; private static SizeGrip[] _bottomMode = new[] { SizeGrip.BottomLeft, SizeGrip.Bottom, SizeGrip.BottomRight }; private static double _xScale = 1; private static double _yScale = 1; private static bool _dpiInitialized = false; static DragablzWindow() { DefaultStyleKeyProperty.OverrideMetadata(typeof(DragablzWindow), new FrameworkPropertyMetadata(typeof(DragablzWindow))); } public DragablzWindow() { AddHandler(DragablzItem.DragStarted, new DragablzDragStartedEventHandler(ItemDragStarted), true); AddHandler(DragablzItem.DragCompleted, new DragablzDragCompletedEventHandler(ItemDragCompleted), true); CommandBindings.Add(new CommandBinding(CloseWindowCommand, CloseWindowExecuted)); CommandBindings.Add(new CommandBinding(MaximizeWindowCommand, MaximizeWindowExecuted)); CommandBindings.Add(new CommandBinding(MinimizeWindowCommand, MinimizeWindowExecuted)); CommandBindings.Add(new CommandBinding(RestoreWindowCommand, RestoreWindowExecuted)); } private static readonly DependencyPropertyKey IsWindowBeingDraggedByTabPropertyKey = DependencyProperty.RegisterReadOnly( "IsBeingDraggedByTab", typeof (bool), typeof (DragablzWindow), new PropertyMetadata(default(bool))); public static readonly DependencyProperty IsBeingDraggedByTabProperty = IsWindowBeingDraggedByTabPropertyKey.DependencyProperty; public bool IsBeingDraggedByTab { get { return (bool) GetValue(IsBeingDraggedByTabProperty); } private set { SetValue(IsWindowBeingDraggedByTabPropertyKey, value); } } private void ItemDragCompleted(object sender, DragablzDragCompletedEventArgs e) { IsBeingDraggedByTab = false; } private void ItemDragStarted(object sender, DragablzDragStartedEventArgs e) { var sourceOfDragItemsControl = ItemsControl.ItemsControlFromItemContainer(e.DragablzItem) as DragablzItemsControl; if (sourceOfDragItemsControl == null) return; var sourceTab = TabablzControl.GetOwnerOfHeaderItems(sourceOfDragItemsControl); if (sourceTab == null) return; if (sourceOfDragItemsControl.Items.Count != 1 || (sourceTab.InterTabController != null && !sourceTab.InterTabController.MoveWindowWithSolitaryTabs) || Layout.IsContainedWithinBranch(sourceOfDragItemsControl)) return; IsBeingDraggedByTab = true; } public override void OnApplyTemplate() { var windowSurfaceGrid = GetTemplateChild(WindowSurfaceGridPartName) as Grid; var windowRestoreThumb = GetTemplateChild(WindowRestoreThumbPartName) as Thumb; var windowResizeThumb = GetTemplateChild(WindowResizeThumbPartName) as Thumb; _templateSubscription.Disposable = Disposable.Create(() => { if (windowSurfaceGrid != null) { windowSurfaceGrid.MouseLeftButtonDown -= WindowSurfaceGridOnMouseLeftButtonDown; } if (windowRestoreThumb != null) { windowRestoreThumb.DragDelta -= WindowMoveThumbOnDragDelta; windowRestoreThumb.MouseDoubleClick -= WindowRestoreThumbOnMouseDoubleClick; } if (windowResizeThumb == null) return; windowResizeThumb.MouseMove -= WindowResizeThumbOnMouseMove; windowResizeThumb.DragStarted -= WindowResizeThumbOnDragStarted; windowResizeThumb.DragDelta -= WindowResizeThumbOnDragDelta; windowResizeThumb.DragCompleted -= WindowResizeThumbOnDragCompleted; }); base.OnApplyTemplate(); if (windowSurfaceGrid != null) { windowSurfaceGrid.MouseLeftButtonDown += WindowSurfaceGridOnMouseLeftButtonDown; } if (windowRestoreThumb != null) { windowRestoreThumb.DragDelta += WindowMoveThumbOnDragDelta; windowRestoreThumb.MouseDoubleClick += WindowRestoreThumbOnMouseDoubleClick; } if (windowResizeThumb == null) return; windowResizeThumb.MouseMove += WindowResizeThumbOnMouseMove; windowResizeThumb.DragStarted += WindowResizeThumbOnDragStarted; windowResizeThumb.DragDelta += WindowResizeThumbOnDragDelta; windowResizeThumb.DragCompleted += WindowResizeThumbOnDragCompleted; } protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { var resizeThumb = GetTemplateChild(WindowResizeThumbPartName) as Thumb; if (resizeThumb != null) { var outerRectangleGeometry = new RectangleGeometry(new Rect(sizeInfo.NewSize)); var innerRectangleGeometry = new RectangleGeometry(new Rect(ResizeMargin, ResizeMargin, sizeInfo.NewSize.Width - ResizeMargin * 2, sizeInfo.NewSize.Height - ResizeMargin*2)); resizeThumb.Clip = new CombinedGeometry(GeometryCombineMode.Exclude, outerRectangleGeometry, innerRectangleGeometry); } base.OnRenderSizeChanged(sizeInfo); } protected IntPtr CriticalHandle { get { var value = typeof (Window).GetProperty("CriticalHandle", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(this, new object[0]); return (IntPtr) value; } } private void WindowSurfaceGridOnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs) { if (mouseButtonEventArgs.ChangedButton != MouseButton.Left) return; if (mouseButtonEventArgs.ClickCount == 1) DragMove(); if (mouseButtonEventArgs.ClickCount == 2) WindowState = WindowState.Maximized; } private static void WindowResizeThumbOnMouseMove(object sender, MouseEventArgs mouseEventArgs) { var thumb = (Thumb)sender; var mousePositionInThumb = Mouse.GetPosition(thumb); thumb.Cursor = SelectCursor(SelectSizingMode(mousePositionInThumb, thumb.RenderSize)); } private void WindowRestoreThumbOnMouseDoubleClick(object sender, MouseButtonEventArgs mouseButtonEventArgs) { WindowState = WindowState.Normal; } private void WindowResizeThumbOnDragCompleted(object sender, DragCompletedEventArgs dragCompletedEventArgs) { Cursor = Cursors.Arrow; } private void WindowResizeThumbOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs) { var mousePositionInWindow = Mouse.GetPosition(this); var currentScreenMousePoint = PointToScreen(mousePositionInWindow); var width = _sizeWhenResizeBegan.Width; var height = _sizeWhenResizeBegan.Height; var left = _windowLocationPointWhenResizeBegan.X; var top = _windowLocationPointWhenResizeBegan.Y; if (_leftMode.Contains(_resizeType)) { var diff = currentScreenMousePoint.X - _screenMousePointWhenResizeBegan.X; diff /= _xScale; var suggestedWidth = width + -diff; left += diff; width = suggestedWidth; } if (_rightMode.Contains(_resizeType)) { var diff = currentScreenMousePoint.X - _screenMousePointWhenResizeBegan.X; diff /= _xScale; width += diff; } if (_topMode.Contains(_resizeType)) { var diff = currentScreenMousePoint.Y - _screenMousePointWhenResizeBegan.Y; diff /= _yScale; height += -diff; top += diff; } if (_bottomMode.Contains(_resizeType)) { var diff = currentScreenMousePoint.Y - _screenMousePointWhenResizeBegan.Y; diff /= _yScale; height += diff; } width = Math.Max(MinWidth, width); height = Math.Max(MinHeight, height); //TODO must try harder. left = Math.Min(left, _windowLocationPointWhenResizeBegan.X + _sizeWhenResizeBegan.Width - ResizeMargin*4); //TODO must try harder. top = Math.Min(top, _windowLocationPointWhenResizeBegan.Y + _sizeWhenResizeBegan.Height - ResizeMargin * 4); SetCurrentValue(WidthProperty, width); SetCurrentValue(HeightProperty, height); SetCurrentValue(LeftProperty, left); SetCurrentValue(TopProperty, top); } private void GetDPI() { if (_dpiInitialized) { return; } Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice; _xScale = m.M11; _yScale = m.M22; _dpiInitialized = true; } private void WindowResizeThumbOnDragStarted(object sender, DragStartedEventArgs dragStartedEventArgs) { _sizeWhenResizeBegan = new Size(ActualWidth, ActualHeight); _windowLocationPointWhenResizeBegan = new Point(Left, Top); var mousePositionInWindow = Mouse.GetPosition(this); _screenMousePointWhenResizeBegan = PointToScreen(mousePositionInWindow); var thumb = (Thumb)sender; var mousePositionInThumb = Mouse.GetPosition(thumb); _resizeType = SelectSizingMode(mousePositionInThumb, thumb.RenderSize); GetDPI(); } private static SizeGrip SelectSizingMode(Point mousePositionInThumb, Size thumbSize) { if (mousePositionInThumb.X <= ResizeMargin) { if (mousePositionInThumb.Y <= ResizeMargin) return SizeGrip.TopLeft; if (mousePositionInThumb.Y >= thumbSize.Height - ResizeMargin) return SizeGrip.BottomLeft; return SizeGrip.Left; } if (mousePositionInThumb.X >= thumbSize.Width - ResizeMargin) { if (mousePositionInThumb.Y <= ResizeMargin) return SizeGrip.TopRight; if (mousePositionInThumb.Y >= thumbSize.Height - ResizeMargin) return SizeGrip.BottomRight; return SizeGrip.Right; } if (mousePositionInThumb.Y <= ResizeMargin) return SizeGrip.Top; return SizeGrip.Bottom; } private static Cursor SelectCursor(SizeGrip sizeGrip) { switch (sizeGrip) { case SizeGrip.Left: return Cursors.SizeWE; case SizeGrip.TopLeft: return Cursors.SizeNWSE; case SizeGrip.Top: return Cursors.SizeNS; case SizeGrip.TopRight: return Cursors.SizeNESW; case SizeGrip.Right: return Cursors.SizeWE; case SizeGrip.BottomRight: return Cursors.SizeNWSE; case SizeGrip.Bottom: return Cursors.SizeNS; case SizeGrip.BottomLeft: return Cursors.SizeNESW; default: return Cursors.Arrow; } } private void WindowMoveThumbOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs) { if (WindowState != WindowState.Maximized || (!(Math.Abs(dragDeltaEventArgs.HorizontalChange) > 2) && !(Math.Abs(dragDeltaEventArgs.VerticalChange) > 2))) return; var cursorPos = Core.Native.GetRawCursorPos(); WindowState = WindowState.Normal; GetDPI(); Top = cursorPos.Y / _yScale - 2; Left = cursorPos.X / _xScale - RestoreBounds.Width / 2; var lParam = (int)(uint)cursorPos.X | (cursorPos.Y << 16); Core.Native.SendMessage(CriticalHandle, WindowMessage.WM_LBUTTONUP, (IntPtr)HitTest.HT_CAPTION, (IntPtr)lParam); Core.Native.SendMessage(CriticalHandle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_MOUSEMOVE, IntPtr.Zero); } private void RestoreWindowExecuted(object sender, ExecutedRoutedEventArgs e) { Core.Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_RESTORE, IntPtr.Zero); } private void MinimizeWindowExecuted(object sender, ExecutedRoutedEventArgs e) { Core.Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_MINIMIZE, IntPtr.Zero); } private void MaximizeWindowExecuted(object sender, ExecutedRoutedEventArgs e) { Core.Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_MAXIMIZE, IntPtr.Zero); } private void CloseWindowExecuted(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) { Core.Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } } }
43.703504
165
0.633958
[ "Apache-2.0" ]
GeekCatPYG/SimpleRemote
SimoleRemote/Controls/Dragablz/DragablzWindow.cs
16,216
C#
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("NonTrailingNamedArguments")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NonTrailingNamedArguments")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("22dd63bb-1b9c-4ef0-9538-2faa70f4f610")] // 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")]
38.305556
84
0.749094
[ "MIT" ]
PacktPublishing/Mastering-C-7.2-and-.NET-Core-2.1-Application-Development
Chapter01/03 - NonTrailingNamedArguments/NonTrailingNamedArguments/Properties/AssemblyInfo.cs
1,382
C#
using Newtonsoft.Json; /// <summary> /// Scribble.rs ♯ data namespace /// </summary> namespace ScribblersSharp.Data { /// <summary> /// A class that describes a received "next-turn" game message /// </summary> [JsonObject(MemberSerialization.OptIn)] internal class NextTurnReceiveGameMessageData : GameMessageData<NextTurnData>, IReceiveGameMessageData { // ... } }
23.764706
106
0.673267
[ "MIT" ]
scribble-rs/ScribbleRSSharp
ScribblersSharp/Data/WebSocket/NextTurnReceiveGameMessageData.cs
408
C#
using BlazorHero.CleanArchitecture.Client.Extensions; using BlazorHero.CleanArchitecture.Client.Infrastructure.Settings; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.JSInterop; using MudBlazor; using System; using System.Net.Http.Headers; using System.Threading.Tasks; namespace BlazorHero.CleanArchitecture.Client.Shared { public partial class MainLayout : IDisposable { [Inject] IJSRuntime _jsRuntime { get; set; } private string CurrentUserId { get; set; } private string FirstName { get; set; } private string SecondName { get; set; } private string Email { get; set; } private char FirstLetterOfName { get; set; } private async Task LoadDataAsync() { var state = await _stateProvider.GetAuthenticationStateAsync(); var user = state.User; if (user == null) return; if (user.Identity.IsAuthenticated) { CurrentUserId = user.GetUserId(); this.FirstName = user.GetFirstName(); if (this.FirstName.Length > 0) { FirstLetterOfName = FirstName[0]; } } } MudTheme currentTheme; private bool _drawerOpen = true; protected override async Task OnInitializedAsync() { _interceptor.RegisterEvent(); currentTheme = await _preferenceManager.GetCurrentThemeAsync(); hubConnection = hubConnection.TryInitialize(_navigationManager); await hubConnection.StartAsync(); hubConnection.On<string, string, string>("ReceiveChatNotification", (message, receiverUserId, senderUserId) => { if (CurrentUserId == receiverUserId) { _jsRuntime.InvokeAsync<string>("PlayAudio", "notification"); _snackBar.Add(message, Severity.Info, config => { config.VisibleStateDuration = 10000; config.HideTransitionDuration = 500; config.ShowTransitionDuration = 500; config.Action = "Chat?"; config.ActionColor = Color.Primary; config.Onclick = snackbar => { _navigationManager.NavigateTo($"chat/{senderUserId}"); return Task.CompletedTask; }; }); } }); hubConnection.On("RegenerateTokens", async () => { try { var token = await _authenticationManager.TryForceRefreshToken(); if (!string.IsNullOrEmpty(token)) { _snackBar.Add("Refreshed Token.", Severity.Success); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } } catch (Exception ex) { Console.WriteLine(ex.Message); _snackBar.Add("You are Logged Out.", Severity.Error); await _authenticationManager.Logout(); _navigationManager.NavigateTo("/"); } }); } void Logout() { string logoutConfirmationText = localizer["Logout Confirmation"]; string logoutText = localizer["Logout"]; var parameters = new DialogParameters(); parameters.Add("ContentText", logoutConfirmationText); parameters.Add("ButtonText", logoutText); parameters.Add("Color", Color.Error); var options = new DialogOptions() { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true }; _dialogService.Show<Dialogs.Logout>("Logout", parameters, options); } void DrawerToggle() { _drawerOpen = !_drawerOpen; } async Task DarkMode() { bool isDarkMode = await _preferenceManager.ToggleDarkModeAsync(); if (isDarkMode) { currentTheme = BlazorHeroTheme.DefaultTheme; } else { currentTheme = BlazorHeroTheme.DarkTheme; } } public void Dispose() { _interceptor.DisposeEvent(); //_ = hubConnection.DisposeAsync(); } private HubConnection hubConnection; public bool IsConnected => hubConnection.State == HubConnectionState.Connected; } }
37.71875
122
0.537283
[ "MIT" ]
jtakec/blazorhero
BlazorHero.CleanArchitecture/Client/Shared/MainLayout.razor.cs
4,830
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.Core.Outputs { [OutputType] public sealed class CustomProviderValidation { /// <summary> /// The endpoint where the validation specification is located. /// </summary> public readonly string Specification; [OutputConstructor] private CustomProviderValidation(string specification) { Specification = specification; } } }
26.892857
88
0.677291
[ "ECL-2.0", "Apache-2.0" ]
AdminTurnedDevOps/pulumi-azure
sdk/dotnet/Core/Outputs/CustomProviderValidation.cs
753
C#
using UnityEngine.UIElements; using UnityEditor; namespace RFG.SceneGraph { public class InspectorView : VisualElement { public new class UxmlFactory : UxmlFactory<InspectorView, VisualElement.UxmlTraits> { } private Editor editor; public InspectorView() { } internal void UpdateSelection(SceneGroup SceneGroup) { Clear(); UnityEngine.Object.DestroyImmediate(editor); editor = Editor.CreateEditor(SceneGroup.scene); IMGUIContainer container = new IMGUIContainer(() => { if (editor && editor.target) { editor.OnInspectorGUI(); } if (!SceneGroup.title.Equals(SceneGroup.scene.scenePath)) { SceneGroup.title = System.IO.Path.GetFileNameWithoutExtension(SceneGroup.scene.scenePath); } }); Add(container); } internal void UpdateTransitionSelection(SceneTransitionNode SceneTransitionNode) { Clear(); UnityEngine.Object.DestroyImmediate(editor); editor = Editor.CreateEditor(SceneTransitionNode.sceneTransition); IMGUIContainer container = new IMGUIContainer(() => { if (editor && editor.target) { editor.OnInspectorGUI(); } }); Add(container); } } }
27.183673
101
0.620871
[ "Apache-2.0" ]
retro-fall-games/PermitDenied
Assets/RFG/SceneGraph/Editor/Elements/InspectorView.cs
1,332
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformationGetArgs : Pulumi.ResourceArgs { /// <summary> /// The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> [Input("priority", required: true)] public Input<int> Priority { get; set; } = null!; /// <summary> /// The transformation to apply, please refer to the Text Transformation [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public WebAclRuleStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformationGetArgs() { } } }
42.71875
224
0.71763
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformationGetArgs.cs
1,367
C#
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. namespace System.Activities.Statements { using System; using System.Activities; using System.Activities.Internals; using System.Activities.Runtime.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq.Expressions; using System.Windows.Markup; [ContentProperty("Cases")] public sealed class Switch<T> : NativeActivity { private IDictionary<T, Activity> cases; public Switch() { } public Switch(Expression<Func<ActivityContext, T>> expression) : this() { if (expression == null) { throw FxTrace.Exception.ArgumentNull(nameof(expression)); } this.Expression = new InArgument<T>(expression); } public Switch(Activity<T> expression) : this() { if (expression == null) { throw FxTrace.Exception.ArgumentNull(nameof(expression)); } this.Expression = new InArgument<T>(expression); } public Switch(InArgument<T> expression) : this() { this.Expression = expression ?? throw FxTrace.Exception.ArgumentNull(nameof(expression)); } [RequiredArgument] [DefaultValue(null)] public InArgument<T> Expression { get; set; } public IDictionary<T, Activity> Cases { get { if (this.cases == null) { this.cases = new NullableKeyDictionary<T, Activity>(); } return this.cases; } } [DefaultValue(null)] public Activity Default { get; set; } protected override void OnCreateDynamicUpdateMap(DynamicUpdate.NativeActivityUpdateMapMetadata metadata, Activity originalActivity) => metadata.AllowUpdateInsideThisActivity(); protected override void CacheMetadata(NativeActivityMetadata metadata) { var expressionArgument = new RuntimeArgument("Expression", typeof(T), ArgumentDirection.In, true); metadata.Bind(Expression, expressionArgument); metadata.SetArgumentsCollection(new Collection<RuntimeArgument> { expressionArgument }); var children = new Collection<Activity>(); foreach (var child in Cases.Values) { children.Add(child); } if (Default != null) { children.Add(Default); } metadata.SetChildrenCollection(children); } protected override void Execute(NativeActivityContext context) { var result = Expression.Get(context); if (!Cases.TryGetValue(result, out var selection)) { if (this.Default != null) { selection = this.Default; } else { if (TD.SwitchCaseNotFoundIsEnabled()) { TD.SwitchCaseNotFound(this.DisplayName); } } } if (selection != null) { context.ScheduleActivity(selection); } } } }
27.636364
143
0.533169
[ "MIT" ]
wforney/corewf
src/System.Activities/Statements/Switch.cs
3,648
C#
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved namespace Microsoft.Samples.HyperV.FibreChannel { using System; using System.Management; using System.Globalization; using Microsoft.Samples.HyperV.Common; static class ModifySanNameSample { /// <summary> /// Renames a Virtual SAN. /// </summary> /// <param name="poolId">The current name of the Virtual SAN.</param> /// <param name="newPoolId">The new name of the Virtual SAN.</param> private static void ModifySanSettings( string poolId, string newPoolId ) { Console.WriteLine("Modifying a Virtual SAN's settings:"); Console.WriteLine("\tSAN Name: {0} (change to {1})", poolId, newPoolId); ManagementScope scope = FibreChannelUtilities.GetFcScope(); using (ManagementObject rpConfigurationService = FibreChannelUtilities.GetResourcePoolConfigurationService(scope)) { string resourcePoolSettingData = FibreChannelUtilities.GetSettingsForPool(scope, newPoolId, null); string poolPath = FibreChannelUtilities.GetResourcePoolPath(scope, poolId); using (ManagementBaseObject inParams = rpConfigurationService.GetMethodParameters("ModifyPoolSettings")) { inParams["ChildPool"] = poolPath; inParams["PoolSettings"] = resourcePoolSettingData; using (ManagementBaseObject outParams = rpConfigurationService.InvokeMethod( "ModifyPoolSettings", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope, true, true); } } } Console.WriteLine("Successfully renamed Virtual SAN: from {0} to {1}", poolId, newPoolId); } /// <summary> /// Entry point for the ModifySanName sample. /// </summary> /// <param name="args">The command line arguments.</param> internal static void ExecuteSample( string[] args) { if (args.Length != 2 || (args.Length > 0 && args[0] == "/?")) { Console.WriteLine("Usage: ModifySanName <SanName> <NewSanName>"); return; } try { ModifySanSettings(args[0], args[1]); } catch (Exception ex) { Console.WriteLine("Failed to modify san name. Error message details:\n"); Console.WriteLine(ex.Message); } } } }
38.802326
103
0.508241
[ "MIT" ]
9578577/Windows-classic-samples
Samples/Hyper-V/FibreChannel/cs/ModifySanName.cs
3,254
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace XenAdmin.Controls { public partial class SectionHeaderLabel : UserControl { /// <summary> /// Vertical Alignment enumeration. This doesn;t appear in .NET until 4.0 /// </summary> public enum VerticalAlignment { /// <summary> /// Align to the Top of the control /// </summary> Top, /// <summary> /// Align to the vertical center of the control /// </summary> Middle, /// <summary> /// Align to the Bottom of the control /// </summary> Bottom } /// <summary> /// Horizontal alignment of the control text /// </summary> [Localizable(true)] public HorizontalAlignment LabelHorizontalAlignment { get; set; } /// <summary> /// Text to display /// </summary> [Localizable(true)] public string LabelText { get; set; } /// <summary> /// Padding around the text /// </summary> [Localizable(true)] public Padding LabelPadding { get; set; } /// <summary> /// Vertical alignment of the header line /// </summary> public VerticalAlignment LineLocation { get; set; } /// <summary> /// Color of the header line /// </summary> public Color LineColor { get; set; } /// <summary> /// Padding around the header line /// </summary> [Localizable(true)] public Padding LinePadding { get; set; } /// <summary> /// Use mnemonic for setting focus on a control /// </summary> [Localizable(true)] public bool UseMnemonic { get; set; } /// <summary> /// The control on which to set focus when mnemonic key is pressed /// </summary> [Localizable(true)] public Control FocusControl { get; set; } /// <summary> /// Public constructor /// </summary> public SectionHeaderLabel() { InitializeComponent(); this.LineColor = Color.Black; SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true); } /// <summary> /// Custom OnPoint method /// </summary> /// <param name="e">PaintEventArgs object</param> protected override void OnPaint(PaintEventArgs e) { DrawLine(e.Graphics); DrawLabel(e.Graphics); Size baseHeight = new Size(0, this.Padding.Vertical + (this.LinePadding.Vertical + 1) + this.LabelPadding.Vertical + (int)e.Graphics.MeasureString(this.LabelText, this.Font).Height); this.MinimumSize = baseHeight; base.OnPaint(e); } /// <summary> /// Handle mnemonic events to set focus to the FocusControl /// </summary> /// <param name="charCode"></param> /// <returns></returns> protected override bool ProcessMnemonic(char charCode) { if (this.UseMnemonic && Control.IsMnemonic(charCode, this.LabelText) && (Control.ModifierKeys == Keys.Alt) && null != this.FocusControl) { this.FocusControl.Focus(); return true; } else { return false; } } /// <summary> /// Draws the text label of the control /// </summary> /// <param name="graphics">Current graphics drawing object</param> private void DrawLabel(Graphics graphics) { StringFormat sf = new StringFormat(); if (this.UseMnemonic) { sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show; if (!this.ShowKeyboardCues) sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Hide; } else sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None; sf.FormatFlags = StringFormatFlags.NoWrap; //Make sure our brush is disposed using (SolidBrush brush = new SolidBrush(this.ForeColor)) { PointF pointF = GetTextPointF(graphics); //Draw the actual text graphics.DrawString(this.LabelText, this.Font, brush, pointF, sf); } } /// <summary> /// Draw the header line /// </summary> /// <param name="graphics">Current graphics drawing object</param> private void DrawLine(Graphics graphics) { //These are used a lot in here... SizeF textSizeF = graphics.MeasureString(this.LabelText, this.Font); float lineY = GetLineVerticalLocation(); //Make sure our pen is disposed using (Pen pen = new Pen(this.LineColor)) { if (LineLocation == VerticalAlignment.Middle) { switch (LabelHorizontalAlignment) { case HorizontalAlignment.Left: { //Draw a line from the right end of the text to the right end of the control DrawLeftLine(graphics, textSizeF, lineY, pen); break; } case HorizontalAlignment.Right: { //Draw a line from the left end of the control to the left end of the text DrawRightLine(graphics, textSizeF, lineY, pen); break; } case HorizontalAlignment.Center: { //Draw a line from the left of the control, to the left of the label, // then from the right of the label to the right of the control DrawLeftLine(graphics, textSizeF, lineY, pen); DrawRightLine(graphics, textSizeF, lineY, pen); break; } } } else { float startX = (float)this.Padding.Left + //Control left padding (float)LinePadding.Left; //Line left padding float endX = (float)this.Width - //Control width (float)this.Padding.Right - //Control right padding (float)this.LinePadding.Right; //Line right padding graphics.DrawLine(pen, startX, lineY, endX, lineY); } } } private void DrawRightLine(Graphics graphics, SizeF textSizeF, float lineY, Pen pen) { float startX = (float)this.Padding.Left + //Control left padding (float)LinePadding.Left; //Line left padding float endX = (float)this.Width - //Control width (float)this.Padding.Right - //Control right padding (float)this.LinePadding.Right - //Line right padding (float)this.LabelPadding.Horizontal - //Label horizontal padding textSizeF.Width; //Width of the label text graphics.DrawLine(pen, startX, lineY, endX, lineY); } private void DrawLeftLine(Graphics graphics, SizeF textSizeF, float lineY, Pen pen) { float startX = (float)this.Padding.Left + //Control left padding (float)LabelPadding.Horizontal + //Label left+right padding (float)LinePadding.Left + //Line left padding textSizeF.Width; //Width of the label text float endX = (float)this.Width - //Control width (float)this.Padding.Right - //Control right padding (float)this.LinePadding.Right; //Line right padding graphics.DrawLine(pen, startX, lineY, endX, lineY); } /// <summary> /// Determines the left point of the line /// </summary> /// <param name="graphics">Current graphics drawing object</param> /// <returns>Returns the left PointF</returns> private PointF GetLeftLinePoint(Graphics graphics) { PointF pointF = new PointF(); pointF.X = this.Padding.Left + this.LinePadding.Left; pointF.Y = GetLineVerticalLocation(); return pointF; } /// <summary> /// Determines the right point of the line /// </summary> /// <param name="graphics">Current graphics drawing object</param> /// <returns>Returns the right PointF</returns> private PointF GetRightLinePoint(Graphics graphics) { PointF pointF = new PointF(); pointF.X = this.Width - this.Padding.Right - this.LinePadding.Right; pointF.Y = GetLineVerticalLocation(); return pointF; } /// <summary> /// Determines the vertical location of the line /// </summary> /// <returns>the float location for the line Y</returns> private float GetLineVerticalLocation() { float Y = 0f; switch (this.LineLocation) { case VerticalAlignment.Top: { Y = this.Padding.Top + this.LinePadding.Top + 1; break; } case VerticalAlignment.Middle: { Y = (this.Height - this.Padding.Vertical) / 2; break; } case VerticalAlignment.Bottom: { Y = (this.Height - this.Padding.Bottom - this.LinePadding.Bottom - 1); break; } } return Y; } /// <summary> /// Determines the point location for the label text /// </summary> /// <param name="graphics">Current graphics drawing object</param> /// <returns>The PointF location of the label text</returns> private PointF GetTextPointF(Graphics graphics) { SizeF textSize = graphics.MeasureString(this.LabelText, this.Font); PointF pointF = new PointF(); pointF.Y = this.Padding.Top + this.LabelPadding.Top + 1; //If both the line and the label are top aligned, // bump the text down, including the line's padding if (LineLocation == VerticalAlignment.Top) { pointF.Y += this.LinePadding.Vertical + 1; } switch (this.LabelHorizontalAlignment) { case HorizontalAlignment.Left: { pointF.X = this.Padding.Left + this.LabelPadding.Left; break; } case HorizontalAlignment.Center: { pointF.X = (this.Width - this.Padding.Horizontal) / 2 - (int)textSize.Width / 2; break; } case HorizontalAlignment.Right: { pointF.X = (this.Width - this.Padding.Right - this.LabelPadding.Right) - (int)textSize.Width; break; } } return pointF; } } }
39.714286
149
0.498589
[ "BSD-2-Clause" ]
xihuan-citrix/xenadmin
XenAdmin/Controls/SectionHeaderLabel.cs
14,180
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.AspNetCore.SignalR.Protocol; namespace Microsoft.AspNetCore.Components.Server.BlazorPack { /// <summary> /// Implements the SignalR Hub Protocol using MessagePack with limited type support. /// </summary> [NonDefaultHubProtocol] internal sealed class BlazorPackHubProtocol : IHubProtocol { internal const string ProtocolName = "blazorpack"; private const int ProtocolVersion = 1; private readonly BlazorPackHubProtocolWorker _worker = new BlazorPackHubProtocolWorker(); /// <inheritdoc /> public string Name => ProtocolName; /// <inheritdoc /> public int Version => ProtocolVersion; /// <inheritdoc /> public TransferFormat TransferFormat => TransferFormat.Binary; /// <inheritdoc /> public bool IsVersionSupported(int version) { return version == Version; } /// <inheritdoc /> public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, out HubMessage message) => _worker.TryParseMessage(ref input, binder, out message); /// <inheritdoc /> public void WriteMessage(HubMessage message, IBufferWriter<byte> output) => _worker.WriteMessage(message, output); /// <inheritdoc /> public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message) => _worker.GetMessageBytes(message); } }
33.769231
119
0.683941
[ "MIT" ]
48355746/AspNetCore
src/Components/Server/src/BlazorPack/BlazorPackHubProtocol.cs
1,756
C#
using TMDb.Client.Attributes; namespace TMDb.Client.Api.V3.Models.Authentication { [ApiPostEndpoint("/authentication/token/validate_with_login")] public class CreateSessionWithLoginRequest : TMDbRequest { [ApiParameter( Name = "username", ParameterType = ParameterType.JsonBody)] public virtual string Username { get; set; } [ApiParameter( Name = "password", ParameterType = ParameterType.JsonBody)] public virtual string Password { get; set; } [ApiParameter( Name = "request_token", ParameterType = ParameterType.JsonBody)] public virtual string RequestToken { get; set; } } }
31.173913
66
0.634589
[ "MIT" ]
joshuajones02/TMDb
TMDb.Client/API/V3/Models/Authentication/CreateSessionWithLoginRequest.cs
719
C#
/* * Copyright (c) Contributors, http://vision-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Vision-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using Nini.Config; using OpenMetaverse; using Vision.Framework.ConsoleFramework; using Vision.Framework.Modules; using Vision.Framework.SceneInfo; using Vision.Region; namespace Vision.Physics.BulletSPlugin { public class ExtendedPhysics : INonSharedRegionModule { static string LogHeader = "[EXTENDED PHYSICS]"; // ============================================================= // Since BulletSim is a plugin, this these values aren't defined easily in one place. // This table must correspond to an identical table in BSScene. // Per scene functions. See BSScene. // Per avatar functions. See BSCharacter. // Per prim functions. See BSPrim. public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType"; public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType"; public const string PhysFunctChangeLinkFixed = "BulletSim.ChangeLinkFixed"; public const string PhysFunctChangeLinkType = "BulletSim.ChangeLinkType"; public const string PhysFunctGetLinkType = "BulletSim.GetLinkType"; public const string PhysFunctChangeLinkParams = "BulletSim.ChangeLinkParams"; public const string PhysFunctAxisLockLimits = "BulletSim.AxisLockLimits"; // ============================================================= IConfig Configuration { get; set; } bool Enabled { get; set; } IScene BaseScene { get; set; } IScriptModuleComms Comms { get; set; } #region INonSharedRegionModule public string Name { get { return GetType().Name; } } public void Initialize(IConfigSource config) { BaseScene = null; Enabled = false; Configuration = null; Comms = null; try { if ((Configuration = config.Configs["ExtendedPhysics"]) != null) { Enabled = Configuration.GetBoolean("Enabled", Enabled); } } catch (Exception e) { MainConsole.Instance.ErrorFormat("{0} Initialization error: {0}", LogHeader, e); } MainConsole.Instance.InfoFormat("{0} module {1} enabled", LogHeader, (Enabled ? "is" : "is not")); } public void Close() { if (BaseScene != null) { // Not implemented yet! /* BaseScene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene; BaseScene.EventManager.OnSceneObjectPartUpdated -= EventManager_OnSceneObjectPartUpdated; */ BaseScene = null; } } public void AddRegion(IScene scene) { } public void RemoveRegion(IScene scene) { if (BaseScene != null && BaseScene == scene) { Close(); } } public void RegionLoaded(IScene scene) { if (!Enabled) return; BaseScene = scene; Comms = BaseScene.RequestModuleInterface<IScriptModuleComms>(); if (Comms == null) { MainConsole.Instance.WarnFormat("{0} ScriptModuleComms interface not defined", LogHeader); Enabled = false; return; } // Not implemented Yet! // Register as LSL functions all the [ScriptInvocation] marked methods. //Comms.RegisterScriptInvocations(this); //Comms.RegisterConstants(this); // Not implemented Yet! // When an object is modifed, we might need to update its extended physics Parameters //BaseScene.EventManager.OnObjectBeingAddedToScene += Eventmanager_OnObjectAddedToScene; //BaseScene.EventManager.OnSceneObjectPartUpdated += EventManager_OnSceneObjectPartUpdated; } public Type ReplaceableInterface { get { return null; } } #endregion // INonSharedRegionModule void EventManager_OnObjectAddedToScene(SceneObjectGroup obj) { } // Event generated when some property of a prim changes. void EventManager_OnSceneObjectPartUpdated(SceneObjectPart sop, bool isFullUpdate) { } [ScriptConstant] public const int PHYS_CENTER_OF_MASS = 1 << 0; [ScriptInvocation] public string physGetEngineType(UUID hostID, UUID scriptID) { string ret = string.Empty; if (BaseScene.PhysicsScene != null) { ret = BaseScene.PhysicsScene.EngineType; } return ret; } // Code for specifying params. // The choice if 14700 is arbitrary and only serves to catch parameter code misuse. [ScriptConstant] public const int PHYS_AXIS_LOCK_LINEAR = 14700; [ScriptConstant] public const int PHYS_AXIS_LOCK_LINEAR_X = 14701; [ScriptConstant] public const int PHYS_AXIS_LIMIT_LINEAR_X = 14702; [ScriptConstant] public const int PHYS_AXIS_LOCK_LINEAR_Y = 14703; [ScriptConstant] public const int PHYS_AXIS_LIMIT_LINEAR_Y = 14704; [ScriptConstant] public const int PHYS_AXIS_LOCK_LINEAR_Z = 14705; [ScriptConstant] public const int PHYS_AXIS_LIMIT_LINEAR_Z = 14706; [ScriptConstant] public const int PHYS_AXIS_LOCK_ANGULAR = 14707; [ScriptConstant] public const int PHYS_AXIS_LOCK_ANGULAR_X = 14708; [ScriptConstant] public const int PHYS_AXIS_LIMIT_ANGULAR_X = 14709; [ScriptConstant] public const int PHYS_AXIS_LOCK_ANGULAR_Y = 14710; [ScriptConstant] public const int PHYS_AXIS_LIMIT_ANGULAR_Y = 14711; [ScriptConstant] public const int PHYS_AXIS_LOCK_ANGULAR_Z = 14712; [ScriptConstant] public const int PHYS_AXIS_LIMIT_ANGULAR_Z = 14713; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_LINEAR = 14714; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_LINEAR_X = 14715; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_LINEAR_Y = 14716; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_LINEAR_Z = 14717; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_ANGULAR = 14718; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_ANGULAR_X = 14719; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_ANGULAR_Y = 14720; [ScriptConstant] public const int PHYS_AXIS_UNLOCK_ANGULAR_Z = 14721; [ScriptConstant] public const int PHYS_AXIS_UNLOCK = 14722; /* // physAxisLockLimits() [ScriptInvocation] public int physAxisLock(UUID hostID, UUID scriptID, object[] parms) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; if (GetRootPhysActor(hostID, out rootPhysActor)) { object[] parms2 = AddToBeginningOfArray(rootPhysActor, null, parms); ret = MakeIntError(rootPhysActor.Extension(PhysFunctAxisLockLimits, parms2)); } return ret; } [ScriptConstant] public const int PHYS_LINKSET_TYPE_CONSTRAINT = 0; [ScriptConstant] public const int PHYS_LINKSET_TYPE_COMPOUND = 1; [ScriptConstant] public const int PHYS_LINKSET_TYPE_MANUAL = 2; */ /* [ScriptInvocation] public int physSetLinksetType(UUID hostID, UUID scriptID, int linksetType) { int ret = -1; if (!Enabled) return ret; // The part that is requesting the change. SceneObjectPart requestingPart = BaseScene.GetSceneObjectPart(hostID); if (requestingPart != null) { // The change is always made to the root of a linkset. SceneObjectGroup containingGroup = requestingPart.ParentGroup; SceneObjectPart rootPart = containingGroup.RootPart; if (rootPart != null) { PhysicsActor rootPhysActor = rootPart.PhysActor; if (rootPhysActor != null) { if (rootPhysActor.IsPhysical) { // Change a physical linkset by making non-physical, waiting for one heartbeat so all // the prim and linkset state is updated, changing the type and making the // linkset physical again. containingGroup.ScriptSetPhysicsStatus(false); Thread.Sleep(150); // longer than one heartbeat tick // A kludge for the moment. // Since compound linksets move the children but don't generate position updates to the // simulator, it is possible for compound linkset children to have out-of-sync simulator // and physical positions. The following causes the simulator to push the real child positions // down into the physics engine to get everything synced. containingGroup.UpdateGroupPosition(containingGroup.AbsolutePosition); containingGroup.UpdateGroupRotationR(containingGroup.GroupRotation); object[] parms2 = { rootPhysActor, null, linksetType }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctSetLinksetType, parms2)); Thread.Sleep(150); // longer than one heartbeat tick containingGroup.ScriptSetPhysicsStatus(true); } else { // Non-physical linksets don't have a physical instantiation so there is no state to // worry about being updated. object[] parms2 = { rootPhysActor, null, linksetType }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctSetLinksetType, parms2)); } } else { MainConsole.Instance.WarnFormat("{0} physSetLinksetType: root part does not have a physics actor. rootName={1}, hostID={2}", LogHeader, rootPart.Name, hostID); } } else { MainConsole.Instance.WarnFormat("{0} physSetLinksetType: root part does not exist. RequestingPartName={1}, hostID={2}", LogHeader, requestingPart.Name, hostID); } } else { MainConsole.Instance.WarnFormat("{0} physSetLinsetType: cannot find script object in scene. hostID={1}", LogHeader, hostID); } return ret; } [ScriptInvocation] public int physGetLinksetType(UUID hostID, UUID scriptID) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; if (GetRootPhysActor(hostID, out rootPhysActor)) { object[] parms2 = { rootPhysActor, null }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctGetLinksetType, parms2)); } else { MainConsole.Instance.WarnFormat("{0} physGetLinsetType: cannot find script object in scene. hostID={1}", LogHeader, hostID); } return ret; } */ [ScriptConstant] public const int PHYS_LINK_TYPE_FIXED = 1234; [ScriptConstant] public const int PHYS_LINK_TYPE_HINGE = 4; [ScriptConstant] public const int PHYS_LINK_TYPE_SPRING = 9; [ScriptConstant] public const int PHYS_LINK_TYPE_6DOF = 6; [ScriptConstant] public const int PHYS_LINK_TYPE_SLIDER = 7; /* // physChangeLinkType(integer linkNum, integer typeCode) [ScriptInvocation] public int physChangeLinkType(UUID hostID, UUID scriptID, int linkNum, int typeCode) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = { rootPhysActor, childPhysActor, typeCode }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkType, parms2)); } return ret; } // physGetLinkType(integer linkNum) [ScriptInvocation] public int physGetLinkType(UUID hostID, UUID scriptID, int linkNum) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = { rootPhysActor, childPhysActor }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctGetLinkType, parms2)); } return ret; } // physChangeLinkFixed(integer linkNum) // Change the link between the root and the linkNum into a fixed, static physical connection. [ScriptInvocation] public int physChangeLinkFixed(UUID hostID, UUID scriptID, int linkNum) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = { rootPhysActor, childPhysActor , PHYS_LINK_TYPE_FIXED }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkType, parms2)); } return ret; } */ // Code for specifying params. // The choice if 14400 is arbitrary and only serves to catch parameter code misuse. public const int PHYS_PARAM_MIN = 14401; [ScriptConstant] public const int PHYS_PARAM_FRAMEINA_LOC = 14401; [ScriptConstant] public const int PHYS_PARAM_FRAMEINA_ROT = 14402; [ScriptConstant] public const int PHYS_PARAM_FRAMEINB_LOC = 14403; [ScriptConstant] public const int PHYS_PARAM_FRAMEINB_ROT = 14404; [ScriptConstant] public const int PHYS_PARAM_LINEAR_LIMIT_LOW = 14405; [ScriptConstant] public const int PHYS_PARAM_LINEAR_LIMIT_HIGH = 14406; [ScriptConstant] public const int PHYS_PARAM_ANGULAR_LIMIT_LOW = 14407; [ScriptConstant] public const int PHYS_PARAM_ANGULAR_LIMIT_HIGH = 14408; [ScriptConstant] public const int PHYS_PARAM_USE_FRAME_OFFSET = 14409; [ScriptConstant] public const int PHYS_PARAM_ENABLE_TRANSMOTOR = 14410; [ScriptConstant] public const int PHYS_PARAM_TRANSMOTOR_MAXVEL = 14411; [ScriptConstant] public const int PHYS_PARAM_TRANSMOTOR_MAXFORCE = 14412; [ScriptConstant] public const int PHYS_PARAM_CFM = 14413; [ScriptConstant] public const int PHYS_PARAM_ERP = 14414; [ScriptConstant] public const int PHYS_PARAM_SOLVER_ITERATIONS = 14415; [ScriptConstant] public const int PHYS_PARAM_SPRING_AXIS_ENABLE = 14416; [ScriptConstant] public const int PHYS_PARAM_SPRING_DAMPING = 14417; [ScriptConstant] public const int PHYS_PARAM_SPRING_STIFFNESS = 14418; [ScriptConstant] public const int PHYS_PARAM_LINK_TYPE = 14419; [ScriptConstant] public const int PHYS_PARAM_USE_LINEAR_FRAMEA = 14420; [ScriptConstant] public const int PHYS_PARAM_SPRING_EQUILIBRIUM_POINT = 14421; public const int PHYS_PARAM_MAX = 14421; // Used when specifying a parameter that has settings for the three linear and three angular axis [ScriptConstant] public const int PHYS_AXIS_ALL = -1; [ScriptConstant] public const int PHYS_AXIS_LINEAR_ALL = -2; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_ALL = -3; [ScriptConstant] public const int PHYS_AXIS_LINEAR_X = 0; [ScriptConstant] public const int PHYS_AXIS_LINEAR_Y = 1; [ScriptConstant] public const int PHYS_AXIS_LINEAR_Z = 2; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_X = 3; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_Y = 4; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_Z = 5; /* // physChangeLinkParams(integer linkNum, [ PHYS_PARAM_*, value, PHYS_PARAM_*, value, ...]) [ScriptInvocation] public int physChangeLinkParams(UUID hostID, UUID scriptID, int linkNum, object[] parms) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = AddToBeginningOfArray(rootPhysActor, childPhysActor, parms); ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkParams, parms2)); } return ret; } bool GetRootPhysActor(UUID hostID, out PhysicsActor rootPhysActor) { SceneObjectGroup containingGroup; SceneObjectPart rootPart; return GetRootPhysActor(hostID, out containingGroup, out rootPart, out rootPhysActor); } bool GetRootPhysActor(UUID hostID, out SceneObjectGroup containingGroup, out SceneObjectPart rootPart, out PhysicsActor rootPhysActor) { bool ret = false; rootPhysActor = null; containingGroup = null; rootPart = null; SceneObjectPart requestingPart; requestingPart = BaseScene.GetSceneObjectPart(hostID); if (requestingPart != null) { // The type is is always on the root of a linkset. containingGroup = requestingPart.ParentGroup; if (containingGroup != null && !containingGroup.IsDeleted) { rootPart = containingGroup.RootPart; if (rootPart != null) { rootPhysActor = rootPart.PhysActor; if (rootPhysActor != null) { ret = true; } else { MainConsole.Instance.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not have a physics actor. rootName={1}, hostID={2}", LogHeader, rootPart.Name, hostID); } } else { MainConsole.Instance.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not exist. RequestingPartName={1}, hostID={2}", LogHeader, requestingPart.Name, hostID); } } else { MainConsole.Instance.WarnFormat("{0} GetRootAndChildPhysActors: Containing group missing or deleted. hostID={1}", LogHeader, hostID); } } else { MainConsole.Instance.WarnFormat("{0} GetRootAndChildPhysActors: cannot find script object in scene. hostID={1}", LogHeader, hostID); } return ret; } // Find the root and child PhysActors based on the linkNum. // Return 'true' if both are found and returned. bool GetRootAndChildPhysActors(UUID hostID, int linkNum, out PhysicsActor rootPhysActor, out PhysicsActor childPhysActor) { bool ret = false; rootPhysActor = null; childPhysActor = null; SceneObjectGroup containingGroup; SceneObjectPart rootPart; if (GetRootPhysActor(hostID, out containingGroup, out rootPart, out rootPhysActor)) { SceneObjectPart linkPart = containingGroup.GetLinkNumPart(linkNum); if (linkPart != null) { childPhysActor = linkPart.PhysActor; if (childPhysActor != null) { ret = true; } else { MainConsole.Instance.WarnFormat("{0} GetRootAndChildPhysActors: Link part has no physical actor. rootName={1}, hostID={2}, linknum={3}", LogHeader, rootPart.Name, hostID, linkNum); } } else { MainConsole.Instance.WarnFormat("{0} GetRootAndChildPhysActors: Could not find linknum part. rootName={1}, hostID={2}, linknum={3}", LogHeader, rootPart.Name, hostID, linkNum); } } else { MainConsole.Instance.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not have a physics actor. rootName={1}, hostID={2}", LogHeader, rootPart.Name, hostID); } return ret; } // Return an array of objects with the passed object as the first object of a new array object[] AddToBeginningOfArray(object firstOne, object secondOne, object[] prevArray) { object[] newArray = new object[2 + prevArray.Length]; newArray[0] = firstOne; newArray[1] = secondOne; prevArray.CopyTo(newArray, 2); return newArray; } // Extension() returns an object. Convert that object into the integer error we expect to return. int MakeIntError(object extensionRet) { int ret = -1; if (extensionRet != null) { try { ret = (int)extensionRet; } catch { ret = -1; } } return ret; } */ } }
40.57189
160
0.577208
[ "MIT" ]
VisionSim/Vision-Sim
Vision/Physics/BulletSPlugin/ExtendedPhysics.cs
25,114
C#
using System.Collections.Generic; using System.Linq; using AGS.API; namespace AGS.Engine { [PropertyFolder] public class AGSMultipleBorders : IBorderStyle { public AGSMultipleBorders(params IBorderStyle[] borders) { Borders = new List<IBorderStyle>(borders); } public List<IBorderStyle> Borders { get; } public float WidthBottom => Borders.Max(b => b.WidthBottom); public float WidthTop => Borders.Max(b => b.WidthTop); public float WidthLeft => Borders.Max(b => b.WidthLeft); public float WidthRight => Borders.Max(b => b.WidthRight); public void RenderBorderBack(AGSBoundingBox square) { for (int i = Borders.Count - 1; i >= 0; i--) { Borders[i].RenderBorderBack(square); } } public void RenderBorderFront(AGSBoundingBox square) { foreach (var border in Borders) { border.RenderBorderFront(square); } } } }
25.285714
68
0.574388
[ "Artistic-2.0" ]
OwenMcDonnell/MonoAGS
Source/Engine/AGS.Engine/UI/Borders/AGSMultipleBorders.cs
1,064
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. // All Rights Reserved. // Licensed under the MIT License. // See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Groove.Api.DataContract { using System; using System.Runtime.Serialization; /// <summary> /// User's subscription information /// </summary> [DataContract(Namespace = Constants.Xmlns)] public class SubscriptionState { /// <summary> /// Type of the active subscription: possible values at the moment are "Paid" and "PreTrial" /// </summary> [DataMember(EmitDefaultValue = false)] public string Type { get; set; } /// <summary> /// Two-letter region code of the subscription. This usually matches the user's account country, but not necessarily. /// </summary> [DataMember(EmitDefaultValue = false)] public string Region { get; set; } /// <summary> /// Expiration date of the current subscription /// </summary> [DataMember(EmitDefaultValue = false)] public DateTime? EndDate { get; set; } } }
34.263158
125
0.549155
[ "MIT" ]
Bhaskers-Blu-Org2/groove-api-sdk-csharp
src/GrooveApiDataContract/DataContract/SubscriptionState.cs
1,304
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(Animator))] public class CharacterMovement : MonoBehaviour { public float speed = 6f; public float turnSpeed = 60f; public float turnSmoothing = 15f; private Vector3 movement; private Animator _anim; private Rigidbody _rb; void Awake() { _anim = GetComponent<Animator>(); _rb = GetComponent<Rigidbody>(); } void FixedUpdate() { float lh = Input.GetAxisRaw("Horizontal"); float lv = Input.GetAxisRaw("Vertical"); Move(lh, lv); Animate(lh, lv); } void Move(float lh, float lv) { movement.Set(lh, 0f, lv); movement = movement.normalized * speed * Time.deltaTime; _rb.MovePosition(transform.position + movement); if (lh != 0f || lv != 0f) { Rotate(lh, lv); } } void Rotate(float lh, float lv) { Vector3 targetDirection = new Vector3(lh, 0f, lv); Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up); Quaternion newRotation = Quaternion.Lerp(_rb.rotation, targetRotation, turnSmoothing * Time.deltaTime); _rb.MoveRotation(newRotation); } void Animate(float lh, float lv) { bool isRunning = lh != 0f || lv != 0f; _anim.SetBool("isRunning", isRunning); } }
23.578947
106
0.680804
[ "MIT" ]
dheavy/unity-desert-robot
Assets/Scripts/CharacterMovement.cs
1,348
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameTurnBaseStrateg { /// <summary> /// 创建技能、创建人物对象, /// 每个人物角色都由四个技能: /// 1.一个无消耗的普通攻击,战士为物理攻击,法师为魔法攻击。 /// 2.三个消耗MP或者HP的特殊技能。 /// </summary> class DataManager { /// <summary> /// 普通攻击技能 /// </summary> /// <param name="hitTimes"></param> /// <param name="dispersion"></param> /// <param name="damageType"></param> /// <param name="targetType"></param> /// <returns></returns> public static Skill CreateAttackSkill( int hitTimes, int dispersion, DamageType damageType, TargetType targetType) { Skill skill = new Skill(); skill.name = "攻击"; skill.hpCost = 0; skill.mpCost = 0; skill.hitTimes = hitTimes; skill.dispersion = dispersion; skill.type = SkillType.NormalAttack; skill.damageType = damageType; skill.targetType = targetType; return skill; } /// <summary> /// 创建状态技能 /// </summary> /// <param name="name"></param> /// <param name="hpCost"></param> /// <param name="mpCost"></param> /// <param name="type"></param> /// <returns></returns> public static Skill CreateStateSkill( string name, int hpCost, int mpCost, TargetType type ) { Skill skill = new Skill(); skill.name = name; skill.hpCost = hpCost; skill.mpCost = mpCost; skill.type = SkillType.State; skill.targetType = type; return skill; } /// <summary> /// 创建一个伤害技能 /// </summary> /// <param name="name">技能名字</param> /// <param name="hpCost">消耗HP</param> /// <param name="mpCost">消耗MP</param> /// <param name="damage">伤害值,不为0的时候会覆盖掉effect里的伤害公式</param> /// <param name="hitTimes">攻击次数</param> /// <param name="targetType">目标类型</param> /// <param name="damageType">伤害类型</param> public static Skill CreateDamageSkill( string name, int hpCost, int mpCost, int hitTimes, int dispersion, TargetType targetType, DamageType damageType ) { Skill skill = new Skill(); skill.name = name; skill.hpCost = hpCost; skill.mpCost = mpCost; skill.hitTimes = hitTimes; skill.dispersion = dispersion; skill.targetType = targetType; skill.damageType = damageType; skill.type = SkillType.Damage; return skill; } /// <summary> /// 创建一个恢复技能 /// </summary> /// <param name="name"></param> /// <param name="hpCost"></param> /// <param name="mpCost"></param> /// <param name="hitTimes">技能生效的次数</param> /// <param name="dispersion">技能的恢复量,不为零的时候会覆盖后面的恢复量公式</param> /// <param name="targetType"></param> /// <returns></returns> public static Skill CreateHealSkill( string name, int hpCost, int mpCost, int hitTimes, int dispersion, TargetType targetType) { Skill skill = new Skill(); skill.name = name; skill.hpCost = hpCost; skill.mpCost = mpCost; skill.hitTimes = hitTimes; skill.dispersion = dispersion; skill.targetType = targetType; skill.type = SkillType.Heal; return skill; } /// <summary> /// 创建一个buff状态 /// </summary> /// <param name="name"></param> /// <param name="times"></param> /// <param name="counts"></param> /// <returns></returns> public static State CreateBuffState( string name, int times, int counts) { State state = new State(); state.name = name; state.times = times; state.counts = counts; state.type = StateType.Buff; return state; } /// <summary> /// 创建一个Debuff状态 /// </summary> /// <param name="name">名称</param> /// <param name="times">次数</param> /// <param name="counts">持续回合</param> /// <returns></returns> public static State CreateDebuffState( string name, int times, int counts) { State state = new State(); state.name = name; state.times = times; state.counts = counts; state.type = StateType.Debuff; return state; } /// <summary> /// 创建一个DOT持续伤害的类型状态 /// </summary> /// <param name="name"></param> /// <param name="times"></param> /// <param name="counts"></param> /// <param name="damage"></param> /// <returns></returns> public static State CreateDOTState( string name, int times, int counts, int damage) { State state = new State(); state.name = name; state.times = times; state.counts = counts; state.damage = damage; state.type = StateType.DamageOverTime; return state; } /// <summary> /// 创建一个HOT持续治疗类型的状态 /// </summary> /// <param name="name"></param> /// <param name="times"></param> /// <param name="counts"></param> /// <param name="hprecover"></param> /// <returns></returns> public static State CreateHOTState( string name, int times, int counts, int hprecover) { State state = new State(); state.name = name; state.times = times; state.counts = counts; state.hprecover = hprecover; state.type = StateType.HealOverTime; return state; } /// <summary> /// 创建一个特殊状态 /// </summary> /// <param name="name"></param> /// <param name="times">该状态使用次数</param> /// <param name="counts">该状态持续回合</param> /// <returns></returns> public static State CreateSpecialState( string name, int times, int counts) { State state = new State(); state.name = name; state.times = times; state.counts = counts; return state; } /// <summary> /// 创建一个伤害提高或减少的状态。 /// 调用后,在其他方法中会指定State是物理还是魔法 /// </summary> /// <param name="name"></param> /// <param name="times"></param> /// <param name="counts"></param> /// <param name="ratio"></param> /// <returns></returns> public static State CreateIncOrDecState( string name, int times, int counts, double ratio) { State state = new State(); state.name = name; state.times = times; state.counts = counts; state.ratio = ratio; return state; } public static BaseCharacter CreateCharSatsuki() { //角色的基本属性 BaseCharacter player = new BaseCharacter(); player.Name = "五月"; player.MaxHp = 421; player.MaxMp = 196; player.Hp = 421; player.Mp = 196; player.Atk = 42; player.Def = 23; player.Mat = 17; player.Men = 18; player.HitRatio = 95; player.CriticalChance = 10; player.Level = 5; player.type = CharacterType.Player; //1.统统攻击技能:创建一个单体物理攻击力为10,攻击次数为1的攻击技能 Skill normalAttack = CreateAttackSkill(1, 10, DamageType.Physical, TargetType.EnemySingle); normalAttack.description = "普通攻击,物理伤害。"; normalAttack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = attacker.Atk * 2 - target.Def; return temp > 0 ? temp : 1; }; player.skill.Add(normalAttack); //2.技能:蓄力,消耗MP Skill charge = CreateStateSkill("蓄力", 0, 30, TargetType.Self); charge.description = "MP【30】:积蓄力量,使得下一次的物理攻击伤害翻倍。"; charge.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State chargeState = CreateIncOrDecState("伤害提高", 1, 0, 2.0); chargeState.type = StateType.PhysicalDamageIncrease; chargeState.skillName = charge.name; attacker.AddState(chargeState); }; player.skill.Add(charge); //消耗MP Skill berserker = CreateStateSkill("狂化", 0, 20, TargetType.Self); berserker.description = "MP【20】:引发自己的吸血冲动,在3回合内增加物理攻击力,降低物理防御力。"; berserker.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State berserkerBuff = CreateBuffState("物理攻击力上升", 0, 4); berserkerBuff.skillName = berserker.name; berserkerBuff.AddState = (BaseCharacter a) => { berserkerBuff.atkUp = a.Atk / 2; a.Atk = a.Atk + berserkerBuff.atkUp; }; berserkerBuff.RemoveState = (BaseCharacter a) => { a.Atk = a.Atk - berserkerBuff.atkUp; }; attacker.AddState(berserkerBuff); State berserkerDebuff = CreateBuffState("物理防御力下降", 0, 4); berserkerDebuff.skillName = berserker.name; berserkerDebuff.AddState = (BaseCharacter a) => { berserkerDebuff.defUp = 0 - a.Def / 2; a.Def = a.Def + berserkerDebuff.defUp; }; berserkerDebuff.RemoveState = (BaseCharacter a) => { a.Def = a.Def - berserkerDebuff.defUp; }; attacker.AddState(berserkerDebuff); }; player.skill.Add(berserker); //3.技能:添加技能“BAKA杀”,消耗MP Skill bakaKill = CreateDamageSkill("八嘎杀", 0, 30, 3, 20, TargetType.EnemySingle, DamageType.Physical); bakaKill.description = "MP【30】:高速的连续攻击,对单个敌人造成3次小幅度的物理伤害。"; bakaKill.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = (attacker.Atk * 2 - target.Def) * 5 / 10; return temp > 0 ? temp : 1; }; player.skill.Add(bakaKill); //消耗MP Skill drynessGarden = CreateDamageSkill("枯渴庭院", 0, 80, 1, 10, TargetType.EnemyMulti, DamageType.Physical); drynessGarden.description = "MP【80】:迅速的抽空大气中的魔力,对敌方全体造成伤害并且减少魔法值。"; drynessGarden.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { target.Mp = target.Mp - attacker.Atk / 2; return attacker.Atk * 3 - target.Def * 2; }; player.skill.Add(drynessGarden); return player; } /// <summary> /// 创建角色艾露露,治疗 /// </summary> /// <returns></returns> public static BaseCharacter CreateCharEruruu() { BaseCharacter eruruu = new BaseCharacter(); eruruu.Name = "艾露露"; eruruu.MaxHp = 288; eruruu.MaxMp = 321; eruruu.Hp = 288; eruruu.Mp = 321; eruruu.Atk = 0; eruruu.Def = 17; eruruu.Mat = 23; eruruu.Men = 27; eruruu.HitRatio = 95; eruruu.CriticalChance = 10; eruruu.Level = 5; eruruu.type = CharacterType.Player; Skill herb = CreateHealSkill("草药", 0, 15, 1, 10, TargetType.PartySingle); herb.description = "MP【15】:艾露露自制的草药,恢复己方单体生命值。"; herb.skillDamage = new Skill.SkillDamage((BaseCharacter attacker, BaseCharacter target) => { return attacker.Men * 2; }); eruruu.skill.Add(herb); Skill rest = CreateStateSkill("摩洛洛粥", 0, 0, TargetType.Self); rest.description = "艾露露为自己准备的家乡的小食,恢复自身的MP值。"; rest.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { int temp = Convert.ToInt32(attacker.Men * 1.34); if (attacker.Mp + temp > attacker.MaxMp) temp = attacker.MaxMp - attacker.Mp; attacker.Mp += temp; MyDraw.DrawCharacterInfo(eruruu, 1); MyDraw.DrawBattleMessageDelay(string.Format("艾露露恢复了{0}点魔法值", temp)); }; eruruu.skill.Add(rest); Skill lilac = CreateHealSkill("花语", 0, 40, 1, 0, TargetType.PartyMulti); lilac.description = "艾露露利用山野中的鲜花特质的线香,为己方全体施加生命恢复效果。(MP:40)"; lilac.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { int tempRecover = Convert.ToInt32(attacker.Men * 3.0 / 2); State lilacState = CreateHOTState("花语", 0, 3, tempRecover); lilacState.skillName = lilac.name; target.AddState(lilacState); }; eruruu.skill.Add(lilac); Skill mandara = CreateDamageSkill("毒雾", 0, 30, 1, 0, TargetType.EnemyMulti, DamageType.Magic); mandara.description = "艾露露利用山中的毒草制成的迷雾攻击敌方全体,一定概率使得敌方中毒。(MP:30)"; mandara.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { int tempRecover = Convert.ToInt32(target.MaxHp * 0.07); if (Program.random.Next(0, 100) > 70) { State mandaraState = CreateDOTState("中毒", 0, 3, tempRecover); mandaraState.skillName = mandara.name; target.AddState(mandaraState); } }; eruruu.skill.Add(mandara); Skill callBack = CreateHealSkill("复活", 0, 50, 1, 10, TargetType.PartySingle); callBack.description = "艾露露复活一名已经阵亡的队友,恢复其30%HP。(MP:50)"; callBack.canDeath = true; callBack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { return Convert.ToInt32(target.MaxHp * 0.3); }; eruruu.skill.Add(callBack); Skill lifeLoop = CreateHealSkill("子守歌", 0, 60, 1, 20, TargetType.PartyMulti); lifeLoop.description = "艾露露唱起小时候听过的子守歌,恢复己方全体的生命值。(MP:60)"; lifeLoop.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { return Convert.ToInt32(attacker.Mat * 2.3 + 16); }; eruruu.skill.Add(lifeLoop); return eruruu; } /// <summary> /// 创建角色玲,魔法师 /// </summary> /// <returns></returns> public static BaseCharacter CreateCharRenne() { BaseCharacter renne = new BaseCharacter(); renne.Name = "玲"; renne.MaxHp = 267; renne.MaxMp = 352; renne.Hp = 267; renne.Mp = 352; renne.Atk = 10; renne.Def = 14; renne.Mat = 32; renne.Men = 23; renne.HitRatio = 90; renne.CriticalChance = 5; renne.Level = 5; renne.type = CharacterType.Player; Skill normalAttack = CreateAttackSkill(1, 10, DamageType.Magic, TargetType.EnemySingle); normalAttack.description = "普通攻击,魔法伤害。"; normalAttack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = attacker.Mat * 2 - target.Men; return temp > 0 ? temp : 1; }; renne.skill.Add(normalAttack); Skill stone = CreateStateSkill("石化光线", 0, 20, TargetType.EnemySingle); stone.description = "召唤帕蒂尔·玛蒂尔释放石化光线,有70%的概率使敌人进入石化状态3回合。(MP:20)"; stone.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { if (Program.random.Next(0, 100) > 70) { return; } MyDraw.DrawBattleMessageDelay("触发了石化效果!"); State dizzy = CreateSpecialState("石化", 0, 3); dizzy.type = StateType.Dizzy; dizzy.skillName = stone.name; target.AddState(dizzy); State damageDec = CreateIncOrDecState("物理抗性提升", 0, 3, -0.5); damageDec.type = StateType.PhysicalBeDamageIncrease; damageDec.skillName = stone.name; target.AddState(damageDec); }; renne.skill.Add(stone); Skill renneKill = CreateDamageSkill("玲·歼灭", 20, 40, 1, 15, TargetType.EnemyMulti, DamageType.Magic); renneKill.description = "玲挥动收割敌人的生命,对敌方全体造成伤害并且低概率即死。(HP:20,MP:40)"; renneKill.isDeathNow = true; renneKill.deathRatio = 15; renneKill.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = Convert.ToInt32(attacker.Mat * 1.67); return temp; }; renne.skill.Add(renneKill); Skill silence = CreateDamageSkill("天国之门", 0, 32, 1, 13, TargetType.EnemySingle, DamageType.Magic); silence.description = "开启天国之门,对单个敌人造成魔法伤害并且必定沉默。(MP:32)"; silence.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = Convert.ToInt32(attacker.Mat * 2.44 - target.Men * 0.83); return temp; }; silence.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State silenceState = CreateSpecialState("沉默", 0, 3); silenceState.skillName = silence.name; silenceState.type = StateType.Silence; target.AddState(silenceState); }; renne.skill.Add(silence); Skill PatelMattel = CreateDamageSkill("帕蒂尔·玛蒂尔", 0, 83, 3, 10, TargetType.EnemyMulti, DamageType.Magic); PatelMattel.description = "帕蒂尔·玛蒂尔用加农炮轰击前方的全体敌人,血量越低伤害越高。(MP:83)"; PatelMattel.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = Convert.ToInt32((attacker.Mat * 2.5 - target.Men * 0.6) * (2 - target.Hp * 1.0 / target.MaxHp)); return temp; }; renne.skill.Add(PatelMattel); return renne; } /// <summary> /// 创建角色马修,骑士 /// </summary> /// <returns></returns> public static BaseCharacter CreateCharMatthew() { BaseCharacter matthew = new BaseCharacter(); matthew.Name = "马修"; matthew.MaxHp = 631; matthew.MaxMp = 214; matthew.Hp = 631; matthew.Mp = 214; matthew.Atk = 19; matthew.Def = 42; matthew.Mat = 17; matthew.Men = 23; matthew.HitRatio = 80; matthew.CriticalChance = 10; matthew.Level = 5; matthew.type = CharacterType.Player; Skill normalAttack = CreateAttackSkill(1, 10, DamageType.Physical, TargetType.EnemySingle); normalAttack.description = "普通攻击,物理伤害。"; normalAttack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = attacker.Atk * 2 - target.Def; return temp > 0 ? temp : 1; }; matthew.skill.Add(normalAttack); Skill invincible = CreateStateSkill("白垩之壁", 0, 30, TargetType.PartySingle); invincible.description = "撑起扰乱时间的屏障,为己方单人赋予一次无敌效果。(MP:30)"; invincible.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State invState = CreateSpecialState("无敌", 1, 0); invState.type = StateType.Invincible; invState.skillName = invincible.name; target.AddState(invState); }; matthew.skill.Add(invincible); Skill defUp = CreateStateSkill("雪花之壁", 0, 28, TargetType.PartyMulti); defUp.description = "为己方全体撑起精神护盾,提高全体的物理防御力。(MP:28)"; defUp.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State defupState = CreateBuffState("物理防御力上升", 0, 4); defupState.type = StateType.Buff; defupState.AddState = (BaseCharacter one) => { defupState.defUp = Convert.ToInt32(one.Def * 0.3); one.Def += defupState.defUp; }; defupState.RemoveState = (BaseCharacter one) => { one.Def -= defupState.defUp; }; defupState.skillName = defUp.name; target.AddState(defupState); }; matthew.skill.Add(defUp); Skill taunt = CreateStateSkill("决意之盾", 0, 17, TargetType.Self); taunt.description = "坚定守护队友的决心,一定时间内提高自己被攻击的概率。(MP:17)"; taunt.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State tauntState = CreateSpecialState("嘲讽", 0, 4); tauntState.skillName = taunt.name; tauntState.ratio = 0.5; tauntState.type = StateType.Taunt; attacker.AddState(tauntState); }; matthew.skill.Add(taunt); Skill revive = CreateStateSkill("神圣之城", 0, 44, TargetType.PartySingle); revive.description = "为队友附加神圣的守护,使一名队友能够复活一次。(MP:44)"; revive.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State revState = CreateSpecialState("复活", 1, 0); revState.skillName = revive.name; revState.type = StateType.Revive; target.AddState(revState); }; matthew.skill.Add(revive); return matthew; } /// <summary> /// 创建一个怪物红色史莱姆 /// </summary> /// <returns></returns> public static BaseCharacter CreateCharSlimeRed() { BaseCharacter slime = new BaseCharacter(); slime.Name = "红色史莱姆"; slime.MaxHp = 1351; slime.MaxMp = 385; slime.Hp = 1351; slime.Mp = 385; slime.Atk = 40; slime.Def = 40; slime.Mat = 20; slime.Men = 20; slime.HitRatio = 80; slime.CriticalChance = 5; slime.Level = 15; slime.type = CharacterType.Enemy; slime.actionType = ActionMode.MaxHP; Skill normalAttack = CreateAttackSkill(1, 20, DamageType.Physical, TargetType.EnemySingle); normalAttack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { return attacker.Atk * 2 - target.Def; }; slime.skill.Add(normalAttack); Skill strongeAttack = CreateDamageSkill("强击", 0, 10, 1, 10, TargetType.EnemySingle, DamageType.Physical); strongeAttack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { return attacker.Atk * 3 - target.Def; }; slime.skill.Add(strongeAttack); Skill softBody = CreateStateSkill("柔化", 0, 20, TargetType.Self); softBody.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State softState = CreateIncOrDecState("物理伤害降低", 0, 4, -0.5); softState.type = StateType.PhysicalBeDamageIncrease; softState.skillName = softBody.name; attacker.AddState(softState); }; slime.skill.Add(softBody); Skill phyReflect = CreateStateSkill("物理反射", 0, 20, TargetType.Self); phyReflect.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State phyReflectState = CreateSpecialState("物理反射", 1, 0); phyReflectState.type = StateType.PhysicalReflect; phyReflectState.skillName = phyReflect.name; attacker.AddState(phyReflectState); }; slime.skill.Add(phyReflect); //史莱姆的技能选择逻辑,就是最简单的AI slime.GetRandomSkill = (BaseCharacter bc, List<BaseCharacter> bcList, int counts) => { //每7回合用一次柔化 if (counts % 7 == 1) { if (bc.skill[2].CanUseSkill(bc)) return bc.skill[2]; } //血量低于一半的时候如果自身没有物理反射状态,释放物理反射技能 if (bc.Hp < (bc.MaxHp / 2)) { if (!bc.HasState(StateType.PhysicalReflect)) if (bc.skill[3].CanUseSkill(bc)) return bc.skill[3]; } //其他情况下,优先在普通攻击和强击中选择技能 List<int> tempList = new List<int>(); for (int i = 0; i < 2; i++) { if (bc.skill[i].CanUseSkill(bc)) tempList.Add(i); } return bc.skill[tempList[Program.random.Next(0, tempList.Count)]]; }; return slime; } /// <summary> /// 创造一个蓝色史莱姆 /// </summary> /// <returns></returns> public static BaseCharacter CreateCharSlimeBlue() { BaseCharacter slime = new BaseCharacter(); slime.Name = "蓝色史莱姆"; slime.MaxHp = 952; slime.MaxMp = 502; slime.Hp = 952; slime.Mp = 502; slime.Atk = 20; slime.Def = 20; slime.Mat = 40; slime.Men = 40; slime.HitRatio = 80; slime.CriticalChance = 0; slime.Level = 15; slime.type = CharacterType.Enemy; slime.actionType = ActionMode.MinHP; Skill normalAttack = CreateAttackSkill(1, 10, DamageType.Magic, TargetType.EnemySingle); normalAttack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { return attacker.Mat * 2 - target.Men; }; slime.skill.Add(normalAttack); Skill magReflect = CreateStateSkill("魔法反射", 0, 30, TargetType.Self); magReflect.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State magrefState = CreateSpecialState("魔法反射", 1, 0); magrefState.skillName = magReflect.name; magrefState.type = StateType.MagicReflect; target.AddState(magrefState); }; slime.skill.Add(magReflect); Skill forbidHeal = CreateStateSkill("禁疗", 0, 30, TargetType.EnemyMulti); forbidHeal.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State forbidHealState = CreateSpecialState("禁疗", 0, 4); forbidHealState.skillName = forbidHeal.name; forbidHealState.type = StateType.ForbidHeal; target.AddState(forbidHealState); }; slime.skill.Add(forbidHeal); Skill magicBullet = CreateDamageSkill("魔法爆弹", 0, 10, 1, 5, TargetType.EnemySingle, DamageType.Magic); magicBullet.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = Convert.ToInt32(attacker.Mat * 2.75 - target.Men); return temp > 0 ? temp : 1; }; slime.skill.Add(magicBullet); Skill heal = CreateHealSkill("治疗", 0, 20, 1, 0, TargetType.PartySingle); heal.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = Convert.ToInt32(attacker.Men * 3.3); return temp > 0 ? temp : 1; }; slime.skill.Add(heal); slime.GetRandomSkill = (BaseCharacter bc, List<BaseCharacter> bcList, int counts) => { //从第三回合开始每7回合一次禁疗 if (counts % 7 == 3) { if (bc.skill[2].CanUseSkill(bc)) return bc.skill[2]; } //从第二回合开始,每四回合检测一次血量并选择释放回血技能 if (counts % 4 == 2) { for (int i = 0; i < bcList.Count; i++) { if (bcList[i].Hp < bcList[i].MaxHp / 2) { if (bc.skill[4].CanUseSkill(bc) && bcList[i].CanBeTarget(bc.skill[4])) return bc.skill[4]; } } } //从第一回合开始每5回合一次魔法反射 if (counts % 5 == 1) { if (!bc.HasState(StateType.MagicReflect)) { if (bc.skill[1].CanUseSkill(bc)) return bc.skill[1]; } } //其他情况能用魔法爆弹就用魔法爆弹 if (bc.skill[3].CanUseSkill(bc)) return bc.skill[3]; return bc.skill[0]; }; return slime; } /// <summary> /// 创造一个史莱姆王 /// </summary> /// <returns></returns> public static BaseCharacter CreateCharSlimeKing() { BaseCharacter slimeKing = new BaseCharacter(); slimeKing.Name = "史莱姆王"; slimeKing.MaxHp = 5428; slimeKing.MaxMp = 2301; slimeKing.Hp = 5428; slimeKing.Mp = 2301; slimeKing.Atk = 50; slimeKing.Def = 30; slimeKing.Mat = 42; slimeKing.Men = 19; slimeKing.HitRatio = 85; slimeKing.CriticalChance = 15; slimeKing.Level = 15; slimeKing.type = CharacterType.Enemy; Skill normalAttack = CreateAttackSkill(1, 20, DamageType.Physical, TargetType.EnemySingle); normalAttack.skillDamage = (BaseCharacter attacker, BaseCharacter target) => { int temp = Convert.ToInt32(attacker.Atk * 1.78 - target.Def); return temp > 0 ? temp : 1; }; slimeKing.skill.Add(normalAttack); Skill damageDec = CreateStateSkill("伤害加深", 0, 40, TargetType.EnemySingle); damageDec.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { State damageIncState = CreateIncOrDecState("物理伤害加深", 0, 3, 0.4); damageIncState.skillName = damageDec.name; damageIncState.type = StateType.PhysicalBeDamageIncrease; target.AddState(damageIncState); State damageIncState2 = CreateIncOrDecState("魔法伤害加深", 0, 3, 0.4); damageIncState2.skillName = damageDec.name; damageIncState2.type = StateType.MagicBeDamageIncrease; target.AddState(damageIncState2); }; slimeKing.skill.Add(damageDec); Skill recover = CreateStateSkill("再生", 0, 52, TargetType.Self); recover.skillEffect = (BaseCharacter attacker, BaseCharacter target) => { int hprecover = Convert.ToInt32(attacker.MaxHp * 0.02); State recoverState = CreateHOTState("再生", 0, 3, hprecover); recoverState.skillName = damageDec.name; target.AddState(recoverState); }; slimeKing.skill.Add(recover); slimeKing.GetRandomSkill = (BaseCharacter bc, List<BaseCharacter> bcList, int counts) => { //如果掉血了且不处于再生状态下,释放再生技能 if (bc.Hp < bc.MaxHp) { if (!bc.HasState(StateType.HealOverTime)) if (bc.skill[2].CanUseSkill(bc)) return bc.skill[2]; } if (counts % 4 == 2) if (bc.skill[1].CanUseSkill(bc)) return bc.skill[2]; return bc.skill[0]; }; return slimeKing; } } }
37.895097
123
0.508335
[ "Apache-2.0" ]
ggwhsd/CSharpStudy
OtherProjects/GameTurnBaseStrategy/DataManager.cs
35,828
C#
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V23.Group; using NHapi.Model.V23.Segment; using NHapi.Model.V23.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V23.Message { ///<summary> /// Represents a ORN_O02 message structure (see chapter 4.7). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (Message header segment) </li> ///<li>1: MSA (Message acknowledgement segment) </li> ///<li>2: ERR (Error segment) optional </li> ///<li>3: NTE (Notes and comments segment) optional repeating</li> ///<li>4: ORN_O02_RESPONSE (a Group object) optional </li> ///</ol> ///</summary> [Serializable] public class ORN_O02 : AbstractMessage { ///<summary> /// Creates a new ORN_O02 Group with custom IModelClassFactory. ///</summary> public ORN_O02(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new ORN_O02 Group with DefaultModelClassFactory. ///</summary> public ORN_O02() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for ORN_O02. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(MSA), true, false); this.add(typeof(ERR), false, false); this.add(typeof(NTE), false, true); this.add(typeof(ORN_O02_RESPONSE), false, false); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ORN_O02 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (Message header segment) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns MSA (Message acknowledgement segment) - creates it if necessary ///</summary> public MSA MSA { get{ MSA ret = null; try { ret = (MSA)this.GetStructure("MSA"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns ERR (Error segment) - creates it if necessary ///</summary> public ERR ERR { get{ ERR ret = null; try { ret = (ERR)this.GetStructure("ERR"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NTE (Notes and comments segment) - creates it if necessary ///</summary> public NTE GetNTE() { NTE ret = null; try { ret = (NTE)this.GetStructure("NTE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NTE /// * (Notes and comments segment) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NTE GetNTE(int rep) { return (NTE)this.GetStructure("NTE", rep); } /** * Returns the number of existing repetitions of NTE */ public int NTERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NTE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NTE results */ public IEnumerable<NTE> NTEs { get { for (int rep = 0; rep < NTERepetitionsUsed; rep++) { yield return (NTE)this.GetStructure("NTE", rep); } } } ///<summary> ///Adds a new NTE ///</summary> public NTE AddNTE() { return this.AddStructure("NTE") as NTE; } ///<summary> ///Removes the given NTE ///</summary> public void RemoveNTE(NTE toRemove) { this.RemoveStructure("NTE", toRemove); } ///<summary> ///Removes the NTE at the given index ///</summary> public void RemoveNTEAt(int index) { this.RemoveRepetition("NTE", index); } ///<summary> /// Returns ORN_O02_RESPONSE (a Group object) - creates it if necessary ///</summary> public ORN_O02_RESPONSE RESPONSE { get{ ORN_O02_RESPONSE ret = null; try { ret = (ORN_O02_RESPONSE)this.GetStructure("RESPONSE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } } }
27.090909
145
0.658425
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V23/Message/ORN_O02.cs
5,662
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Kongverge.DTOs; using Kongverge.Helpers; using Kongverge.Services; using Kongverge.Workflow; using Moq; using TestStack.BDDfy; using TestStack.BDDfy.Xunit; namespace Kongverge.Tests.Workflow { public class KongvergeWorkflowScenarios : WorkflowSteps<KongvergeWorkflow> { protected const string And = "_"; protected KongvergeConfiguration Target = new KongvergeConfiguration(); protected IReadOnlyList<ExtendibleKongObject> GlobalConfigs; protected IReadOnlyList<KongService> Services; protected IReadOnlyList<KongRoute> Routes; protected IReadOnlyList<KongPlugin> Plugins; protected List<KongPlugin> InsertedPlugins = new List<KongPlugin>(); public KongvergeWorkflowScenarios() { GlobalConfigs = Fixture.CreateGlobalConfigs(2); Services = Fixture.CreateServices(4); Routes = Fixture.CreateRoutes(6); Plugins = Fixture.CreatePlugins(10); GetMock<IKongAdminWriter>() .Setup(x => x.AddRoute(It.IsAny<string>(), It.IsAny<KongRoute>())) .Returns<string, KongRoute>((serviceId, route) => { if (serviceId == null) { throw new InvalidOperationException(); } route.WithIdAndCreatedAtAndServiceReference(serviceId); return Task.CompletedTask; }); GetMock<IKongAdminWriter>() .Setup(x => x.UpsertPlugin(It.IsAny<KongPlugin>())) .Returns<KongPlugin>(x => { if (x.Id == null) { InsertedPlugins.Add(x); } x.WithIdAndCreatedAt(); return Task.CompletedTask; }); GetMock<IKongAdminWriter>() .Setup(x => x.AddService(It.IsAny<KongService>())) .Returns<KongService>(x => { x.WithIdAndCreatedAt(); return Task.CompletedTask; }); } [BddfyFact(DisplayName = nameof(KongIsNotReachable))] public void Scenario1() => this.Given(s => s.KongIsNotReachable()) .When(s => s.Executing()) .Then(s => s.TheExitCodeIs(ExitCode.HostUnreachable)) .BDDfy(); [BddfyFact(DisplayName = nameof(KongIsReachable) + And + nameof(NonExistentInputFolder))] public void Scenario2() => this.Given(s => s.KongIsReachable()) .And(s => s.NonExistentInputFolder()) .When(s => s.Executing()) .Then(s => s.TheExitCodeIs(ExitCode.InputFolderUnreachable)) .BDDfy(); [BddfyFact(DisplayName = nameof(KongIsReachable) + And + nameof(InvalidTargetConfiguration))] public void Scenario3() => this.Given(s => s.KongIsReachable()) .And(s => s.InvalidTargetConfiguration()) .When(s => s.Executing()) .Then(s => s.TheExitCodeIs(ExitCode.InvalidConfigurationFile)) .BDDfy(); [BddfyFact(DisplayName = nameof(KongIsReachable) + And + nameof(NoExistingServicesOrGlobalConfig) + And + nameof(NoTargetServicesOrGlobalConfig))] public void Scenario4() => this.Given(s => s.KongIsReachable()) .And(s => s.NoExistingServicesOrGlobalConfig()) .And(s => s.NoTargetServicesOrGlobalConfig()) .When(s => s.Executing()) .Then(s => s.NoServicesAreAdded()) .And(s => s.NoServicesAreUpdated()) .And(s => s.NoServicesAreDeleted()) .And(s => s.NoRoutesAreAdded()) .And(s => s.NoRoutesAreDeleted()) .And(s => s.NoPluginsAreUpserted()) .And(s => s.NoPluginsAreDeleted()) .And(s => s.TheExitCodeIs(ExitCode.Success)) .BDDfy(); [BddfyFact(DisplayName = nameof(KongIsReachable) + And + nameof(NoExistingServicesOrGlobalConfig) + And + nameof(AnAssortmentOfTargetServicesAndGlobalConfig))] public void Scenario5() => this.Given(s => s.KongIsReachable()) .And(s => s.NoExistingServicesOrGlobalConfig()) .And(s => s.AnAssortmentOfTargetServicesAndGlobalConfig()) .When(s => s.Executing()) .Then(s => s.TheTargetServicesAreAdded()) .And(s => s.NoServicesAreUpdated()) .And(s => s.NoServicesAreDeleted()) .And(s => s.TheTargetRoutesAreAdded()) .And(s => s.NoRoutesAreDeleted()) .And(s => s.TheTargetPluginsAreUpserted()) .And(s => s.NoPluginsAreDeleted()) .And(s => s.TheExitCodeIs(ExitCode.Success)) .BDDfy(); [BddfyFact(DisplayName = nameof(KongIsReachable) + And + nameof(AnAssortmentOfExistingServicesAndGlobalConfig) + And + nameof(NoTargetServicesOrGlobalConfig))] public void Scenario6() => this.Given(s => s.KongIsReachable()) .And(s => s.AnAssortmentOfExistingServicesAndGlobalConfig()) .And(s => s.NoTargetServicesOrGlobalConfig()) .When(s => s.Executing()) .Then(s => s.NoServicesAreAdded()) .And(s => s.NoServicesAreUpdated()) .And(s => s.TheExistingServicesAreDeleted()) .And(s => s.NoRoutesAreAdded()) .And(s => s.NoRoutesAreDeleted()) .And(s => s.NoPluginsAreUpserted()) .And(s => s.TheExistingPluginsAreDeleted()) .And(s => s.TheExitCodeIs(ExitCode.Success)) .BDDfy(); [BddfyFact(DisplayName = nameof(KongIsReachable) + And + nameof(AnAssortmentOfExistingServicesAndGlobalConfig) + And + nameof(AnAssortmentOfTargetServicesAndGlobalConfig))] public void Scenario7() => this.Given(s => s.KongIsReachable()) .And(s => s.AnAssortmentOfExistingServicesAndGlobalConfig()) .And(s => s.AnAssortmentOfTargetServicesAndGlobalConfig()) .When(s => s.Executing()) .Then(s => s.TheNewServicesAreAdded()) .And(s => s.TheChangedServicesAreUpdated()) .And(s => s.TheUnchangedServicesAreNotUpdated()) .And(s => s.TheRemovedServicesAreDeleted()) .And(s => s.TheChangedOrNewRoutesAreAdded()) .And(s => s.TheUnchangedRoutesAreNotAddedOrDeleted()) .And(s => s.TheChangedOrRemovedRoutesAreDeleted()) .And(s => s.TheChangedOrNewPluginsAreUpserted()) .And(s => s.TheUnchangedPluginsAreNotUpserted()) .And(s => s.NoneOfThePluginsOfChangedOrDeletedRoutesAreUpserted()) .And(s => s.TheRemovedPluginsAreDeleted()) .And(s => s.NoneOfThePluginsOfDeletedServicesAreDeleted()) .And(s => s.NoneOfThePluginsOfChangedOrDeletedRoutesAreDeleted()) .And(s => s.TheExitCodeIs(ExitCode.Success)) .BDDfy(); protected void NoExistingServicesOrGlobalConfig() { Existing.Services = Array.Empty<KongService>(); Existing.GlobalConfig = new ExtendibleKongObject(); } protected void NoTargetServicesOrGlobalConfig() { Target.Services = Array.Empty<KongService>(); Target.GlobalConfig = new ExtendibleKongObject(); SetupTargetConfiguration(); } protected void NonExistentInputFolder() => GetMock<ConfigFileReader>().Setup(x => x.ReadConfiguration(Settings.InputFolder)).ThrowsAsync(new DirectoryNotFoundException()); protected void InvalidTargetConfiguration() => GetMock<ConfigFileReader>().Setup(x => x.ReadConfiguration(Settings.InputFolder)).ThrowsAsync(new InvalidConfigurationFileException(string.Empty, string.Empty)); protected void AnAssortmentOfExistingServicesAndGlobalConfig() { Existing.Services = new[] { Services[0].AsExisting(), Services[1].AsExisting(), Services[2].AsExisting() }; Existing.Services[0].Plugins = new[] { Plugins[3].AsExisting(), Plugins[4].AsExisting(), Plugins[5].AsExisting() }; Existing.Services[0].Routes = new[] { Routes[0].AsExisting(), Routes[1].AsExisting(), Routes[2].AsExisting() }; Existing.Services[0].Routes[0].Plugins = new[] { Plugins[0].AsExisting(), Plugins[1].AsExisting(), Plugins[2].AsExisting() }; Existing.Services[0].Routes[1].Plugins = new[] { Plugins[3].AsExisting(), Plugins[4].AsExisting(), Plugins[5].AsExisting() }; Existing.Services[1].Routes = new[] { Routes[3].AsExisting() }; Existing.Services[2].Plugins = new[] { Plugins[0].AsExisting() }; Existing.Services[2].Routes = new[] { Routes[4].AsExisting(), Routes[5].AsExisting() }; Existing.GlobalConfig = GlobalConfigs[0]; Existing.GlobalConfig.Plugins = new[] { Plugins[6].AsExisting(), Plugins[7].AsExisting(), Plugins[8].AsExisting() }; } protected void AnAssortmentOfTargetServicesAndGlobalConfig() { Target.Services = new[] { Services[0].AsTarget(true), // Changed Services[1].AsTarget(), // Same // Services[2] Removed Services[3].AsTarget() // Added }; Target.Services[0].Plugins = new[] { Plugins[3].AsTarget(true), // Changed Plugins[4].AsTarget(), // Same // Plugins[5] Removed Plugins[6].AsTarget() // Added }; Target.Services[0].Routes = new[] { Routes[0].AsTarget(true), // Changed Routes[1].AsTarget(), // Same // Routes[2] Removed Routes[3].AsTarget() // Added }; Target.Services[0].Routes[0].Plugins = new[] { Plugins[0].AsTarget(true), // Changed Plugins[1].AsTarget(), // Same // Plugins[2] Removed Plugins[3].AsTarget() // Added }; Target.Services[0].Routes[1].Plugins = new[] { Plugins[3].AsTarget(true), // Changed Plugins[4].AsTarget(), // Same // Plugins[5] Removed Plugins[6].AsTarget() // Added }; Target.Services[1].Routes = new[] { // Routes[3] Removed Routes[4].AsTarget() // Added }; Target.Services[2].Routes = new[] { Routes[5].AsTarget() // Added }; Target.Services[2].Routes[0].Plugins = new[] { Plugins[0].AsTarget(), // Added Plugins[1].AsTarget() // Added }; Target.GlobalConfig = GlobalConfigs[1]; Target.GlobalConfig.Plugins = new[] { Plugins[6].AsTarget(true), // Changed Plugins[7].AsTarget(), // Same // Plugins[8] Removed Plugins[9].AsTarget() // Added }; SetupTargetConfiguration(); } protected void SetupTargetConfiguration() => GetMock<ConfigFileReader>().Setup(x => x.ReadConfiguration(Settings.InputFolder)).ReturnsAsync(Target); protected void NoServicesAreAdded() => GetMock<IKongAdminWriter>().Verify(x => x.AddService(It.IsAny<KongService>()), Times.Never); protected void NoServicesAreUpdated() => GetMock<IKongAdminWriter>().Verify(x => x.UpdateService(It.IsAny<KongService>()), Times.Never); protected void NoServicesAreDeleted() => GetMock<IKongAdminWriter>().Verify(x => x.DeleteService(It.IsAny<string>()), Times.Never); protected void NoRoutesAreAdded() => GetMock<IKongAdminWriter>().Verify(x => x.AddRoute(It.IsAny<string>(), It.IsAny<KongRoute>()), Times.Never); protected void NoRoutesAreDeleted() => GetMock<IKongAdminWriter>().Verify(x => x.DeleteRoute(It.IsAny<string>()), Times.Never); protected void NoPluginsAreUpserted() => GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.IsAny<KongPlugin>()), Times.Never); protected void NoPluginsAreDeleted() => GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(It.IsAny<string>()), Times.Never); protected void TheTargetServicesAreAdded() { foreach (var targetService in Target.Services) { GetMock<IKongAdminWriter>().Verify(x => x.AddService(targetService), Times.Once); } } protected void TheExistingServicesAreDeleted() { foreach (var existingService in Existing.Services) { GetMock<IKongAdminWriter>().Verify(x => x.DeleteService(existingService.Id), Times.Once); } } protected void TheTargetRoutesAreAdded() { foreach (var targetService in Target.Services) { foreach (var targetRoute in targetService.Routes) { GetMock<IKongAdminWriter>().Verify(x => x.AddRoute(targetService.Id, targetRoute), Times.Once); } } } protected void TheTargetPluginsAreUpserted() { foreach (var targetService in Target.Services) { foreach (var targetPlugin in targetService.Plugins) { GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(targetPlugin) && p.CorrespondsToKongService(targetService))), Times.Once); } foreach (var targetRoute in targetService.Routes) { foreach (var targetPlugin in targetRoute.Plugins) { GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(targetPlugin) && p.CorrespondsToKongRoute(targetRoute))), Times.Once); } } } foreach (var targetPlugin in Target.GlobalConfig.Plugins) { GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(targetPlugin) && p.IsGlobal())), Times.Once); } } protected void TheExistingPluginsAreDeleted() { foreach (var existingPlugin in Existing.GlobalConfig.Plugins) { GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(existingPlugin.Id), Times.Once); } } protected void TheNewServicesAreAdded() => GetMock<IKongAdminWriter>().Verify(x => x.AddService(Target.Services[2]), Times.Once); protected void TheChangedServicesAreUpdated() => GetMock<IKongAdminWriter>().Verify(x => x.UpdateService(Target.Services[0]), Times.Once); protected void TheUnchangedServicesAreNotUpdated() => GetMock<IKongAdminWriter>().Verify(x => x.UpdateService(Target.Services[1]), Times.Never); protected void TheRemovedServicesAreDeleted() => GetMock<IKongAdminWriter>().Verify(x => x.DeleteService(Existing.Services[2].Id), Times.Once); protected void TheChangedOrNewRoutesAreAdded() { GetMock<IKongAdminWriter>().Verify(x => x.AddRoute(Target.Services[0].Id, Target.Services[0].Routes[0]), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.AddRoute(Target.Services[0].Id, Target.Services[0].Routes[2]), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.AddRoute(Existing.Services[1].Id, Target.Services[1].Routes[0]), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.AddRoute(Target.Services[2].Id, Target.Services[2].Routes[0]), Times.Once); } protected void TheUnchangedRoutesAreNotAddedOrDeleted() { GetMock<IKongAdminWriter>().Verify(x => x.AddRoute(Target.Services[0].Id, Target.Services[0].Routes[1]), Times.Never); GetMock<IKongAdminWriter>().Verify(x => x.DeleteRoute(Existing.Services[0].Routes[1].Id), Times.Never); } protected void TheChangedOrRemovedRoutesAreDeleted() { GetMock<IKongAdminWriter>().Verify(x => x.DeleteRoute(Existing.Services[0].Routes[0].Id), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.DeleteRoute(Existing.Services[1].Routes[0].Id), Times.Once); } protected void TheChangedOrNewPluginsAreUpserted() { GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[0].Plugins[0]) && p.CorrespondsToKongService(Target.Services[0]) && p.CorrespondsToExistingPlugin(Existing.Services[0].Plugins[0]))), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[0].Plugins[2]) && p.CorrespondsToKongService(Target.Services[0]) && InsertedPlugins.Contains(p))), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[0].Routes[1].Plugins[0]) && p.CorrespondsToKongRoute(Target.Services[0].Routes[1]) && p.CorrespondsToExistingPlugin(Existing.Services[0].Routes[1].Plugins[0]))), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[0].Routes[1].Plugins[2]) && p.CorrespondsToKongRoute(Target.Services[0].Routes[1]) && InsertedPlugins.Contains(p))), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[2].Routes[0].Plugins[0]) && p.CorrespondsToKongRoute(Target.Services[2].Routes[0]) && InsertedPlugins.Contains(p))), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[2].Routes[0].Plugins[1]) && p.CorrespondsToKongRoute(Target.Services[2].Routes[0]) && InsertedPlugins.Contains(p))), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.GlobalConfig.Plugins[0]) && p.IsGlobal() && p.CorrespondsToExistingPlugin(Existing.GlobalConfig.Plugins[0]))), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.GlobalConfig.Plugins[2]) && p.IsGlobal() && InsertedPlugins.Contains(p))), Times.Once); } protected void TheUnchangedPluginsAreNotUpserted() { GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[0].Routes[1].Plugins[1]) && p.CorrespondsToKongRoute(Target.Services[0].Routes[1]))), Times.Never); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.Services[0].Plugins[1]) && p.CorrespondsToKongService(Target.Services[0]))), Times.Never); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Target.GlobalConfig.Plugins[1]) && p.IsGlobal())), Times.Never); } protected void NoneOfThePluginsOfChangedOrDeletedRoutesAreUpserted() { GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Existing.Services[0].Routes[0].Plugins[0]) && p.CorrespondsToKongRoute(Existing.Services[0].Routes[0]))), Times.Never); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Existing.Services[0].Routes[0].Plugins[1]) && p.CorrespondsToKongRoute(Existing.Services[0].Routes[0]))), Times.Never); GetMock<IKongAdminWriter>().Verify(x => x.UpsertPlugin(It.Is<KongPlugin>(p => p.IsTheSameAs(Existing.Services[0].Routes[0].Plugins[2]) && p.CorrespondsToKongRoute(Existing.Services[0].Routes[0]))), Times.Never); } protected void TheRemovedPluginsAreDeleted() { GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(Existing.Services[0].Plugins[2].Id), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(Existing.Services[0].Routes[1].Plugins[2].Id), Times.Once); GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(Existing.GlobalConfig.Plugins[2].Id), Times.Once); } protected void NoneOfThePluginsOfDeletedServicesAreDeleted() => GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(Existing.Services[2].Plugins[0].Id), Times.Never); protected void NoneOfThePluginsOfChangedOrDeletedRoutesAreDeleted() { GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(Existing.Services[0].Routes[0].Plugins[0].Id), Times.Never); GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(Existing.Services[0].Routes[0].Plugins[1].Id), Times.Never); GetMock<IKongAdminWriter>().Verify(x => x.DeletePlugin(Existing.Services[0].Routes[0].Plugins[2].Id), Times.Never); } } }
45.48419
180
0.564501
[ "Apache-2.0" ]
slang25/kongverge
test/Kongverge.Tests/Workflow/KongvergeWorkflowScenarios.cs
23,015
C#
using System; using UnityEngine; public class ResidentObject : MonoBehaviour { private void Awake() { UnityEngine.Object.DontDestroyOnLoad(base.gameObject); } }
15.181818
56
0.772455
[ "MIT" ]
moto2002/wudihanghai
src/ResidentObject.cs
167
C#
// This file is part of the TA.Ascom.ReactiveCommunications project // // Copyright © 2015-2020 Tigra Astronomy, all rights reserved. // // 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. The Software comes with no warranty of any kind. // You make use of the Software entirely at your own risk and assume all liability arising from your use thereof. // // File: failed_transaction.cs Last modified: 2020-07-20@00:51 by Tim Long using System.Linq; using JetBrains.Annotations; using Machine.Specifications; namespace TA.Ascom.ReactiveCommunications.Specifications.Behaviours { [Behaviors] [UsedImplicitly] internal class failed_transaction : rxascom_behaviour { It should_have_a_reason_for_failure = () => Transaction.ErrorMessage.Any().ShouldBeTrue(); It should_have_correct_lifecycle_state = () => Transaction.State.ShouldEqual(TransactionLifecycle.Failed); It should_indicate_completed = () => Transaction.Completed.ShouldBeTrue(); It should_indicate_failed = () => Transaction.Failed.ShouldBeTrue(); It should_not_indicate_success = () => Transaction.Successful.ShouldBeFalse(); } }
52.62069
118
0.748362
[ "MIT" ]
KyleWorley/TA.ReactiveCommunications
TA.Ascom.ReactiveCommunications.Specifications/Behaviours/failed_transaction.cs
1,529
C#
using EngineeringUnits.Units; using Fractions; using Newtonsoft.Json; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace EngineeringUnits { public partial class AmountOfSubstance : BaseUnit { /// <summary> /// The Avogadro constant is the number of constituent particles, usually molecules, /// atoms or ions that are contained in the amount of substance given by one mole. It is the proportionality factor that relates /// the molar mass of a substance to the mass of a sample, is designated with the symbol NA or L[1], and has the value /// 6.02214076e23 mol−1 in the International System of Units (SI). /// </summary> /// <remarks> /// Pending revisions in the base set of SI units necessitated redefinitions of the concepts of chemical quantity. The Avogadro number, /// and its definition, was deprecated in favor of the Avogadro constant and its definition. Based on measurements made through the /// middle of 2017 which calculated a value for the Avogadro constant of NA = 6.022140758(62)×1023 mol−1, the redefinition of SI units /// is planned to take effect on 20 May 2019. The value of the constant will be fixed to exactly 6.02214076×1023 mol−1. /// See here: https://www.bipm.org/utils/common/pdf/CGPM-2018/26th-CGPM-Resolutions.pdf /// </remarks> public static double AvogadroConstant { get; } = 6.02214076e23; /// <summary> /// Calculates the number of particles (atoms or molecules) in this amount of substance using the <see cref="AvogadroConstant"/>. /// </summary> /// <returns>The number of particles (atoms or molecules) in this amount of substance.</returns> public double NumberOfParticles() { var moles = As(AmountOfSubstanceUnit.Mole); return AvogadroConstant * moles; } /// <summary>Get <see cref="AmountOfSubstance" /> from <see cref="Mass" /> and a given <see cref="MolarMass" />.</summary> public static AmountOfSubstance FromMass(Mass mass, MolarMass molarMass) { return mass / molarMass; } } }
45.28
147
0.659011
[ "MIT" ]
AtefeBahrani/EngineeringUnits
EngineeringUnits/BaseUnits/AmountOfSubstance/Amount.extra.cs
2,274
C#
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("ArchiveMonkey.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ArchiveMonkey.Services")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("656d2e6b-8b36-408a-a859-78926ced869d")] // 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")]
38.162162
84
0.75
[ "MIT" ]
STISource/ArchiveMonkey
ArchiveMonkey/ArchiveMonkey.Services/Properties/AssemblyInfo.cs
1,415
C#
/* Copyright(c) 2020-2021 Przemysław Łukawski 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 DotnetWebApiBench.ApiModel.Product.Request; using FluentValidation; namespace DotnetWebApiBench.Api.Validators.Product { public class AddProductRequestValidator : AbstractValidator<AddProductRequest> { public AddProductRequestValidator() { this.CascadeMode = CascadeMode.Stop; RuleFor(x => x.ProductName) .NotEmpty().WithMessage($"Field {nameof(AddProductRequest.ProductName)} cannot be empty.") .MaximumLength(8000).WithMessage($"Field {nameof(AddProductRequest.ProductName)} is too long."); RuleFor(x => x.CategoryId) .NotEmpty().WithMessage($"Field {nameof(AddProductRequest.CategoryId)} cannot be empty."); RuleFor(x => x.SupplierId) .NotEmpty().WithMessage($"Field {nameof(AddProductRequest.SupplierId)} cannot be empty."); } } }
42.782609
112
0.737297
[ "MIT" ]
plukawski/DWABench
src/DotnetWebApiBench.Api/Validators/Product/AddProductRequestValidator.cs
1,972
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System.Net.Http; using System.Threading; using Hl7.Fhir.ElementModel; using Hl7.Fhir.Model; using Hl7.Fhir.Serialization; using Microsoft.Health.Fhir.Core.Extensions; using Microsoft.Health.Fhir.Core.Features.Persistence; using Microsoft.Health.Fhir.Core.Features.Search.Parameters; using Microsoft.Health.Fhir.Core.Messages.Create; using Microsoft.Health.Fhir.Core.Messages.Delete; using Microsoft.Health.Fhir.Core.Messages.Upsert; using Microsoft.Health.Fhir.Core.Models; using Microsoft.Health.Fhir.Tests.Common; using NSubstitute; using Xunit; using Task = System.Threading.Tasks.Task; namespace Microsoft.Health.Fhir.Core.UnitTests.Features.Search { public class SearchParameterBehaviorTests { private readonly ISearchParameterOperations _searchParameterOperations = Substitute.For<ISearchParameterOperations>(); private readonly IRawResourceFactory _rawResourceFactory; private readonly IResourceWrapperFactory _resourceWrapperFactory; private readonly IFhirDataStore _fhirDataStore; public SearchParameterBehaviorTests() { _rawResourceFactory = Substitute.For<RawResourceFactory>(new FhirJsonSerializer()); _resourceWrapperFactory = Substitute.For<IResourceWrapperFactory>(); _resourceWrapperFactory .Create(Arg.Any<ResourceElement>(), Arg.Any<bool>(), Arg.Any<bool>()) .Returns(x => CreateResourceWrapper(x.ArgAt<ResourceElement>(0), x.ArgAt<bool>(1))); _fhirDataStore = Substitute.For<IFhirDataStore>(); } [Fact] public async Task GivenACreateResourceRequest_WhenCreatingAResourceOtherThanSearchParameter_ThenNoCallToAddParameterMade() { var resource = Samples.GetDefaultObservation().UpdateId("id1"); var request = new CreateResourceRequest(resource); var wrapper = CreateResourceWrapper(resource, false); var response = new UpsertResourceResponse(new SaveOutcome(new RawResourceElement(wrapper), SaveOutcomeType.Created)); var behavior = new CreateOrUpdateSearchParameterBehavior<CreateResourceRequest, UpsertResourceResponse>(_searchParameterOperations, _fhirDataStore); await behavior.Handle(request, CancellationToken.None, async () => await Task.Run(() => response)); // Ensure for non-SearchParameter, that we do not call Add SearchParameter await _searchParameterOperations.DidNotReceive().AddSearchParameterAsync(Arg.Any<ITypedElement>()); } [Fact] public async Task GivenACreateResourceRequest_WhenCreatingASearchParameterResource_ThenAddNewSearchParameterShouldBeCalled() { var searchParameter = new SearchParameter() { Id = "Id" }; var resource = searchParameter.ToTypedElement().ToResourceElement(); var request = new CreateResourceRequest(resource); var wrapper = CreateResourceWrapper(resource, false); var response = new UpsertResourceResponse(new SaveOutcome(new RawResourceElement(wrapper), SaveOutcomeType.Created)); var behavior = new CreateOrUpdateSearchParameterBehavior<CreateResourceRequest, UpsertResourceResponse>(_searchParameterOperations, _fhirDataStore); await behavior.Handle(request, CancellationToken.None, async () => await Task.Run(() => response)); await _searchParameterOperations.Received().AddSearchParameterAsync(Arg.Any<ITypedElement>()); } [Fact] public async Task GivenADeleteResourceRequest_WhenDeletingAResourceOtherThanSearchParameter_ThenNoCallToDeleteParameterMade() { var resource = Samples.GetDefaultObservation().UpdateId("id1"); var key = new ResourceKey("Observation", "id1"); var request = new DeleteResourceRequest(key, false); var wrapper = CreateResourceWrapper(resource, false); _fhirDataStore.GetAsync(key, Arg.Any<CancellationToken>()).Returns(wrapper); var response = new DeleteResourceResponse(key); var behavior = new DeleteSearchParameterBehavior<DeleteResourceRequest, DeleteResourceResponse>(_searchParameterOperations, _fhirDataStore); await behavior.Handle(request, CancellationToken.None, async () => await Task.Run(() => response)); // Ensure for non-SearchParameter, that we do not call Add SearchParameter await _searchParameterOperations.DidNotReceive().DeleteSearchParameterAsync(Arg.Any<RawResource>()); } [Fact] public async Task GivenADeleteResourceRequest_WhenDeletingASearchParameterResource_TheDeleteSearchParameterShouldBeCalled() { var searchParameter = new SearchParameter() { Id = "Id" }; var resource = searchParameter.ToTypedElement().ToResourceElement(); var key = new ResourceKey("SearchParameter", "Id"); var request = new DeleteResourceRequest(key, false); var wrapper = CreateResourceWrapper(resource, false); _fhirDataStore.GetAsync(key, Arg.Any<CancellationToken>()).Returns(wrapper); var response = new DeleteResourceResponse(key); var behavior = new DeleteSearchParameterBehavior<DeleteResourceRequest, DeleteResourceResponse>(_searchParameterOperations, _fhirDataStore); await behavior.Handle(request, CancellationToken.None, async () => await Task.Run(() => response)); await _searchParameterOperations.Received().DeleteSearchParameterAsync(Arg.Any<RawResource>()); } [Fact] public async Task GivenADeleteResourceRequest_WhenDeletingAnAlreadyDeletedSearchParameterResource_TheDeleteSearchParameterShouldNotBeCalled() { var searchParameter = new SearchParameter() { Id = "Id" }; var resource = searchParameter.ToTypedElement().ToResourceElement(); var key = new ResourceKey("SearchParameter", "Id"); var request = new DeleteResourceRequest(key, false); var wrapper = CreateResourceWrapper(resource, true); _fhirDataStore.GetAsync(key, Arg.Any<CancellationToken>()).Returns(wrapper); var response = new DeleteResourceResponse(key); var behavior = new DeleteSearchParameterBehavior<DeleteResourceRequest, DeleteResourceResponse>(_searchParameterOperations, _fhirDataStore); await behavior.Handle(request, CancellationToken.None, async () => await Task.Run(() => response)); await _searchParameterOperations.DidNotReceive().DeleteSearchParameterAsync(Arg.Any<RawResource>()); } private ResourceWrapper CreateResourceWrapper(ResourceElement resource, bool isDeleted) { return new ResourceWrapper( resource, _rawResourceFactory.Create(resource, keepMeta: true), new ResourceRequest(HttpMethod.Post, "http://fhir"), isDeleted, null, null, null, null); } } }
49.529801
160
0.687258
[ "MIT" ]
ConsensysHealth/fhir-server
src/Microsoft.Health.Fhir.Shared.Core.UnitTests/Features/Search/SearchParameters/SearchParameterBehaviorTests.cs
7,481
C#
using System; namespace Sharp.MySQL.Migrations.Attributes { /// <summary> /// Defines a property as AutoIncrement. Property MUST be INT and NotNull (see about TypeFieldBDAttribute to set as NotNull). /// </summary> [AttributeUsage(AttributeTargets.Property)] public class AutoIncrementAttribute : Attribute { } }
26.384615
129
0.71137
[ "MIT" ]
SharpSistemas/MigrationMySQL
Sharp.Migrations.MySQL/Attributes/AutoIncrementAttribute.cs
345
C#
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // 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.Generic; using System.Globalization; using ICSharpCode.NRefactory.Utils; namespace ICSharpCode.NRefactory.TypeSystem.Implementation { /// <summary> /// Default implementation of <see cref="IUnresolvedTypeParameter"/>. /// </summary> [Serializable] public class DefaultUnresolvedTypeParameter : IUnresolvedTypeParameter, IFreezable { readonly int index; IList<IUnresolvedAttribute> attributes; IList<ITypeReference> constraints; string name; DomRegion region; SymbolKind ownerType; VarianceModifier variance; BitVector16 flags; const ushort FlagFrozen = 0x0001; const ushort FlagReferenceTypeConstraint = 0x0002; const ushort FlagValueTypeConstraint = 0x0004; const ushort FlagDefaultConstructorConstraint = 0x0008; public void Freeze() { if (!flags[FlagFrozen]) { FreezeInternal(); flags[FlagFrozen] = true; } } protected virtual void FreezeInternal() { attributes = FreezableHelper.FreezeListAndElements(attributes); constraints = FreezableHelper.FreezeList(constraints); } public DefaultUnresolvedTypeParameter(SymbolKind ownerType, int index, string name = null) { this.ownerType = ownerType; this.index = index; this.name = name ?? ((ownerType == SymbolKind.Method ? "!!" : "!") + index.ToString(CultureInfo.InvariantCulture)); } public SymbolKind OwnerType { get { return ownerType; } } public int Index { get { return index; } } public bool IsFrozen { get { return flags[FlagFrozen]; } } public string Name { get { return name; } set { FreezableHelper.ThrowIfFrozen(this); name = value; } } string INamedElement.FullName { get { return name; } } string INamedElement.Namespace { get { return string.Empty; } } string INamedElement.ReflectionName { get { if (ownerType == SymbolKind.Method) return "``" + index.ToString(CultureInfo.InvariantCulture); else return "`" + index.ToString(CultureInfo.InvariantCulture); } } public IList<IUnresolvedAttribute> Attributes { get { if (attributes == null) attributes = new List<IUnresolvedAttribute>(); return attributes; } } public IList<ITypeReference> Constraints { get { if (constraints == null) constraints = new List<ITypeReference>(); return constraints; } } public VarianceModifier Variance { get { return variance; } set { FreezableHelper.ThrowIfFrozen(this); variance = value; } } public DomRegion Region { get { return region; } set { FreezableHelper.ThrowIfFrozen(this); region = value; } } public bool HasDefaultConstructorConstraint { get { return flags[FlagDefaultConstructorConstraint]; } set { FreezableHelper.ThrowIfFrozen(this); flags[FlagDefaultConstructorConstraint] = value; } } public bool HasReferenceTypeConstraint { get { return flags[FlagReferenceTypeConstraint]; } set { FreezableHelper.ThrowIfFrozen(this); flags[FlagReferenceTypeConstraint] = value; } } public bool HasValueTypeConstraint { get { return flags[FlagValueTypeConstraint]; } set { FreezableHelper.ThrowIfFrozen(this); flags[FlagValueTypeConstraint] = value; } } /// <summary> /// Uses the specified interning provider to intern /// strings and lists in this entity. /// This method does not test arbitrary objects to see if they implement ISupportsInterning; /// instead we assume that those are interned immediately when they are created (before they are added to this entity). /// </summary> public virtual void ApplyInterningProvider(InterningProvider provider) { if (provider == null) throw new ArgumentNullException("provider"); FreezableHelper.ThrowIfFrozen(this); name = provider.Intern(name); attributes = provider.InternList(attributes); constraints = provider.InternList(constraints); } public virtual ITypeParameter CreateResolvedTypeParameter(ITypeResolveContext context) { IEntity owner = null; if (this.OwnerType == SymbolKind.Method) { owner = context.CurrentMember as IMethod; } else if (this.OwnerType == SymbolKind.TypeDefinition) { owner = context.CurrentTypeDefinition; } if (owner == null) throw new InvalidOperationException("Could not determine the type parameter's owner."); return new DefaultTypeParameter( owner, index, name, variance, this.Attributes.CreateResolvedAttributes(context), this.Region, this.HasValueTypeConstraint, this.HasReferenceTypeConstraint, this.HasDefaultConstructorConstraint, this.Constraints.Resolve(context) ); } } }
30.2
137
0.717439
[ "MIT" ]
376730969/ILSpy
NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedTypeParameter.cs
5,891
C#
//========================================================================================== // // OpenNETCF.Windows.Forms.Cipher // Copyright (c) 2003, OpenNETCF.org // // This library is free software; you can redistribute it and/or modify it under // the terms of the OpenNETCF.org Shared Source License. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License // for more details. // // You should have received a copy of the OpenNETCF.org Shared Source License // along with this library; if not, email licensing@opennetcf.org to request a copy. // // If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please // email licensing@opennetcf.org. // // For general enquiries, email enquiries@opennetcf.org or visit our website at: // http://www.opennetcf.org // // !!! A HUGE thank-you goes out to Casey Chesnut for supplying this class library !!! // !!! You can contact Casey at http://www.brains-n-brawn.com !!! // //========================================================================================== using System; using System.Text; using System.Runtime.InteropServices; namespace FlickrNet.Security.Cryptography.NativeMethods { internal class Cipher { public static byte [] Encrypt(IntPtr key, IntPtr hash, byte [] data) { bool final = true; uint flags = 0; uint dataLen = (uint) data.Length; //int blockSize = Key.GetBlockSize(key) / 8; //blockSize = Math.Min(blockSize, data.Length); uint bufLen = (uint) data.Length; //encrypted data could be larger - 1 block? //uint bufLen = (uint) (data.Length + blockSize); byte [] encData = new byte[bufLen]; Array.Copy(data, 0, encData, 0, data.Length); bool retVal = Crypto.CryptEncrypt(key, hash, final, flags, encData, ref dataLen, bufLen); ErrCode ec = Error.HandleRetVal(retVal, ErrCode.MORE_DATA); if(ec == ErrCode.MORE_DATA) { bufLen = dataLen; dataLen = (uint) data.Length; encData = new byte[bufLen]; Buffer.BlockCopy(data, 0, encData, 0, data.Length); retVal = Crypto.CryptEncrypt(key, hash, final, flags, encData, ref dataLen, bufLen); ec = Error.HandleRetVal(retVal); } retVal = Format.CompareBytes(data, encData); if(retVal == true) //same throw new Exception("data was not encrypted"); //Format.HiddenBytes(data, encData); //catch nullKey encryption return encData; } public static byte[] Decrypt(IntPtr key, IntPtr hash, byte[] data) { byte [] ciphData = (byte []) data.Clone(); byte [] clearData; bool final = true; uint flags = 0; uint dataLen = (uint) data.Length; bool retVal = Crypto.CryptDecrypt(key, hash, final, flags, ciphData, ref dataLen); ErrCode ec = Error.HandleRetVal(retVal); clearData = new byte[dataLen]; Buffer.BlockCopy(ciphData, 0, clearData, 0, (int) dataLen); return clearData; } public static byte [] ProtectData(byte [] plainIn) { byte [] cipherBa = ProtectData(plainIn, ProtectParam.UI_FORBIDDEN, null); if(cipherBa.Length == plainIn.Length) throw new Exception("data was not protected"); return cipherBa; } public static byte [] UnprotectData(byte [] cipherIn) { string outStr = null; byte [] plainBa = UnprotectData(cipherIn, ProtectParam.UI_FORBIDDEN, out outStr); if(plainBa.Length == cipherIn.Length) throw new Exception("data was not unprotected"); return plainBa; } //http://www.obviex.com/samples/dpapi.aspx //http://msdn.microsoft.com/security/securecode/dotnet/default.aspx?pull=/library/en-us/dnnetsec/html/SecNetHT07.asp public static byte [] ProtectData(byte [] plainIn, ProtectParam flags, string desc) { StringBuilder sb = new StringBuilder(desc); CRYPTOAPI_BLOB blobIn = new CRYPTOAPI_BLOB(); byte [] cipherOut; try { blobIn.cbData = plainIn.Length; //blobIn.pbData = plainIn; //byte[] //blobIn.pbData = Mem.AllocHGlobal(blobIn.cbData); blobIn.pbData = Mem.CryptMemAlloc(blobIn.cbData); Marshal.Copy(plainIn, 0, blobIn.pbData, blobIn.cbData); IntPtr optEntropy = IntPtr.Zero; //CRYPTOAPI_BLOB* IntPtr reserved = IntPtr.Zero; //PVOID IntPtr prompt = IntPtr.Zero; //CRYPTPROTECT_PROMPTSTRUCT* CRYPTOAPI_BLOB dataOut = new CRYPTOAPI_BLOB(); bool retVal = Crypto.CryptProtectData(ref blobIn, sb, optEntropy, reserved, prompt, (uint) flags, ref dataOut); ErrCode ec = Error.HandleRetVal(retVal); cipherOut = new byte[dataOut.cbData]; Marshal.Copy(dataOut.pbData, cipherOut, 0, dataOut.cbData); //Mem.FreeHGlobal(dataOut.pbData); Mem.CryptMemFree(dataOut.pbData); } catch(Exception ex) { throw ex; } finally { if (blobIn.pbData != IntPtr.Zero) { //Mem.FreeHGlobal(blobIn.pbData); Mem.CryptMemFree(blobIn.pbData); } } return cipherOut; } //http://www.obviex.com/samples/dpapi.aspx //http://msdn.microsoft.com/security/securecode/dotnet/default.aspx?pull=/library/en-us/dnnetsec/html/SecNetHT07.asp public static byte [] UnprotectData(byte [] cipherIn, ProtectParam flags, out string desc) { desc =null; StringBuilder sb = new StringBuilder(); //TODO not returning properly CRYPTOAPI_BLOB blobIn = new CRYPTOAPI_BLOB(); byte [] plainOut; try { blobIn.cbData = cipherIn.Length; //blobIn.pbData = cipherIn; //byte[] //blobIn.pbData = Mem.AllocHGlobal(blobIn.cbData); blobIn.pbData = Mem.CryptMemAlloc(blobIn.cbData); Marshal.Copy(cipherIn, 0, blobIn.pbData, blobIn.cbData); IntPtr optEntropy = IntPtr.Zero; //CRYPTOAPI_BLOB* IntPtr reserved = IntPtr.Zero; //PVOID IntPtr prompt = IntPtr.Zero; //CRYPTPROTECT_PROMPTSTRUCT* CRYPTOAPI_BLOB dataOut = new CRYPTOAPI_BLOB(); //BUG //bool retVal = Crypto.CryptUnprotectData(ref blobIn, sb, optEntropy, reserved, prompt, (uint) flags, ref dataOut); //desc = sb.ToString(); //Assuming a max size of 99 characters in the description null terminating character IntPtr ppszDescription = Mem.CryptMemAlloc(100); bool retVal = Crypto.CryptUnprotectData(ref blobIn, ref ppszDescription, optEntropy, reserved, prompt, (uint) flags, ref dataOut); desc = Marshal.PtrToStringUni(ppszDescription); Mem.CryptMemFree(ppszDescription); ErrCode ec = Error.HandleRetVal(retVal); plainOut = new byte[dataOut.cbData]; Marshal.Copy(dataOut.pbData, plainOut, 0, dataOut.cbData); //Mem.FreeHGlobal(dataOut.pbData); Mem.CryptMemFree(dataOut.pbData); } catch(Exception ex) { throw ex; } finally { if (blobIn.pbData != IntPtr.Zero) { //Mem.FreeHGlobal(blobIn.pbData); Mem.CryptMemFree(blobIn.pbData); } } return plainOut; } } }
35.476923
134
0.671726
[ "Unlicense" ]
jjxtra/FlickrDownloader
FlickrNet/OpenCF/Cipher.cs
6,918
C#
//Copyright (c) 2018 Yardi Technology Limited. Http://www.kooboo.com //All rights reserved. using Kooboo.Data.Interface; using Kooboo.Extensions; using System; using System.Security.Cryptography; namespace Kooboo.Sites.Models { [Kooboo.Attributes.Diskable(Kooboo.Attributes.DiskType.Binary)] [Kooboo.Attributes.Routable] public class CmsFile : CoreObject, IBinaryFile, IExtensionable { public CmsFile() { this.ConstType = ConstObjectType.CmsFile; } private Guid _id; public override Guid Id { set { _id = value; } get { if (_id == default(Guid)) { _id = Kooboo.Data.IDGenerator.GetNewGuid(); } return _id; } } [Kooboo.Attributes.SummaryIgnore] public string Extension { get; set; } /// <summary> /// the content bytes of this file. /// </summary> [Kooboo.Attributes.SummaryIgnore] public byte[] ContentBytes { get; set; } /// <summary> /// this is for some file like text file, etc... /// </summary> public string ContentString { get; set; } /// <summary> /// The content type of this file. like. application/flash. /// This is often used to save original content type saved from other location. /// </summary> public string ContentType { get; set; } private int _size; public int Size { get { if (_size == default(int)) { if (ContentBytes != null) { _size = ContentBytes.Length; } } return _size; } set { _size = value; } } public override int GetHashCode() { string uniquestring = this.Extension + this.Name; if (this.ContentBytes != null) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(ContentBytes); uniquestring += System.Text.Encoding.ASCII.GetString(data); } return Lib.Security.Hash.ComputeIntCaseSensitive(uniquestring); } } }
26.933333
88
0.500413
[ "MIT" ]
VZhiLinCorp/Kooboo
Kooboo.Sites/Models/CmsFile.cs
2,424
C#
using System.Collections.Generic; /* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace org.camunda.bpm.engine.rest.helper { using ArgumentMatcher = org.mockito.ArgumentMatcher; public class EqualsList : ArgumentMatcher<IList<string>> { private IList<string> listToCompare; public EqualsList(IList<string> listToCompare) { this.listToCompare = listToCompare; } public override bool matches(object list) { if ((list == null && listToCompare != null) || (list != null && listToCompare == null)) { return false; } if (list == null && listToCompare == null) { return true; } IList<string> argumentList = (IList<string>) list; ISet<string> setToCompare = new HashSet<string>(listToCompare); ISet<string> argumentSet = new HashSet<string>(argumentList); return setToCompare.SetEquals(argumentSet); } } }
29.089286
89
0.731123
[ "Apache-2.0" ]
luizfbicalho/Camunda.NET
camunda-bpm-platform-net/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsList.cs
1,631
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/dwmapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="UNSIGNED_RATIO" /> struct.</summary> public static unsafe class UNSIGNED_RATIOTests { /// <summary>Validates that the <see cref="UNSIGNED_RATIO" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<UNSIGNED_RATIO>(), Is.EqualTo(sizeof(UNSIGNED_RATIO))); } /// <summary>Validates that the <see cref="UNSIGNED_RATIO" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(UNSIGNED_RATIO).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="UNSIGNED_RATIO" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(UNSIGNED_RATIO), Is.EqualTo(8)); } } }
37.777778
145
0.663971
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/dwmapi/UNSIGNED_RATIOTests.cs
1,362
C#
// 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.Diagnostics; using System.Text; using Microsoft.AspNetCore.Cryptography.Cng; using Microsoft.AspNetCore.Cryptography.SafeHandles; namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2 { /// <summary> /// A PBKDF2 provider which utilizes the Win7 API BCryptDeriveKeyPBKDF2. /// </summary> internal sealed unsafe class Win7Pbkdf2Provider : IPbkdf2Provider { public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested) { Debug.Assert(password != null); Debug.Assert(salt != null); Debug.Assert(iterationCount > 0); Debug.Assert(numBytesRequested > 0); byte dummy; // CLR doesn't like pinning zero-length buffers, so this provides a valid memory address when working with zero-length buffers // Don't dispose of this algorithm instance; it is cached and reused! var algHandle = PrfToCachedCngAlgorithmInstance(prf); // Convert password string to bytes. // Allocate on the stack whenever we can to save allocations. int cbPasswordBuffer = Encoding.UTF8.GetMaxByteCount(password.Length); fixed (byte* pbHeapAllocatedPasswordBuffer = (cbPasswordBuffer > Constants.MAX_STACKALLOC_BYTES) ? new byte[cbPasswordBuffer] : null) { byte* pbPasswordBuffer = pbHeapAllocatedPasswordBuffer; if (pbPasswordBuffer == null) { if (cbPasswordBuffer == 0) { pbPasswordBuffer = &dummy; } else { byte* pbStackAllocPasswordBuffer = stackalloc byte[cbPasswordBuffer]; // will be released when the frame unwinds pbPasswordBuffer = pbStackAllocPasswordBuffer; } } try { int cbPasswordBufferUsed; // we're not filling the entire buffer, just a partial buffer fixed (char* pszPassword = password) { cbPasswordBufferUsed = Encoding.UTF8.GetBytes(pszPassword, password.Length, pbPasswordBuffer, cbPasswordBuffer); } fixed (byte* pbHeapAllocatedSalt = salt) { byte* pbSalt = (pbHeapAllocatedSalt != null) ? pbHeapAllocatedSalt : &dummy; byte[] retVal = new byte[numBytesRequested]; fixed (byte* pbRetVal = retVal) { int ntstatus = UnsafeNativeMethods.BCryptDeriveKeyPBKDF2( hPrf: algHandle, pbPassword: pbPasswordBuffer, cbPassword: (uint)cbPasswordBufferUsed, pbSalt: pbSalt, cbSalt: (uint)salt.Length, cIterations: (ulong)iterationCount, pbDerivedKey: pbRetVal, cbDerivedKey: (uint)retVal.Length, dwFlags: 0); UnsafeNativeMethods.ThrowExceptionForBCryptStatus(ntstatus); } return retVal; } } finally { UnsafeBufferUtil.SecureZeroMemory(pbPasswordBuffer, cbPasswordBuffer); } } } private static BCryptAlgorithmHandle PrfToCachedCngAlgorithmInstance(KeyDerivationPrf prf) { switch (prf) { case KeyDerivationPrf.HMACSHA1: return CachedAlgorithmHandles.HMAC_SHA1; case KeyDerivationPrf.HMACSHA256: return CachedAlgorithmHandles.HMAC_SHA256; case KeyDerivationPrf.HMACSHA512: return CachedAlgorithmHandles.HMAC_SHA512; default: throw CryptoUtil.Fail("Unrecognized PRF."); } } } }
44.039604
150
0.542716
[ "Apache-2.0" ]
Asifshikder/aspnetcore
src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs
4,448
C#
using System; using BEPUphysics.CollisionTests.CollisionAlgorithms; using BEPUutilities; using BEPUphysics.Settings; using FixMath.NET; namespace BEPUphysics.CollisionShapes.ConvexShapes { ///<summary> /// Superclass of convex collision shapes. ///</summary> public abstract class ConvexShape : EntityShape { protected void UpdateConvexShapeInfo(ConvexShapeDescription description) { UpdateEntityShapeVolume(description.EntityShapeVolume); MinimumRadius = description.MinimumRadius; MaximumRadius = description.MaximumRadius; collisionMargin = description.CollisionMargin; } protected internal Fix64 collisionMargin = CollisionDetectionSettings.DefaultMargin; ///<summary> /// Collision margin of the convex shape. The margin is a small spherical expansion around /// entities which allows specialized collision detection algorithms to be used. /// It's recommended that this be left unchanged. ///</summary> public Fix64 CollisionMargin { get { return collisionMargin; } set { if (value < F64.C0) throw new ArgumentException("Collision margin must be nonnegative.."); collisionMargin = value; OnShapeChanged(); } } /// <summary> /// Gets or sets the minimum radius of the collidable's shape. This is initialized to a value that is /// guaranteed to be equal to or smaller than the actual minimum radius. When setting this property, /// ensure that the inner sphere formed by the new minimum radius is fully contained within the shape. /// </summary> public Fix64 MinimumRadius { get; internal set; } /// <summary> /// Gets the maximum radius of the collidable's shape. This is initialized to a value that is /// guaranteed to be equal to or larger than the actual maximum radius. /// </summary> public Fix64 MaximumRadius { get; internal set; } ///<summary> /// Gets the extreme point of the shape in local space in a given direction. ///</summary> ///<param name="direction">Direction to find the extreme point in.</param> ///<param name="extremePoint">Extreme point on the shape.</param> public abstract void GetLocalExtremePointWithoutMargin(ref Vector3 direction, out Vector3 extremePoint); ///<summary> /// Gets the extreme point of the shape in world space in a given direction. ///</summary> ///<param name="direction">Direction to find the extreme point in.</param> /// <param name="shapeTransform">Transform to use for the shape.</param> ///<param name="extremePoint">Extreme point on the shape.</param> public void GetExtremePointWithoutMargin(Vector3 direction, ref RigidTransform shapeTransform, out Vector3 extremePoint) { Quaternion conjugate; Quaternion.Conjugate(ref shapeTransform.Orientation, out conjugate); Quaternion.Transform(ref direction, ref conjugate, out direction); GetLocalExtremePointWithoutMargin(ref direction, out extremePoint); Quaternion.Transform(ref extremePoint, ref shapeTransform.Orientation, out extremePoint); Vector3.Add(ref extremePoint, ref shapeTransform.Position, out extremePoint); } ///<summary> /// Gets the extreme point of the shape in world space in a given direction with margin expansion. ///</summary> ///<param name="direction">Direction to find the extreme point in.</param> /// <param name="shapeTransform">Transform to use for the shape.</param> ///<param name="extremePoint">Extreme point on the shape.</param> public void GetExtremePoint(Vector3 direction, ref RigidTransform shapeTransform, out Vector3 extremePoint) { GetExtremePointWithoutMargin(direction, ref shapeTransform, out extremePoint); Fix64 directionLength = direction.LengthSquared(); if (directionLength > Toolbox.Epsilon) { Vector3.Multiply(ref direction, collisionMargin / Fix64.Sqrt(directionLength), out direction); Vector3.Add(ref extremePoint, ref direction, out extremePoint); } } ///<summary> /// Gets the extreme point of the shape in local space in a given direction with margin expansion. ///</summary> ///<param name="direction">Direction to find the extreme point in.</param> ///<param name="extremePoint">Extreme point on the shape.</param> public void GetLocalExtremePoint(Vector3 direction, out Vector3 extremePoint) { GetLocalExtremePointWithoutMargin(ref direction, out extremePoint); Fix64 directionLength = direction.LengthSquared(); if (directionLength > Toolbox.Epsilon) { Vector3.Multiply(ref direction, collisionMargin / Fix64.Sqrt(directionLength), out direction); Vector3.Add(ref extremePoint, ref direction, out extremePoint); } } /// <summary> /// Gets the bounding box of the shape given a transform. /// </summary> /// <param name="shapeTransform">Transform to use.</param> /// <param name="boundingBox">Bounding box of the transformed shape.</param> public override void GetBoundingBox(ref RigidTransform shapeTransform, out BoundingBox boundingBox) { #if !WINDOWS boundingBox = new BoundingBox(); #endif Matrix3x3 o; Matrix3x3.CreateFromQuaternion(ref shapeTransform.Orientation, out o); //Sample the local directions from the orientation matrix, implicitly transposed. Vector3 right; var direction = new Vector3(o.M11, o.M21, o.M31); GetLocalExtremePointWithoutMargin(ref direction, out right); Vector3 left; direction = new Vector3(-o.M11, -o.M21, -o.M31); GetLocalExtremePointWithoutMargin(ref direction, out left); Vector3 up; direction = new Vector3(o.M12, o.M22, o.M32); GetLocalExtremePointWithoutMargin(ref direction, out up); Vector3 down; direction = new Vector3(-o.M12, -o.M22, -o.M32); GetLocalExtremePointWithoutMargin(ref direction, out down); Vector3 backward; direction = new Vector3(o.M13, o.M23, o.M33); GetLocalExtremePointWithoutMargin(ref direction, out backward); Vector3 forward; direction = new Vector3(-o.M13, -o.M23, -o.M33); GetLocalExtremePointWithoutMargin(ref direction, out forward); //Rather than transforming each axis independently (and doing three times as many operations as required), just get the 6 required values directly. Vector3 positive, negative; TransformLocalExtremePoints(ref right, ref up, ref backward, ref o, out positive); TransformLocalExtremePoints(ref left, ref down, ref forward, ref o, out negative); //The positive and negative vectors represent the X, Y and Z coordinates of the extreme points in world space along the world space axes. boundingBox.Max.X = shapeTransform.Position.X + positive.X + collisionMargin; boundingBox.Max.Y = shapeTransform.Position.Y + positive.Y + collisionMargin; boundingBox.Max.Z = shapeTransform.Position.Z + positive.Z + collisionMargin; boundingBox.Min.X = shapeTransform.Position.X + negative.X - collisionMargin; boundingBox.Min.Y = shapeTransform.Position.Y + negative.Y - collisionMargin; boundingBox.Min.Z = shapeTransform.Position.Z + negative.Z - collisionMargin; } /// <summary> /// Gets the intersection between the convex shape and the ray. /// </summary> /// <param name="ray">Ray to test.</param> /// <param name="transform">Transform of the convex shape.</param> /// <param name="maximumLength">Maximum distance to travel in units of the ray direction's length.</param> /// <param name="hit">Ray hit data, if any.</param> /// <returns>Whether or not the ray hit the target.</returns> public virtual bool RayTest(ref Ray ray, ref RigidTransform transform, Fix64 maximumLength, out RayHit hit) { return MPRToolbox.RayCast(ray, maximumLength, this, ref transform, out hit); } /// <summary> /// Computes a bounding box for the shape and expands it. /// </summary> /// <param name="transform">Transform to use to position the shape.</param> /// <param name="sweep">Extra to add to the bounding box.</param> /// <param name="boundingBox">Expanded bounding box.</param> public void GetSweptBoundingBox(ref RigidTransform transform, ref Vector3 sweep, out BoundingBox boundingBox) { GetBoundingBox(ref transform, out boundingBox); Toolbox.ExpandBoundingBox(ref boundingBox, ref sweep); } /// <summary> /// Gets the bounding box of the convex shape transformed first into world space, and then into the local space of another affine transform. /// </summary> /// <param name="shapeTransform">Transform to use to put the shape into world space.</param> /// <param name="spaceTransform">Used as the frame of reference to compute the bounding box. /// In effect, the shape is transformed by the inverse of the space transform to compute its bounding box in local space.</param> /// <param name="sweep">Vector to expand the bounding box with in local space.</param> /// <param name="boundingBox">Bounding box in the local space.</param> public void GetSweptLocalBoundingBox(ref RigidTransform shapeTransform, ref AffineTransform spaceTransform, ref Vector3 sweep, out BoundingBox boundingBox) { GetLocalBoundingBox(ref shapeTransform, ref spaceTransform, out boundingBox); Vector3 expansion; Matrix3x3.TransformTranspose(ref sweep, ref spaceTransform.LinearTransform, out expansion); Toolbox.ExpandBoundingBox(ref boundingBox, ref expansion); } //Transform the convex into the space of something else. /// <summary> /// Gets the bounding box of the convex shape transformed first into world space, and then into the local space of another affine transform. /// </summary> /// <param name="shapeTransform">Transform to use to put the shape into world space.</param> /// <param name="spaceTransform">Used as the frame of reference to compute the bounding box. /// In effect, the shape is transformed by the inverse of the space transform to compute its bounding box in local space.</param> /// <param name="boundingBox">Bounding box in the local space.</param> public void GetLocalBoundingBox(ref RigidTransform shapeTransform, ref AffineTransform spaceTransform, out BoundingBox boundingBox) { #if !WINDOWS boundingBox = new BoundingBox(); #endif //TODO: This method peforms quite a few sqrts because the collision margin can get scaled, and so cannot be applied as a final step. //There should be a better way to do this. At the very least, it should be possible to avoid the 6 square roots involved currently. //If this shows a a bottleneck, it might be best to virtualize this function and implement a per-shape variant. //Also... It might be better just to have the internal function be a GetBoundingBox that takes an AffineTransform, and an outer function //does the local space fiddling. //Move forward into convex's space, backwards into the new space's local space. AffineTransform transform; AffineTransform.Invert(ref spaceTransform, out transform); AffineTransform.Multiply(ref shapeTransform, ref transform, out transform); //Sample the local directions from the orientation matrix, implicitly transposed. Vector3 right; var direction = new Vector3(transform.LinearTransform.M11, transform.LinearTransform.M21, transform.LinearTransform.M31); GetLocalExtremePoint(direction, out right); Vector3 left; direction = new Vector3(-transform.LinearTransform.M11, -transform.LinearTransform.M21, -transform.LinearTransform.M31); GetLocalExtremePoint(direction, out left); Vector3 up; direction = new Vector3(transform.LinearTransform.M12, transform.LinearTransform.M22, transform.LinearTransform.M32); GetLocalExtremePoint(direction, out up); Vector3 down; direction = new Vector3(-transform.LinearTransform.M12, -transform.LinearTransform.M22, -transform.LinearTransform.M32); GetLocalExtremePoint(direction, out down); Vector3 backward; direction = new Vector3(transform.LinearTransform.M13, transform.LinearTransform.M23, transform.LinearTransform.M33); GetLocalExtremePoint(direction, out backward); Vector3 forward; direction = new Vector3(-transform.LinearTransform.M13, -transform.LinearTransform.M23, -transform.LinearTransform.M33); GetLocalExtremePoint(direction, out forward); //Rather than transforming each axis independently (and doing three times as many operations as required), just get the 6 required values directly. Vector3 positive, negative; TransformLocalExtremePoints(ref right, ref up, ref backward, ref transform.LinearTransform, out positive); TransformLocalExtremePoints(ref left, ref down, ref forward, ref transform.LinearTransform, out negative); //The positive and negative vectors represent the X, Y and Z coordinates of the extreme points in world space along the world space axes. boundingBox.Max.X = transform.Translation.X + positive.X; boundingBox.Max.Y = transform.Translation.Y + positive.Y; boundingBox.Max.Z = transform.Translation.Z + positive.Z; boundingBox.Min.X = transform.Translation.X + negative.X; boundingBox.Min.Y = transform.Translation.Y + negative.Y; boundingBox.Min.Z = transform.Translation.Z + negative.Z; } } }
51.555944
163
0.662937
[ "MIT" ]
XingHong/SimpleLockStepClient
Assets/Engine.LockstepEngine/Src/BepuPhysicsEngine/BEPUphysics/CollisionShapes/ConvexShapes/ConvexShape.cs
14,747
C#
using Eventinars.Application.Features.Products.Commands.AddEdit; using Eventinars.Application.Features.Products.Commands.Delete; using Eventinars.Application.Features.Products.Queries.Export; using Eventinars.Application.Features.Products.Queries.GetAllPaged; using Eventinars.Application.Features.Products.Queries.GetProductImage; using Eventinars.Shared.Constants.Permission; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Eventinars.Server.Controllers.v1.Catalog { public class ProductsController : BaseApiController<ProductsController> { /// <summary> /// Get All Products /// </summary> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <param name="searchString"></param> /// <param name="orderBy"></param> /// <returns>Status 200 OK</returns> [Authorize(Policy = Permissions.Products.View)] [HttpGet] public async Task<IActionResult> GetAll(int pageNumber, int pageSize, string searchString, string orderBy = null) { var products = await _mediator.Send(new GetAllProductsQuery(pageNumber, pageSize, searchString, orderBy)); return Ok(products); } /// <summary> /// Get a Product Image by Id /// </summary> /// <param name="id"></param> /// <returns>Status 200 OK</returns> [Authorize(Policy = Permissions.Products.View)] [HttpGet("image/{id}")] public async Task<IActionResult> GetProductImageAsync(int id) { var result = await _mediator.Send(new GetProductImageQuery(id)); return Ok(result); } /// <summary> /// Add/Edit a Product /// </summary> /// <param name="command"></param> /// <returns>Status 200 OK</returns> [Authorize(Policy = Permissions.Products.Create)] [HttpPost] public async Task<IActionResult> Post(AddEditProductCommand command) { return Ok(await _mediator.Send(command)); } /// <summary> /// Delete a Product /// </summary> /// <param name="id"></param> /// <returns>Status 200 OK response</returns> [Authorize(Policy = Permissions.Products.Delete)] [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { return Ok(await _mediator.Send(new DeleteProductCommand { Id = id })); } /// <summary> /// Search Products and Export to Excel /// </summary> /// <param name="searchString"></param> /// <returns>Status 200 OK</returns> [Authorize(Policy = Permissions.Products.Export)] [HttpGet("export")] public async Task<IActionResult> Export(string searchString = "") { return Ok(await _mediator.Send(new ExportProductsQuery(searchString))); } } }
37.55
121
0.619507
[ "MIT" ]
justSteve/Eventinars
src/Server/Controllers/v1/Catalog/ProductsController.cs
3,006
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using StardewValley.Menus; namespace DeluxeJournal.Menus { public interface IPage { const int TabRegion = 9500; /// <summary>A wrapper for the IClickableMenu.allClickableComponents (or equivalent) field.</summary> List<ClickableComponent> AllClickableComponents { get; } /// <summary>Hover text to be displayed by the parent DeluxeJournalMenu.</summary> string HoverText { get; } /// <summary>ID value for the tab ClickableComponent.</summary> int TabComponentID => TabID + TabRegion; /// <summary>Tab ID value assigned by the page manager (this value is set immediately AFTER construction).</summary> int TabID { get; set; } /// <summary>Get the ClickableTextureComponent for the page tab.</summary> ClickableTextureComponent GetTabComponent(); /// <summary>Called when the page becomes visible and active.</summary> void OnVisible(); /// <summary>Called when the page is hidden and no longer active.</summary> void OnHidden(); /// <summary>Returns true if keyboard input should be ignored by the parent DeluxeJournalMenu.</summary> bool KeyboardHasFocus(); /// <summary>Returns true if all input should be ignored by the parent DeluxeJournalMenu.</summary> bool ChildHasFocus(); // --- // Methods below are provided by StardewValley.Menus.IClickableMenu // --- void populateClickableComponentList(); ClickableComponent getCurrentlySnappedComponent(); void setCurrentlySnappedComponentTo(int id); void automaticSnapBehavior(int direction, int oldRegion, int oldID); void snapToDefaultClickableComponent(); void snapCursorToCurrentSnappedComponent(); void receiveGamePadButton(Buttons b); void setUpForGamePadMode(); void receiveLeftClick(int x, int y, bool playSound = true); void leftClickHeld(int x, int y); void releaseLeftClick(int x, int y); void receiveRightClick(int x, int y, bool playSound = true); void receiveScrollWheelAction(int direction); void receiveKeyPress(Keys key); void performHoverAction(int x, int y); bool readyToClose(); bool shouldDrawCloseButton(); void update(GameTime time); void draw(SpriteBatch b); } }
30.658537
124
0.672633
[ "MIT" ]
MolsonCAD/DeluxeJournal
src/Menus/IPage.cs
2,516
C#
using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.WebUtilities; using Store.Contracts.V1; using Store.Contracts.V1.Responses; using Store.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Store.Helpers { public class PaginationHelper { public static PageResponse<T> CreateResponse<T>(PaginationFilter paginationFilter,IEnumerable<T> data,HttpContext httpContext,string url) { var response = new PageResponse<T>(data); var absoluteUri = string.Concat(httpContext.Request.Scheme, "://", httpContext.Request.Host.ToUriComponent(), "/"); var previosPage = QueryHelpers.AddQueryString(absoluteUri + url, "pageNumber", (paginationFilter.PageNumber - 1).ToString()); previosPage = QueryHelpers.AddQueryString(previosPage, "pageSize", (paginationFilter.PageSize).ToString()); var nextPage = QueryHelpers.AddQueryString(absoluteUri + url, "pageNumber", (paginationFilter.PageNumber + 1).ToString()); nextPage = QueryHelpers.AddQueryString(nextPage, "pageSize", (paginationFilter.PageSize).ToString()); response.PreviousPage = paginationFilter.PageNumber > 1 ? previosPage : null; response.NextPage = data.Any() ? nextPage : null; return response; } } }
46.1
145
0.712943
[ "MIT" ]
Remigiusz-Ruszkiewicz/Store-masterv3
Store/Helpers/PaginationHelper.cs
1,385
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.CodeFirst { using System.Linq.Expressions; using Xunit; public class CodePlex2846Mapping : TestBase { public class BaseClass { public int Id { get; set; } } public class Derived : BaseClass { } public class ContextWithDerivedEntity : DbContext { static ContextWithDerivedEntity() { Database.SetInitializer<ContextWithDerivedEntity>(null); } public DbSet<Derived> Deriveds { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Derived>() .HasKey(CreateExpressionWithExtraConvertExplicitly<Derived>()); } } public static Expression<Func<TType, int>> CreateExpressionWithExtraConvertExplicitly<TType>() where TType : BaseClass { var param = Expression.Parameter(typeof(TType), "u"); var body = Expression.MakeMemberAccess(Expression.Convert(param, typeof(BaseClass)), typeof(TType).GetMember("Id")[0]); var ex = Expression.Lambda<Func<TType, int>>(body, param); return ex; } /// <summary> /// In the roslyn 1.1 compiler this expression will be emitted as u => Convert(u).Id because u refers to a /// type parameter. Convert's Type property will be BaseClass (the limit type of TType). /// </summary> /// <typeparam name="TType"></typeparam> /// <returns></returns> public static Expression<Func<TType, int>> CreateExpressionWithExtraConvertInRoslyn11<TType>() where TType : BaseClass { return u => u.Id; } [Fact] public void Can_map_expression_with_extra_convert_in_expression() { Assert.DoesNotThrow( () => { using (var context = new ContextWithDerivedEntity()) { Assert.NotNull(context.Deriveds.ToString()); } } ); } } }
33.797101
133
0.569468
[ "Apache-2.0" ]
staff0rd/EntityFramework6-beta8
test/EntityFramework/FunctionalTests/CodeFirst/CodePlex2846Mapping.cs
2,334
C#
/* * MIT License * * Copyright (c) 2018 Clark Yang * * 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; namespace Loxodon.Framework.Prefs { public class VersionTypeEncoder : ITypeEncoder { private int priority = 999; public int Priority { get { return this.priority; } set { this.priority = value; } } public bool IsSupport(Type type) { if (type.Equals(typeof(Version))) return true; return false; } public object Decode(Type type, string value) { if (string.IsNullOrEmpty(value)) return null; return new Version(value); } public string Encode(object value) { return ((Version)value).ToString(); } } }
30.629032
86
0.654028
[ "MIT" ]
AsimKhan2019/Loxodon-Framework-MVVM
Assets/LoxodonFramework/Scripts/Framework/Prefs/TypeEncoder/VersionTypeEncoder.cs
1,901
C#
using System.Collections.Generic; namespace MLSoftware.OTA { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")] public partial class RailOriginDestinationSummaryTypeConnectionLocation { private List<CompanyNamePrefType> _operatorPref; private string _locationCode; private string _codeContext; private bool _multiCityStationInd; private PreferLevelType _preferLevel; public RailOriginDestinationSummaryTypeConnectionLocation() { this._operatorPref = new List<CompanyNamePrefType>(); } [System.Xml.Serialization.XmlElementAttribute("OperatorPref")] public List<CompanyNamePrefType> OperatorPref { get { return this._operatorPref; } set { this._operatorPref = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string LocationCode { get { return this._locationCode; } set { this._locationCode = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string CodeContext { get { return this._codeContext; } set { this._codeContext = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool MultiCityStationInd { get { return this._multiCityStationInd; } set { this._multiCityStationInd = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public PreferLevelType PreferLevel { get { return this._preferLevel; } set { this._preferLevel = value; } } } }
26.602151
118
0.519806
[ "MIT" ]
Franklin89/OTA-Library
src/OTA-Library/RailOriginDestinationSummaryTypeConnectionLocation.cs
2,474
C#
using Bulkie.API.Infrastructure; using BulkieFileProcessor.API.Model; using Microsoft.EntityFrameworkCore; using System; using System.Threading.Tasks; namespace BulkieFileProcessor.API.Infrastructure { public class FileReferenceRepository : IFileReferenceRepository { private readonly FileReferenceContext _fileReferenceContext; public FileReferenceRepository(FileReferenceContext fileReferenceContext) { _fileReferenceContext = fileReferenceContext; } public async Task<FileReference> FindOrCreate(string hash) { var fileReference = await _fileReferenceContext.FileReferences.FirstOrDefaultAsync(x => x.FileHash.Equals(hash)); if (fileReference != null) { return fileReference; } var newFileReference = new FileReference { Id = Guid.NewGuid(), FileHash = hash }; await _fileReferenceContext.AddAsync(newFileReference); await _fileReferenceContext.SaveChangesAsync(); return newFileReference; } } }
28.195122
125
0.653114
[ "MIT" ]
jbw/Bulkie
src/Services/Bulkie/BulkieFileProcessor.API/Infrastructure/FileReferenceRepository.cs
1,158
C#
using Microsoft.AspNetCore.Http; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; using System.IO; namespace AspNetBoilerPlateMySql.Web.Extensions { public static class FormFileExtensions { public static byte[] OptimizeImageSize(this IFormFile file, int maxWidth, int maxHeight) { using (var stream = file.OpenReadStream()) using (var image = Image.Load(stream)) { using (var writeStream = new MemoryStream()) { //if (image.Width > maxWidth) //{ // var thumbScaleFactor = maxWidth / image.Width; // image.Mutate(i => i.Resize(maxWidth, image.Height * // thumbScaleFactor)); //} if (image.Height > maxHeight) { var thumbScaleFactor = maxHeight / image.Height; image.Mutate(i => i.Resize(maxHeight, image.Width * thumbScaleFactor)); } image.SaveAsPng(writeStream); return writeStream.ToArray(); } } } } }
36.085714
96
0.490895
[ "MIT" ]
ltaquino/AspNetBoilerPlateMySql
AspNetBoilerPlateMySql.Web/Extensions/FormFileExtensions.cs
1,265
C#
using System; using Npgsql; namespace Shared.Infrastructure { public class PostgreContext { private readonly string m_ConnectionString; public NpgsqlConnection Instance => ConnectToPostgres(); public PostgreContext(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentException($"'{nameof(connectionString)}' cannot be null or empty", nameof(connectionString)); m_ConnectionString = connectionString; } private NpgsqlConnection ConnectToPostgres() => new NpgsqlConnection(m_ConnectionString); } }
28.217391
127
0.677966
[ "MIT" ]
Elpulgo/microservice_example_v2
Shared/Shared.Infrastructure/Data/PostgreContext.cs
649
C#
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 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.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Xml.Serialization; namespace Node.Cs.Lib.Settings { public class CulturesDefinition { private string _defaultCultureString; private string _availableCultureStrings; private readonly ConcurrentDictionary<string, CultureInfo> _availableCultures = new ConcurrentDictionary<string,CultureInfo>( new Dictionary<string, CultureInfo>(StringComparer.OrdinalIgnoreCase),StringComparer.OrdinalIgnoreCase); private CultureInfo _defaultCulture = new CultureInfo("en-US"); [XmlAttribute("Default")] public string DefaultCultureString { get { return _defaultCultureString; } set { _defaultCultureString = value; if (!string.IsNullOrWhiteSpace(_defaultCultureString)) { _defaultCulture = new CultureInfo(_defaultCultureString); } } } [XmlAttribute("Available")] public string AvailableCultureStrings { get { return _availableCultureStrings; } set { if (value == null) value = string.Empty; _availableCultureStrings = value; var allCultures = _availableCultureStrings.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var tmpList = new List<CultureInfo>(); foreach (var culture in allCultures) { _availableCultures.TryAdd(culture,new CultureInfo(culture)); } } } [XmlIgnore] public IDictionary<string,CultureInfo> AvailableCultures { get { return _availableCultures; } } [XmlIgnore] public CultureInfo DefaultCulture { get { return _defaultCulture; } } } }
32.939759
131
0.712143
[ "MIT" ]
endaroza/Node.Cs
Src/Node.Cs.Commons/Settings/CulturesDescriptor.cs
2,734
C#
using System; namespace MackySoft.Choice.Internal { public static class ArrayPoolUtility { public static void EnsureCapacity<T> (ref T[] array,int index) { if (array.Length <= index) { int newSize = array.Length * 2; T[] newArray = ArrayPool<T>.Rent((index < newSize) ? newSize : (index * 2)); Array.Copy(array,0,newArray,0,array.Length); ArrayPool<T>.Return(array,!RuntimeHelpers.IsWellKnownNoReferenceContainsType<T>()); array = newArray; } } } }
25.578947
87
0.679012
[ "MIT" ]
mackysoft/Choice
Assets/MackySoft/MackySoft.Choice/Runtime/Internal/ArrayPoolUtility.cs
488
C#
using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Text; namespace ImGuiNET { public unsafe partial struct ImFontGlyph { public ushort Codepoint; public float AdvanceX; public float X0; public float Y0; public float X1; public float Y1; public float U0; public float V0; public float U1; public float V1; } public unsafe partial struct ImFontGlyphPtr { public ImFontGlyph* NativePtr { get; } public ImFontGlyphPtr(ImFontGlyph* nativePtr) => NativePtr = nativePtr; public ImFontGlyphPtr(IntPtr nativePtr) => NativePtr = (ImFontGlyph*)nativePtr; public static implicit operator ImFontGlyphPtr(ImFontGlyph* nativePtr) => new ImFontGlyphPtr(nativePtr); public static implicit operator ImFontGlyph* (ImFontGlyphPtr wrappedPtr) => wrappedPtr.NativePtr; public static implicit operator ImFontGlyphPtr(IntPtr nativePtr) => new ImFontGlyphPtr(nativePtr); public ref ushort Codepoint => ref Unsafe.AsRef<ushort>(&NativePtr->Codepoint); public ref float AdvanceX => ref Unsafe.AsRef<float>(&NativePtr->AdvanceX); public ref float X0 => ref Unsafe.AsRef<float>(&NativePtr->X0); public ref float Y0 => ref Unsafe.AsRef<float>(&NativePtr->Y0); public ref float X1 => ref Unsafe.AsRef<float>(&NativePtr->X1); public ref float Y1 => ref Unsafe.AsRef<float>(&NativePtr->Y1); public ref float U0 => ref Unsafe.AsRef<float>(&NativePtr->U0); public ref float V0 => ref Unsafe.AsRef<float>(&NativePtr->V0); public ref float U1 => ref Unsafe.AsRef<float>(&NativePtr->U1); public ref float V1 => ref Unsafe.AsRef<float>(&NativePtr->V1); } }
44.609756
113
0.659923
[ "MIT" ]
JayPeet/UnityImGUI
UnityImGUI/Assets/UnityImGui/Scripts/ImGui.NET/Generated/ImFontGlyph.gen.cs
1,829
C#
/* ==================================================================== 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 is1 distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.HSSF.Record.Chart { using System; using Npoi.Core.HSSF.Record; using Npoi.Core.HSSF.Record.Chart; using NUnit.Framework; /** * Tests the serialization and deserialization of the BarRecord * class works correctly. Test data taken directly from a real * Excel file. * * @author Glen Stampoultzis (glens at apache.org) */ [TestFixture] public class TestBarRecord { byte[] data = new byte[] { (byte)0x00,(byte)0x00, // bar space (byte)0x96,(byte)0x00, // category space (byte)0x00,(byte)0x00 // format flags }; public TestBarRecord() { } [Test] public void TestLoad() { BarRecord record = new BarRecord(TestcaseRecordInputStream.Create((short)0x1017, data)); Assert.AreEqual(0, record.BarSpace); Assert.AreEqual(0x96, record.CategorySpace); Assert.AreEqual(0, record.FormatFlags); Assert.AreEqual(false, record.IsHorizontal); Assert.AreEqual(false, record.IsStacked); Assert.AreEqual(false, record.IsDisplayAsPercentage); Assert.AreEqual(false, record.IsShadow); Assert.AreEqual(10, record.RecordSize); } [Test] public void TestStore() { BarRecord record = new BarRecord(); record.BarSpace = ((short)0); record.CategorySpace = ((short)0x96); record.IsHorizontal = (false); record.IsStacked = (false); record.IsDisplayAsPercentage = (false); record.IsShadow = (false); byte[] recordBytes = record.Serialize(); Assert.AreEqual(recordBytes.Length - 4, data.Length); for (int i = 0; i < data.Length; i++) Assert.AreEqual(data[i], recordBytes[i + 4], "At offset " + i); } } }
34.261905
100
0.597637
[ "Apache-2.0" ]
Arch/Npoi.Core
test/Npoi.Core.TestCases/HSSF/Record/Chart/TestBarRecord.cs
2,878
C#
namespace SteamAutoMarket.Steam.Market { using SteamAutoMarket.Steam.Market.Enums; public class Settings { public ELanguage Language { get; set; } public string UserAgent { get; set; } } }
20.272727
47
0.654709
[ "MIT" ]
Shamanovski/SteamAutoMarket
SteamAutoMarketWPF/SteamAutoMarket/SteamAutoMarket/Steam/Market/Settings.cs
225
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DirectionBehavior : Behavior { public bool rotateOnXAxis = true; public bool rotateOnYAxis = false; public Transform rotationTransform; [HideInInspector] public Vector2 rotation; // rotates the entity using rotation parameter public virtual void Rotate(Vector2 rotation) { this.rotation.x += rotation.x; this.rotation.y = Mathf.Clamp(this.rotation.y - rotation.y, -90, 90); CalculateRotation(); } // calculates rotations off of rotation variable public virtual void CalculateRotation() { rotationTransform.localRotation = Quaternion.Euler(new Vector3(rotateOnYAxis ? rotation.y : 0, rotateOnXAxis ? rotation.x : 0, 0)); } // gets the Horzontal Direction based off of the rotation variable public virtual Vector3 HorizontalDirection() { return transform.TransformDirection(Quaternion.AngleAxis(rotation.x, Vector3.up) * Vector3.forward); } public virtual Vector3 GetDirection() { return transform.TransformDirection(GetEntityRotation() * Vector3.forward); } // gets the rotation based off of the rotation variable public virtual Quaternion GetHorizontalEntityRotation() { return transform.rotation * Quaternion.Euler(0, rotation.x, 0); } // gets the rotation based off of the rotation variable public virtual Quaternion GetEntityRotation() { return transform.rotation * Quaternion.Euler(rotation.y, rotation.x, 0); } }
31.254902
139
0.704517
[ "MIT" ]
Themaster-123/Survival-Game
Assets/Scripts/Behaviors/DirectionBehavior.cs
1,594
C#
namespace Cauldron.XAML.Theme.Styles { public partial class ListViewStyle { public ListViewStyle() { InitializeComponent(); } } }
17.8
38
0.567416
[ "MIT" ]
Capgemini/Cauldron
Old/Desktop/Cauldron.Desktop.XAML.Theme/Styles/ListViewStyle.xaml.cs
180
C#
using System; using System.Collections.Generic; using Content.Server.GameObjects.EntitySystems; using Content.Server.Interfaces; using Content.Shared.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.Random; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Random; using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Destructible { /// <summary> /// Deletes the entity once a certain damage threshold has been reached. /// </summary> [RegisterComponent] public class DestructibleComponent : Component, IOnDamageBehavior, IDestroyAct, IExAct { #pragma warning disable 649 [Dependency] private readonly IEntitySystemManager _entitySystemManager; #pragma warning restore 649 /// <inheritdoc /> public override string Name => "Destructible"; /// <summary> /// Damage threshold calculated from the values /// given in the prototype declaration. /// </summary> [ViewVariables] public DamageThreshold Threshold { get; private set; } public DamageType damageType = DamageType.Total; public int damageValue = 0; public string spawnOnDestroy = ""; public bool destroyed = false; ActSystem _actSystem; public override void ExposeData(ObjectSerializer serializer) { base.ExposeData(serializer); serializer.DataField(ref damageValue, "thresholdvalue", 100); serializer.DataField(ref damageType, "thresholdtype", DamageType.Total); serializer.DataField(ref spawnOnDestroy, "spawnondestroy", ""); } public override void Initialize() { base.Initialize(); _actSystem = _entitySystemManager.GetEntitySystem<ActSystem>(); } /// <inheritdoc /> List<DamageThreshold> IOnDamageBehavior.GetAllDamageThresholds() { Threshold = new DamageThreshold(damageType, damageValue, ThresholdType.Destruction); return new List<DamageThreshold>() { Threshold }; } /// <inheritdoc /> void IOnDamageBehavior.OnDamageThresholdPassed(object obj, DamageThresholdPassedEventArgs e) { if (e.Passed && e.DamageThreshold == Threshold && destroyed == false) { destroyed = true; _actSystem.HandleDestruction(Owner, true); } } void IExAct.OnExplosion(ExplosionEventArgs eventArgs) { var prob = IoCManager.Resolve<IRobustRandom>(); switch (eventArgs.Severity) { case ExplosionSeverity.Destruction: _actSystem.HandleDestruction(Owner, false); break; case ExplosionSeverity.Heavy: _actSystem.HandleDestruction(Owner, true); break; case ExplosionSeverity.Light: if (prob.Prob(40)) _actSystem.HandleDestruction(Owner, true); break; } } void IDestroyAct.OnDestroy(DestructionEventArgs eventArgs) { if (!string.IsNullOrWhiteSpace(spawnOnDestroy) && eventArgs.IsSpawnWreck) { Owner.EntityManager.SpawnEntityAt(spawnOnDestroy, Owner.Transform.GridPosition); } } } }
33.556604
100
0.624684
[ "MIT" ]
rjarbour/space-station-14
Content.Server/GameObjects/Components/Damage/DestructibleComponent.cs
3,559
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Linq; namespace Azure.IoT.DeviceUpdate.Models { /// <summary> Import update input metadata. </summary> public partial class ImportUpdateInput { /// <summary> Initializes a new instance of ImportUpdateInput. </summary> /// <param name="importManifest"> Import manifest metadata like source URL, file size/hashes, etc. </param> /// <param name="files"> One or more update file properties like filename and source URL. </param> /// <exception cref="ArgumentNullException"> <paramref name="importManifest"/> or <paramref name="files"/> is null. </exception> public ImportUpdateInput(ImportManifestMetadata importManifest, IEnumerable<FileImportMetadata> files) { if (importManifest == null) { throw new ArgumentNullException(nameof(importManifest)); } if (files == null) { throw new ArgumentNullException(nameof(files)); } ImportManifest = importManifest; Files = files.ToList(); } /// <summary> Import manifest metadata like source URL, file size/hashes, etc. </summary> public ImportManifestMetadata ImportManifest { get; } /// <summary> One or more update file properties like filename and source URL. </summary> public IList<FileImportMetadata> Files { get; } } }
38.047619
136
0.650188
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/deviceupdate/Azure.IoT.DeviceUpdate/src/Generated/Models/ImportUpdateInput.cs
1,598
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using CyberCommando.Engine; using CyberCommando.Entities.Enviroment; using Microsoft.Xna.Framework.Input; namespace CyberCommando.Services.Utils { class GameScreen : Screen { World WCore; Color ShadowColor = Color.Gray; bool ShadowEffect = false; bool BloomEffect = false; KeyboardState Kstate = Keyboard.GetState(); BloomRenderComponent BloomRender; QuadRenderComponent SQuadRender; ShadowResolver ShadowRender; int LLimit { get; set; } int RLimit { get; set; } int RLightLimit { get; set; } public override void Initialize(GraphicsDevice graphdev, Game game, params object[] param) { base.Initialize(graphdev, game); this.SQuadRender = new QuadRenderComponent(CoreGame); this.BloomRender = new BloomRenderComponent(CoreGame); var lvl = (LevelNames) param[0]; LevelManager.Instance.Initialize(); LevelManager.Instance.LoadLevel(lvl); this.WCore = new World(CoreGame, GraphDev.Viewport.Height, GraphDev.Viewport.Width, GraphDev.Viewport); this.WCore.Initialize(); } public override void Resize(ResolutionState res, int width, int height) { base.Resize(res, width, height); WCore.UpdateResolution(width, height, res); LLimit = WCore.FWidth / 2; RLimit = WCore.LevelLimits.Width - WCore.FWidth / 2; RLightLimit = WCore.LevelLimits.Width - WCore.FWidth; } public override void LoadContent(ContentManager content) { base.LoadContent(content); CoreGame.Components.Add(BloomRender); CoreGame.Components.Add(SQuadRender); //Resize screen Resize(ResolutionState.R1280x720, GraphDev.Viewport.Width, GraphDev.Viewport.Height); ShadowRender = new ShadowResolver(GraphDev, SQuadRender, ShadowMapSize.Size256, ShadowMapSize.Size256, ShadowColor); ShadowRender.LoadContent(Content); } public override void UnloadContent() { base.UnloadContent(); } public override void Update(GameTime gameTime) { WCore.Update(gameTime); KeyboardState state = Keyboard.GetState(); if (state.IsKeyDown(Keys.P) && Kstate.IsKeyUp(Keys.P)) ShadowEffect = !ShadowEffect; if (state.IsKeyDown(Keys.O) && Kstate.IsKeyUp(Keys.O)) BloomEffect = !BloomEffect; Kstate = state; } /// <summary> /// /// </summary> public void DrawLights(SpriteBatch batcher) { batcher.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null, null); foreach (var light in WCore.LevelLight) { if (light.IsOnScreen) batcher.Draw(light.RenderTarget, light.DPosition - light.LAreaSize * 0.5f, light.LColor); } batcher.End(); } /// <summary> /// /// </summary> public void ResolveLightShadowCasts(SpriteBatch batcher, GameTime gameTime) { var playerLeft = WCore.Player.WPosition.X - LLimit; var lightOnLevel = WCore.LevelLight; var LightLeftLimit = new Vector2(-lightOnLevel[0].LAreaSize.X, 0); var LightRightLimit = new Vector2(WCore.FWidth + lightOnLevel[0].LAreaSize.X, 0); foreach (var light in lightOnLevel) { if (WCore.Player.WPosition.X < LLimit) light.DPosition = light.WPosition; else if (WCore.Player.WPosition.X > RLimit) light.DPosition = new Vector2(light.WPosition.X - RLightLimit, light.WPosition.Y); else light.DPosition = new Vector2((light.WPosition.X - playerLeft), light.WPosition.Y); if (light.DPosition.X > LightRightLimit.X || light.DPosition.X < LightLeftLimit.X) { light.IsOnScreen = false; continue; } else light.IsOnScreen = true; light.BeginDrawingShadowCasters(); WCore.DrawEntitiesShadowCasters(gameTime, batcher, light, Color.Black); light.EndDrawingShadowCasters(); ShadowRender.ResolveShadows(light.RenderTarget, light.RenderTarget, light.DPosition); } } public override void Draw(SpriteBatch batcher, GameTime gameTime) { // Resolve shadow map if (ShadowEffect) { ResolveLightShadowCasts(batcher, gameTime); ShadowRender.BeginDraw(); DrawLights(batcher); ShadowRender.EndDraw(); } // Draw Bloom Effect if (BloomEffect) BloomRender.BeginDraw(); // Draw Level background layers WCore.DrawLVLBack(gameTime, batcher); if (BloomEffect) { BloomRender.DrawBloom(); BloomRender.EndDraw(); BloomRender.DisplayBloomTarget(); } // Display Frontlevel layers and Entitites WCore.DrawLVLFront(gameTime, batcher); WCore.DrawLVLEntities(gameTime, batcher); // Display Shadow Map if (ShadowEffect) ShadowRender.DisplayShadowCast(); base.Draw(batcher, gameTime); // DrawCharacter without effects cause all effects already accured WCore.DrawCharacter(gameTime, batcher); } } }
33.182292
115
0.552504
[ "MIT" ]
GoodforGod/NightFall
CyberCommando/Services/Utils/GameScreen.cs
6,373
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("MISD.Server.Performancetest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MISD.Server.Performancetest")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("ade41951-59dc-41ee-8a39-fb55d0570d49")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.972973
107
0.744366
[ "BSD-3-Clause" ]
sebastianzillessen/MISD-OWL
Code/MISDCode/MISD.Server.Performancetest/Properties/AssemblyInfo.cs
1,571
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using Cinemachine; public class PlayerMovement : MonoBehaviour { [Header("Float")] public float speed = 5; public float orignSpeed = 5; public float dashSpeed = 5; public float jumpForce = 300; private float x; [Space] [Header("Booleans")] public bool isJumpUp = false; // Y軸速度>0 public bool fall = false; //判斷是否放開跳躍鍵 private bool jumping = false; private bool doubleJump = true; private bool canMove = true; private bool damage = false; private bool startJump = false; [Space] [Header("Object")] [HideInInspector] public Rigidbody2D rb; Animator animator; private Collision coll; void Awake() { if (GameObject.FindGameObjectsWithTag("Player").Length > 3) Destroy(this.gameObject); else DontDestroyOnLoad(this.gameObject); } void Start() { rb = GetComponent<Rigidbody2D>(); animator = GetComponent<Animator>(); coll = GetComponent<Collision>(); } void Update() { x = Input.GetAxis("Horizontal"); SetJumpState(); if (canMove) { if (Input.GetButtonDown("Jump")) { if (coll.OnGround() || doubleJump) startJump = true; } Dash(); } } private void FixedUpdate() { if (canMove) { Move(); Jump(); } if (coll.OnGround()) { jumping = false; doubleJump = true; } //判斷落下 if (rb.velocity.y < 0) { isJumpUp = false; } // 短按跳躍落下 if (isJumpUp) { if (!Input.GetButton("Jump")) { fall = true; } } if (fall && rb.velocity.y <= 2.5f) { rb.velocity = new Vector2(rb.velocity.x, 0); fall = false; } } void Move() { if (!canMove) return; float movement = x * speed; rb.velocity = new Vector2(movement, rb.velocity.y); if (rb.velocity.x != 0) { Vector2 scale = transform.localScale; scale.x = Mathf.Sign(rb.velocity.x) == 1f ? 1f : -1; transform.localScale = scale; } } void Dash() { if (Input.GetButton("Dash")) { if(speed <= dashSpeed) speed += Time.deltaTime * 8; return; } if (speed >= orignSpeed) speed -= Time.deltaTime * 4; } void Jump() { if (coll.OnGround() && (rb.velocity.y < 1 && rb.velocity.y > -1)) { if (startJump) { jumping = true; rb.velocity = new Vector3(rb.velocity.x, 0); rb.AddForce(Vector3.up * jumpForce); isJumpUp = true; startJump = false; } } else if (doubleJump && startJump) { jumping = true; rb.velocity = new Vector3(rb.velocity.x, 0); rb.AddForce(Vector3.up * jumpForce * 1f); isJumpUp = true; startJump = false; doubleJump = false; } } void SetJumpState() { if (rb.velocity.y > 1 || rb.velocity.y < -1) { jumping = true; } } public void MoveOrNot(bool Active) { canMove = Active; } }
23.819355
74
0.46831
[ "MIT" ]
neil841004/UU
Assets/Script/PlayerMovement.cs
3,738
C#
// // MRElf.cs // // Author: // Steve Jakab <> // // Copyright (c) 2015 Steve Jakab // // 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 UnityEngine; using System.Collections; using AssemblyCSharp; namespace PortableRealm { public class MRElf : MRCharacter { #region Properties public override MRGame.eCharacters Character { get{ return MRGame.eCharacters.Elf; } } public override string Name { get{ return "Elf"; } } public override string IconName { get{ return "Textures/elf"; } } public override int StartingGoldValue { get { return 16; } } #endregion #region Methods public MRElf() { } public MRElf(JSONObject jsonData, int index) : base(jsonData, index) { } // Does initialization associated with birdsong. public override void StartBirdsong() { base.StartBirdsong(); // Elusiveness: can do an extra hide phase int bonus = mExtraActivities[MRGame.eActivity.Hide]; mExtraActivities[MRGame.eActivity.Hide] = bonus + 1; } // Returns the die pool for a given roll type public override MRDiePool DiePool(MRGame.eRollTypes roll) { // Archer: rolls 1 die on missile table if (roll == MRGame.eRollTypes.Missile) { MRDiePool pool = MRDiePool.NewDicePool; pool.NumDice = 1; return pool; } return base.DiePool(roll); } // Update is called once per frame public override void Update () { base.Update(); } #endregion } }
22.633028
80
0.717876
[ "MIT" ]
portablemagicrealm/portablerealm
Assets/Standard Assets (Mobile)/Scripts/Characters/Classes/MRElf.cs
2,467
C#
using System.Threading.Tasks; using OrchardCore.DisplayManagement.Entities; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; using OrchardCore.Modules; using OrchardCore.Users.Models; using OrchardCore.Users.TimeZone.Models; using OrchardCore.Users.TimeZone.Services; using OrchardCore.Users.TimeZone.ViewModels; namespace OrchardCore.Users.TimeZone.Drivers { public class UserTimeZoneDisplayDriver : SectionDisplayDriver<User, UserTimeZone> { private readonly IClock _clock; private readonly UserTimeZoneService _userTimeZoneService; public UserTimeZoneDisplayDriver(IClock clock, UserTimeZoneService userTimeZoneService) { _clock = clock; _userTimeZoneService = userTimeZoneService; } public override IDisplayResult Edit(UserTimeZone userTimeZone, BuildEditorContext context) { return Initialize<UserTimeZoneViewModel>("UserTimeZone_Edit", model => { model.TimeZoneId = userTimeZone.TimeZoneId; }).Location("Content:2"); } public override async Task<IDisplayResult> UpdateAsync(User user, UserTimeZone userTimeZone, IUpdateModel updater, BuildEditorContext context) { var model = new UserTimeZoneViewModel(); if (await context.Updater.TryUpdateModelAsync(model, Prefix)) { userTimeZone.TimeZoneId = model.TimeZoneId; // Remove the cache entry, don't update it, as the form might still fail validation for other reasons. await _userTimeZoneService.UpdateUserTimeZoneAsync(user); } return await EditAsync(userTimeZone, context); } } }
37.306122
150
0.700766
[ "BSD-3-Clause" ]
1426463237/OrchardCore
src/OrchardCore.Modules/OrchardCore.Users/TimeZone/Drivers/UserTimeZoneDisplayDriver.cs
1,828
C#
#if !NETSTANDARD13 using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Amazon.Runtime { /// <summary> /// An enumerable containing all of the responses for a paginated /// operation /// </summary> /// <typeparam name="TResponse"></typeparam> public class PaginatedResponse<TResponse> : IPaginatedEnumerable<TResponse> { private readonly IPaginator<TResponse> _paginator; /// <summary> /// Create a PaginatedResponse object by providing /// any operation paginator /// </summary> /// <param name="paginator"></param> public PaginatedResponse(IPaginator<TResponse> paginator) { this._paginator = paginator; } #if AWS_ASYNC_ENUMERABLES_API /// <summary> /// Get responses asynchronously /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public async IAsyncEnumerator<TResponse> GetAsyncEnumerator(CancellationToken cancellationToken = default) { await foreach (var response in _paginator.PaginateAsync().WithCancellation(cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); yield return response; } } #endif #if BCL /// <summary> /// Get responses synchronously /// </summary> /// <returns></returns> public IEnumerator<TResponse> GetEnumerator() { return _paginator.Paginate().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endif } } #endif
29.852459
129
0.607908
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Core/Amazon.Runtime/_bcl45+netstandard/PaginatedResponse.cs
1,823
C#
// <copyright> // Copyright 2020 Max Ieremenko // // 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. // </copyright> using System; using System.Collections.Generic; namespace ServiceModel.Grpc.Internal { internal sealed class InterfaceDescription { public InterfaceDescription(Type interfaceType) { InterfaceType = interfaceType; } public Type InterfaceType { get; } public IList<MethodDescription> Methods { get; } = new List<MethodDescription>(); public IList<OperationDescription> Operations { get; } = new List<OperationDescription>(); public IList<MethodDescription> NotSupportedOperations { get; } = new List<MethodDescription>(); } }
32.342105
104
0.712775
[ "Apache-2.0" ]
max-ieremenko/ServiceModel.Grpc
Sources/ServiceModel.Grpc/Internal/InterfaceDescription.cs
1,231
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ManagedIOSStoreAppRequest. /// </summary> public partial class ManagedIOSStoreAppRequest : BaseRequest, IManagedIOSStoreAppRequest { /// <summary> /// Constructs a new ManagedIOSStoreAppRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ManagedIOSStoreAppRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified ManagedIOSStoreApp using POST. /// </summary> /// <param name="managedIOSStoreAppToCreate">The ManagedIOSStoreApp to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ManagedIOSStoreApp.</returns> public async System.Threading.Tasks.Task<ManagedIOSStoreApp> CreateAsync(ManagedIOSStoreApp managedIOSStoreAppToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; var newEntity = await this.SendAsync<ManagedIOSStoreApp>(managedIOSStoreAppToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Creates the specified ManagedIOSStoreApp using POST and returns a <see cref="GraphResponse{ManagedIOSStoreApp}"/> object. /// </summary> /// <param name="managedIOSStoreAppToCreate">The ManagedIOSStoreApp to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{ManagedIOSStoreApp}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<ManagedIOSStoreApp>> CreateResponseAsync(ManagedIOSStoreApp managedIOSStoreAppToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<ManagedIOSStoreApp>(managedIOSStoreAppToCreate, cancellationToken); } /// <summary> /// Deletes the specified ManagedIOSStoreApp. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; await this.SendAsync<ManagedIOSStoreApp>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified ManagedIOSStoreApp and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; return this.SendAsyncWithGraphResponse(null, cancellationToken); } /// <summary> /// Gets the specified ManagedIOSStoreApp. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The ManagedIOSStoreApp.</returns> public async System.Threading.Tasks.Task<ManagedIOSStoreApp> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var retrievedEntity = await this.SendAsync<ManagedIOSStoreApp>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Gets the specified ManagedIOSStoreApp and returns a <see cref="GraphResponse{ManagedIOSStoreApp}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{ManagedIOSStoreApp}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<ManagedIOSStoreApp>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<ManagedIOSStoreApp>(null, cancellationToken); } /// <summary> /// Updates the specified ManagedIOSStoreApp using PATCH. /// </summary> /// <param name="managedIOSStoreAppToUpdate">The ManagedIOSStoreApp to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated ManagedIOSStoreApp.</returns> public async System.Threading.Tasks.Task<ManagedIOSStoreApp> UpdateAsync(ManagedIOSStoreApp managedIOSStoreAppToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; var updatedEntity = await this.SendAsync<ManagedIOSStoreApp>(managedIOSStoreAppToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified ManagedIOSStoreApp using PATCH and returns a <see cref="GraphResponse{ManagedIOSStoreApp}"/> object. /// </summary> /// <param name="managedIOSStoreAppToUpdate">The ManagedIOSStoreApp to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{ManagedIOSStoreApp}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<ManagedIOSStoreApp>> UpdateResponseAsync(ManagedIOSStoreApp managedIOSStoreAppToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; return this.SendAsyncWithGraphResponse<ManagedIOSStoreApp>(managedIOSStoreAppToUpdate, cancellationToken); } /// <summary> /// Updates the specified ManagedIOSStoreApp using PUT. /// </summary> /// <param name="managedIOSStoreAppToUpdate">The ManagedIOSStoreApp object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task<ManagedIOSStoreApp> PutAsync(ManagedIOSStoreApp managedIOSStoreAppToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; var updatedEntity = await this.SendAsync<ManagedIOSStoreApp>(managedIOSStoreAppToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified ManagedIOSStoreApp using PUT and returns a <see cref="GraphResponse{ManagedIOSStoreApp}"/> object. /// </summary> /// <param name="managedIOSStoreAppToUpdate">The ManagedIOSStoreApp object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await of <see cref="GraphResponse{ManagedIOSStoreApp}"/>.</returns> public System.Threading.Tasks.Task<GraphResponse<ManagedIOSStoreApp>> PutResponseAsync(ManagedIOSStoreApp managedIOSStoreAppToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; return this.SendAsyncWithGraphResponse<ManagedIOSStoreApp>(managedIOSStoreAppToUpdate, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IManagedIOSStoreAppRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IManagedIOSStoreAppRequest Expand(Expression<Func<ManagedIOSStoreApp, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IManagedIOSStoreAppRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IManagedIOSStoreAppRequest Select(Expression<Func<ManagedIOSStoreApp, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="managedIOSStoreAppToInitialize">The <see cref="ManagedIOSStoreApp"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(ManagedIOSStoreApp managedIOSStoreAppToInitialize) { } } }
51.732
191
0.654605
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/ManagedIOSStoreAppRequest.cs
12,933
C#
using System; using System.Collections.Generic; using System.Text; namespace DesignPattern.Memento { public sealed class MobileBackOriginator { /// <summary> /// 发起人需要保存的内部状态 /// </summary> private List<ContactPerson> _personList; public List<ContactPerson> ContactPersonList { get { return _personList; } set { _personList = value; } } /// <summary> /// 初始化需要备份的电话名单 /// </summary> /// <param name="personList"></param> public MobileBackOriginator(List<ContactPerson> personList) { if (personList != null) { _personList = personList; } else { throw new ArgumentNullException("参数不能为空!"); } } /// <summary> /// 创建备忘录对象实例,将当期要保存的联系人列表保存到备忘录对象中 /// </summary> /// <returns></returns> public ContactPersonMemento CreateMemento() { return new ContactPersonMemento(new List<ContactPerson>(this._personList)); } // 将备忘录中的数据备份还原到联系人列表中 public void RestoreMemento(ContactPersonMemento memento) { ContactPersonList = memento.ContactPersonListBack; } public void Show() { Console.WriteLine("联系人列表中共有{0}个人,他们是:", ContactPersonList.Count); foreach (ContactPerson p in ContactPersonList) { Console.WriteLine("姓名: {0} 号码: {1}", p.Name, p.MobileNumber); } } } }
24.449275
87
0.510966
[ "MIT" ]
LambertW/DesignPattern
DesignPattern.Memento/MobileBackOriginator.cs
1,887
C#
using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.PrinterCommunication; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MatterHackers.SerialPortCommunication.FrostedSerial; using Zeroconf; using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.Agg.Platform; using MatterHackers.ImageProcessing; namespace MatterHackers.MatterControl.SlicerConfiguration { class IpAddessField : UIField { private DropDownList dropdownList; private IconButton refreshButton; private PrinterConfig printer; private ThemeConfig theme; public IpAddessField(PrinterConfig printer, ThemeConfig theme) { this.printer = printer; this.theme = theme; } public override void Initialize(int tabIndex) { base.Initialize(tabIndex); bool canChangeComPort = !printer.Connection.IsConnected && printer.Connection.CommunicationState != CommunicationStates.AttemptingToConnect; //This setting defaults to Manual var selectedMachine = printer.Settings.GetValue(SettingsKey.selector_ip_address); dropdownList = new MHDropDownList(selectedMachine, theme, maxHeight: 200 * GuiWidget.DeviceScale) { ToolTipText = HelpText, Margin = new BorderDouble(), TabIndex = tabIndex, Enabled = canChangeComPort, TextColor = canChangeComPort ? theme.TextColor : new Color(theme.TextColor, 150), }; // Create default option MenuItem defaultOption = dropdownList.AddItem("Manual", "127.0.0.1:23"); defaultOption.Selected += (sender, e) => { printer.Settings.SetValue(SettingsKey.selector_ip_address, defaultOption.Text); }; // Prevent droplist interaction when connected void CommunicationStateChanged(object s, EventArgs e) { canChangeComPort = !printer.Connection.IsConnected && printer.Connection.CommunicationState != CommunicationStates.AttemptingToConnect; dropdownList.TextColor = theme.TextColor; dropdownList.Enabled = canChangeComPort; } printer.Connection.CommunicationStateChanged += CommunicationStateChanged; dropdownList.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; var widget = new FlowLayoutWidget(); widget.AddChild(dropdownList); refreshButton = new IconButton(StaticData.Instance.LoadIcon("fa-refresh_14.png", 14, 14).SetToColor(theme.TextColor), theme) { Margin = new BorderDouble(left: 5) }; refreshButton.Click += (s, e) => RebuildMenuItems(); widget.AddChild(refreshButton); this.Content = widget; UiThread.RunOnIdle(RebuildMenuItems); } protected override void OnValueChanged(FieldChangedEventArgs fieldChangedEventArgs) { dropdownList.SelectedLabel = this.Value; base.OnValueChanged(fieldChangedEventArgs); } private async void RebuildMenuItems() { refreshButton.Enabled = false; IReadOnlyList<Zeroconf.IZeroconfHost> possibleHosts = await ProbeForNetworkedTelenetConnections(); dropdownList.MenuItems.Clear(); MenuItem defaultOption = dropdownList.AddItem("Manual", "127.0.0.1:23"); defaultOption.Selected += (sender, e) => { printer.Settings.SetValue(SettingsKey.selector_ip_address, defaultOption.Text); }; foreach (Zeroconf.IZeroconfHost host in possibleHosts) { // Add each found telnet host to the dropdown list IService service; bool exists = host.Services.TryGetValue("_telnet._tcp.local.", out service); int port = exists ? service.Port : 23; MenuItem newItem = dropdownList.AddItem(host.DisplayName, $"{host.IPAddress}:{port}"); // The port may be unnecessary // When the given menu item is selected, save its value back into settings newItem.Selected += (sender, e) => { if (sender is MenuItem menuItem) { // this.SetValue( // menuItem.Text, // userInitiated: true); string[] ipAndPort = menuItem.Value.Split(':'); printer.Settings.SetValue(SettingsKey.ip_address, ipAndPort[0]); printer.Settings.SetValue(SettingsKey.ip_port, ipAndPort[1]); printer.Settings.SetValue(SettingsKey.selector_ip_address, menuItem.Text); } }; } refreshButton.Enabled = true; } private void DefaultOption_Selected(object sender, EventArgs e) { throw new NotImplementedException(); } public static async Task<IReadOnlyList<Zeroconf.IZeroconfHost>> ProbeForNetworkedTelenetConnections() { return await ZeroconfResolver.ResolveAsync("_telnet._tcp.local."); } public static async Task<IReadOnlyList<Zeroconf.IZeroconfHost>> EnumerateAllServicesFromAllHosts() { ILookup<string, string> domains = await ZeroconfResolver.BrowseDomainsAsync(); return await ZeroconfResolver.ResolveAsync(domains.Select(g => g.Key)); } } }
34.042254
143
0.750103
[ "BSD-2-Clause" ]
Bhalddin/MatterControl
MatterControlLib/SlicerConfiguration/UIFields/IpAddessField.cs
4,836
C#
using Microsoft.Extensions.DependencyInjection; using ReadingTracker.Domain.Interfaces; using ReadingTracker.Repository.Context; using ReadingTracker.Repository.Repository; using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Extensions.DependencyInjection { public static class InfraDependencyInjection { public static void ResolverDependenciasInfra(this IServiceCollection services) { RegisterMappings.Register(); services.AddScoped<IPessoaRepository, PessoaRepository>(); } } }
28.85
86
0.764298
[ "MIT" ]
tangsan06/ReadingTrackerWebApi.netcore
src/ReadingTracker.Infra/InfraDependencyInjection.cs
579
C#
using System.Diagnostics; using System.Threading.Tasks; using SimpleRtRest.RestClient; using SimpleRtRest.RestClient.Authenticators; using System.Net; namespace TelAPI { public partial class TelAPIRestClient { /// <summary> /// TelAPI API version to use when making requests /// </summary> public string ApiVersion { get; set; } /// <summary> /// Base URL of Rest Service /// </summary> public string BaseUrl { get; set; } private string AccountSid { get; set; } private string AuthToken { get; set; } private RestClient _client { get; set; } /// <summary> /// Initializes a new REST client with credentials /// </summary> /// <param name="accountSid">The AccountSid to authenticate with</param> /// <param name="authToken">The AuthToken to authenticate with</param> public TelAPIRestClient(string accountSid, string authToken) { ApiVersion = "v1"; BaseUrl = "https://api.telapi.com/"; AccountSid = accountSid; AuthToken = authToken; this.Connect(); } /// <summary> /// Initializes a new REST client with credentials /// </summary> /// <param name="configuration">TelAPIConfiguration</param> public TelAPIRestClient(ITelAPIConfiguration configuration) { ApiVersion = configuration.ApiVersion; BaseUrl = configuration.BaseUrl; AccountSid = configuration.AccountSid; AuthToken = configuration.AuthToken; this.Connect(); } /// <summary> /// Authenticate and connect to Rest service with credentials /// </summary> public void Connect() { //turned off because of testing purpose //var version = Assembly.GetEntryAssembly().GetName().Version; _client = new RestClient(); _client.UserAgent = "TelAPI-winrt/" + "1.0"; _client.Authenticator = new HttpBasicAuthenticator(AccountSid, AuthToken); _client.BaseUrl = string.Format("{0}{1}/", BaseUrl, ApiVersion); _client.IgnoreNullOnDeserialization = true; _client.AddDefaultUrlSegment("AccountSid", AccountSid); } /// <summary> /// Execute REST request /// </summary> /// <typeparam name="T">The type of object to create and populate with data</typeparam> /// <param name="request">The RestRequest to execute</param> /// <returns></returns> public async Task<T> Execute<T>(RestRequest request) where T : new() { var response = await _client.Execute<T>(request); switch (response.StatusCode) { case HttpStatusCode.BadRequest: throw new TelAPIBadRequestException(response.ErrorMessage + " Details : " + response.RawData); case HttpStatusCode.Unauthorized: throw new TelAPIUnauthorizedException(response.ErrorMessage + " Details : " + response.RawData); case HttpStatusCode.Forbidden: throw new TelAPIForbidenException(response.ErrorMessage + " Details : " + response.RawData); case HttpStatusCode.NotFound: throw new TelAPINotFoundException(response.ErrorMessage + " Details : " + response.RawData); case HttpStatusCode.InternalServerError: throw new TelAPIInternalErrorException(response.ErrorMessage + " Details : " + response.RawData); } //print out JSON response for testing purpose Debug.WriteLine(response.RawData); return response.Data; } /// <summary> /// Execute a REST request /// </summary> /// <param name="request">The RestRequest to execute</param> /// <returns></returns> public async Task<IRestResponse> Execute(IRestRequest request) { return await _client.Execute(request); } /// <summary> /// Helper for adding inequalities for DateTime parameters /// </summary> /// <param name="comparisonType">Comparasion type (less or greater)</param> /// <param name="parameterName">DateTime parameter name</param> /// <returns></returns> private string GetParameterNameWithEquality(ComparisonType? comparisonType, string parameterName) { if (comparisonType.HasValue) { switch (comparisonType) { case ComparisonType.GreaterThanOrEqualTo: parameterName += ">"; break; case ComparisonType.LessThanOrEqualTo: parameterName += "<"; break; } } return parameterName; } } }
37.410448
155
0.5769
[ "MIT" ]
TelAPI/telapi-dotnet
library/TelAPI.WinRT.Api/Core.cs
5,015
C#
namespace Geko.HttpClientService.CompleteSample.ClientCredentialsProtectedResourceServices.Dto; /// <summary> /// An object representing the result of the protected resource https://demo.identityserver.io/api/test /// </summary> public record class ClientCredentialsProtectedResourceResponseDto { /// <summary> /// The type property of the result /// </summary> public string? Type { get; init; } /// <summary> /// The value property of the result /// </summary> public string? Value { get; init; } }
29.777778
103
0.701493
[ "Apache-2.0" ]
georgekosmidis/Geko.HttpClientService
samples/Geko.HttpClientService.CompleteSample/ClientCredentialsProtectedResourceServices/Dto/ClientCredentialsProtectedResourceResponseDto.cs
538
C#
//------------------------------------------------------------------------------ // <auto-generated> // Bu kod araç tarafından oluşturuldu. // Çalışma Zamanı Sürümü:4.0.30319.42000 // // Bu dosyada yapılacak değişiklikler yanlış davranışa neden olabilir ve // kod yeniden oluşturulursa kaybolur. // </auto-generated> //------------------------------------------------------------------------------ namespace McTurk.Properties { using System; /// <summary> /// Yerelleştirilmiş dizeleri aramak gibi işlemler için, türü kesin olarak belirtilmiş kaynak sınıfı. /// </summary> // Bu sınıf ResGen veya Visual Studio gibi bir araç kullanılarak StronglyTypedResourceBuilder // sınıfı tarafından otomatik olarak oluşturuldu. // Üye eklemek veya kaldırmak için .ResX dosyanızı düzenleyin ve sonra da ResGen // komutunu /str seçeneğiyle yeniden çalıştırın veya VS projenizi yeniden oluşturun. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Bu sınıf tarafından kullanılan, önbelleğe alınmış ResourceManager örneğini döndürür. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("McTurk.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Tümü için geçerli iş parçacığının CurrentUICulture özelliğini geçersiz kular /// CurrentUICulture özelliğini tüm kaynak aramaları için geçersiz kılar. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap edit { get { object obj = ResourceManager.GetObject("edit", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap minecraft_dirt { get { object obj = ResourceManager.GetObject("minecraft_dirt", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap minecraft_logo { get { object obj = ResourceManager.GetObject("minecraft_logo", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap trash { get { object obj = ResourceManager.GetObject("trash", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
42.567308
172
0.601084
[ "MIT" ]
Mc-Turk/Launcher
src/FreeLauncher/Properties/Resources.Designer.cs
4,530
C#
using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MIMWebClient.Models { using System.Web.Mvc.Routing.Constraints; public class CreatePlayer { [Required(ErrorMessage = "You won't become a legend without a name!")] [MinLength(3, ErrorMessage = "What kind of name is that? Try a longer one than 2 characters.")] [RegularExpression(@"^[a-zA-Z']+$", ErrorMessage = "A name like that doesn't sound very fantasy. Try using only A to Z")] [Remote("Isname_Available", "Home")] public string Name { get; set; } [Required] public string Race { get; set; } [Required] public string Class { get; set; } [Required] public string Strength { get; set; } [Required] public string Dexterity { get; set; } [Required] public string Constitution { get; set; } [Required] public string Intelligence { get; set; } [Required] public string Wisdom { get; set; } [Required] public string Charisma { get; set; } [Required] public string Gender { get; set; } [Required(ErrorMessage = "We need your email incase you forget your password.")] [EmailAddress(ErrorMessage = "Email address needs to be valid, enter abc@email.com if you don't want to leave one. ")] public string Email { get; set; } [Required(ErrorMessage = "We need your password to protect your character.")] [MinLength(6, ErrorMessage = "Password needs to be atleast 6 characters long.")] public string Password { get; set; } [Required(ErrorMessage = "You can copy & paste your password if you like, but don't blame me if it's wrong.")] [MinLength(6, ErrorMessage = "Password needs to be atleast 6 characters long.")] [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "Your passwords do not match.")] public string ConfirmPassword { get; set; } public void savePlayer() { } } }
35.147541
130
0.606343
[ "MIT" ]
LiamKenneth/ArchaicQuest
MIMWebClient/Models/createPlayer.cs
2,146
C#
// Copyright 2017 the original author or authors. // // 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 // // https://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 Steeltoe.CloudFoundry.Connector.Services; using Xunit; namespace Steeltoe.CloudFoundry.Connector.MySql.Test { public class MySqlProviderConfigurerTest { [Fact] public void UpdateConfiguration_WithNullMySqlServiceInfo_ReturnsExpected() { MySqlProviderConfigurer configurer = new MySqlProviderConfigurer(); MySqlProviderConnectorOptions config = new MySqlProviderConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; configurer.UpdateConfiguration(null, config); Assert.Equal("localhost", config.Server); Assert.Equal(1234, config.Port); Assert.Equal("username", config.Username); Assert.Equal("password", config.Password); Assert.Equal("database", config.Database); Assert.Null(config.ConnectionString); } [Fact] public void UpdateConfiguration_WithMySqlServiceInfo_ReturnsExpected() { MySqlProviderConfigurer configurer = new MySqlProviderConfigurer(); MySqlProviderConnectorOptions config = new MySqlProviderConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; MySqlServiceInfo si = new MySqlServiceInfo("MyId", "mysql://Dd6O1BPXUHdrmzbP:7E1LxXnlH2hhlPVt@192.168.0.90:3306/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355"); configurer.UpdateConfiguration(si, config); Assert.Equal("192.168.0.90", config.Server); Assert.Equal(3306, config.Port); Assert.Equal("Dd6O1BPXUHdrmzbP", config.Username); Assert.Equal("7E1LxXnlH2hhlPVt", config.Password); Assert.Equal("cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355", config.Database); } [Fact] public void Configure_NoServiceInfo_ReturnsExpected() { MySqlProviderConnectorOptions config = new MySqlProviderConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; MySqlProviderConfigurer configurer = new MySqlProviderConfigurer(); var opts = configurer.Configure(null, config); Assert.Contains("Server=localhost;", opts); Assert.Contains("Port=1234;", opts); Assert.Contains("Username=username;", opts); Assert.Contains("Password=password;", opts); Assert.Contains("Database=database;", opts); } [Fact] public void Configure_ServiceInfoOveridesConfig_ReturnsExpected() { MySqlProviderConnectorOptions config = new MySqlProviderConnectorOptions() { Server = "localhost", Port = 1234, Username = "username", Password = "password", Database = "database" }; MySqlProviderConfigurer configurer = new MySqlProviderConfigurer(); MySqlServiceInfo si = new MySqlServiceInfo("MyId", "mysql://Dd6O1BPXUHdrmzbP:7E1LxXnlH2hhlPVt@192.168.0.90:3306/cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355"); var opts = configurer.Configure(si, config); Assert.Contains("Server=192.168.0.90;", opts); Assert.Contains("Port=3306;", opts); Assert.Contains("Username=Dd6O1BPXUHdrmzbP;", opts); Assert.Contains("Password=7E1LxXnlH2hhlPVt;", opts); Assert.Contains("Database=cf_b4f8d2fa_a3ea_4e3a_a0e8_2cd040790355;", opts); } } }
39.842105
166
0.61845
[ "Apache-2.0" ]
acesyde/steeltoe
src/Connectors/test/ConnectorBase.Test/Relational/MySql/MySqlProviderConfigurerTest.cs
4,544
C#
namespace P01_Examples { using System; using System.Linq; public class StartUp { public static void Main() { //// ================================================================= // //int lengthOfArray = int.Parse(Console.ReadLine()); //int[] array = new int[lengthOfArray]; //for (int index = 0; index < array.Length; index++) //{ // int number = int.Parse(Console.ReadLine()); // array[index] = number; //} //PrintOneDimensionalArrayWithForLoop(array); //// ================================================================= // //int[] arrayFromNumbers = Console.ReadLine() // .Split(" ", StringSplitOptions.RemoveEmptyEntries) // .Select(int.Parse) // .ToArray(); //PrintOneDimensionalArrayWithForLoop(arrayFromNumbers); //// ================================================================= // //int[] arr = { 1, 2, 3, 4, 5, 6 }; // ================================================================= // int lengthOfTwoDimensionalArray = int.Parse(Console.ReadLine()); int[,] twoDimensionalArrayOfNumbersWithForLoop = new int[lengthOfTwoDimensionalArray, lengthOfTwoDimensionalArray]; for (int row = 0; row < twoDimensionalArrayOfNumbersWithForLoop.GetLength(0); row++) { for (int col = 0; col < twoDimensionalArrayOfNumbersWithForLoop.GetLength(1); col++) { Console.Write($"[{row}, {col}] = "); int number = int.Parse(Console.ReadLine()); twoDimensionalArrayOfNumbersWithForLoop[row, col] = number; } Console.WriteLine(); } PrintArrayWithForLoop(twoDimensionalArrayOfNumbersWithForLoop); } private static void PrintArrayWithForLoop(int[,] array) { for (int row = 0; row < array.GetLength(0); row++) { for (int col = 0; col < array.GetLength(1); col++) { Console.Write(array[row, col] + " "); } Console.WriteLine(); } } // Example for overloading of methods private static void PrintArrayWithForLoop(char[] array) { Console.WriteLine("The char array elements are: "); for (int index = 0; index < array.Length; index++) { Console.Write(array[index] + " "); } Console.WriteLine(); } private static void PrintArrayWithForLoop(int[] array) { Console.WriteLine("The array elements are: "); // 1 2 3 4 5 6 for (int index = 0; index < array.Length; index++) { Console.Write(array[index] + " "); } Console.WriteLine(); } } }
32.882979
100
0.448075
[ "MIT" ]
Botche/VTU-Software-Engineering-First-Course
L06_Methods/P01_Examples/StartUp.cs
3,093
C#
// This file is part of Hangfire. // Copyright © 2013-2014 Sergey Odinokov. // // Hangfire is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 // of the License, or any later version. // // Hangfire is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with Hangfire. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.Linq; #if FEATURE_TRANSACTIONSCOPE using System.Transactions; #else using System.Data; #endif using Dapper; using Hangfire.Annotations; // ReSharper disable RedundantAnonymousTypePropertyName namespace Hangfire.SqlServer { internal class SqlServerJobQueueMonitoringApi : IPersistentJobQueueMonitoringApi { private static readonly TimeSpan QueuesCacheTimeout = TimeSpan.FromSeconds(5); private readonly SqlServerStorage _storage; private readonly object _cacheLock = new object(); private List<string> _queuesCache = new List<string>(); private Stopwatch _cacheUpdated; public SqlServerJobQueueMonitoringApi([NotNull] SqlServerStorage storage) { if (storage == null) throw new ArgumentNullException(nameof(storage)); _storage = storage; } public IEnumerable<string> GetQueues() { string sqlQuery = $@"select distinct(Queue) from [{_storage.SchemaName}].JobQueue with (nolock)"; lock (_cacheLock) { if (_queuesCache.Count == 0 || _cacheUpdated.Elapsed > QueuesCacheTimeout) { var result = _storage.UseConnection(null, connection => { return connection.Query(sqlQuery, commandTimeout: _storage.CommandTimeout).Select(x => x.Queue).ToList(); }); _queuesCache = result.FirstOrDefault(); _cacheUpdated = Stopwatch.StartNew(); } return _queuesCache.ToList(); } } public IEnumerable<long> GetEnqueuedJobIds(string queue, int @from, int perPage) { var sqlQuery = $@"select r.JobId from ( select jq.JobId, row_number() over (order by jq.Id) as row_num from [{_storage.SchemaName}].JobQueue jq with (nolock, forceseek) where jq.Queue = @queue and jq.FetchedAt is null ) as r where r.row_num between @start and @end"; return _storage.UseConnection(null, connection => { return connection.Query<JobIdDto>( sqlQuery, new { queue = queue, start = from + 1, end = @from + perPage }, commandTimeout: _storage.CommandTimeout) .ToList() .Select(x => x.JobId) .ToList(); }); } public IEnumerable<long> GetFetchedJobIds(string queue, int @from, int perPage) { var fetchedJobsSql = $@" select r.JobId from ( select jq.JobId, jq.FetchedAt, row_number() over (order by jq.Id) as row_num from [{_storage.SchemaName}].JobQueue jq with (nolock, forceseek) where jq.Queue = @queue and jq.FetchedAt is not null ) as r where r.row_num between @start and @end"; return _storage.UseConnection(null, connection => { return connection.Query<JobIdDto>( fetchedJobsSql, new { queue = queue, start = from + 1, end = @from + perPage }) .ToList() .Select(x => x.JobId) .ToList(); }); } public EnqueuedAndFetchedCountDto GetEnqueuedAndFetchedCount(string queue) { var sqlQuery = $@" select sum(Enqueued) as EnqueuedCount, sum(Fetched) as FetchedCount from ( select case when FetchedAt is null then 1 else 0 end as Enqueued, case when FetchedAt is not null then 1 else 0 end as Fetched from [{_storage.SchemaName}].JobQueue with (nolock, forceseek) where Queue = @queue ) q"; return _storage.UseConnection(null, connection => { var result = connection.Query(sqlQuery, new { queue }).Single(); return new EnqueuedAndFetchedCountDto { EnqueuedCount = result.EnqueuedCount, FetchedCount = result.FetchedCount }; }); } private class JobIdDto { [UsedImplicitly] public long JobId { get; set; } } } }
35.840278
129
0.590583
[ "MIT" ]
collabratech/HangfireApplicationPOC
Hangfire.SqlServer/SqlServerJobQueueMonitoringApi.cs
5,164
C#
using System; using System.Collections.Generic; namespace HierarchicalProgress { partial class HierarchicalProgress<TProgressReport> where TProgressReport : IProgressReport, new() { internal sealed class Unsubscriber : IDisposable { private readonly IList<IObserver<TProgressReport>> _observers; private readonly IObserver<TProgressReport> _observer; internal Unsubscriber(IList<IObserver<TProgressReport>> observers, IObserver<TProgressReport> observer) { _observers = observers; _observer = observer; } public void Dispose() { if (_observers.Contains(_observer)) _observers.Remove(_observer); } } } }
29.888889
115
0.613383
[ "MIT" ]
ProphetLamb/HierarchicalProgress
src/HierarchicalProgress.Unsubscriber.cs
809
C#
using System; using System.Collections.Generic; using System.Linq; using YJC.Toolkit.Sys; using YJC.Toolkit.MetaData; namespace YJC.Toolkit.Data { [CoreDisplayConfig(CreateDate = "2018-04-18", NamespaceType = NamespaceType.Toolkit, Author = "YJC", Description = "当浮点高于或低于某个基准值时,以指定的颜色来显示")] internal class DoubleColorDisplayConfig : IDisplay, IConfigCreator<IDisplay> { #region IDisplay 成员 public string DisplayValue(object value, Tk5FieldInfoEx field, IFieldValueProvider rowValue) { if (DisplayUtil.IsNull(value)) return string.Empty; double dblValue = value.Value<double>(); string format = string.Format(ObjectUtil.SysCulture, "{{0:{0}}}", Format); string text = string.Format(ObjectUtil.SysCulture, format, dblValue); if (dblValue > BaseValue) return DisplayText(text, HighColor); else if (dblValue < BaseValue) return DisplayText(text, LowColor); else return DisplayText(text, EqualColor); } #endregion IDisplay 成员 #region IConfigCreator<IDisplay> 成员 public IDisplay CreateObject(params object[] args) { return this; } #endregion IConfigCreator<IDisplay> 成员 [SimpleAttribute] public double BaseValue { get; private set; } [SimpleAttribute] public string HighColor { get; private set; } [SimpleAttribute] public string LowColor { get; private set; } [SimpleAttribute] public string EqualColor { get; private set; } [SimpleAttribute(DefaultValue = "0.00")] public string Format { get; private set; } private static string DisplayText(string text, string color) { if (string.IsNullOrEmpty(color)) return text; return HtmlColorDisplayConfig.DisplayColorText(text, color); } } }
30.8
100
0.619381
[ "BSD-3-Clause" ]
madiantech/tkcore
Data/YJC.Toolkit.Web.Common/Data/_Display/DoubleColorDisplayConfig.cs
2,068
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20210201Preview.Outputs { /// <summary> /// GroupMembers Item. /// </summary> [OutputType] public sealed class GroupMembersItemResponse { /// <summary> /// Resource Id. /// </summary> public readonly string? ResourceId; [OutputConstructor] private GroupMembersItemResponse(string? resourceId) { ResourceId = resourceId; } } }
24.806452
81
0.650195
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20210201Preview/Outputs/GroupMembersItemResponse.cs
769
C#
using R5.FFDB.Core.Entities; using R5.FFDB.Core.Models; using R5.Internals.PostgresMapper.Attributes; using R5.Internals.PostgresMapper.Models; using System; using System.Collections.Generic; using System.Text; namespace R5.FFDB.DbProviders.PostgreSql.Entities { [Table(TableName.TeamGameStats)] [CompositePrimaryKeys("team_id", "season", "week")] public class TeamGameStatsSql { [NotNull] [ForeignKey(typeof(TeamSql), "id")] [Column("team_id", PostgresDataType.INT)] public int TeamId { get; set; } [NotNull] [Column("season", PostgresDataType.INT)] public int Season { get; set; } [NotNull] [Column("week", PostgresDataType.INT)] public int Week { get; set; } [NotNull] [Column("points_first_quarter", PostgresDataType.INT)] public int PointsFirstQuarter { get; set; } [NotNull] [Column("points_second_quarter", PostgresDataType.INT)] public int PointsSecondQuarter { get; set; } [NotNull] [Column("points_third_quarter", PostgresDataType.INT)] public int PointsThirdQuarter { get; set; } [NotNull] [Column("points_fourth_quarter", PostgresDataType.INT)] public int PointsFourthQuarter { get; set; } [NotNull] [Column("points_overtime", PostgresDataType.INT)] public int PointsOverTime { get; set; } [NotNull] [Column("points_total", PostgresDataType.INT)] public int PointsTotal { get; set; } [NotNull] [Column("first_downs", PostgresDataType.INT)] public int FirstDowns { get; set; } [NotNull] [Column("total_yards", PostgresDataType.INT)] public int TotalYards { get; set; } [NotNull] [Column("passing_yards", PostgresDataType.INT)] public int PassingYards { get; set; } [NotNull] [Column("rushing_yards", PostgresDataType.INT)] public int RushingYards { get; set; } [NotNull] [Column("penalties", PostgresDataType.INT)] public int Penalties { get; set; } [NotNull] [Column("penalty_yards", PostgresDataType.INT)] public int PenaltyYards { get; set; } [NotNull] [Column("turnovers", PostgresDataType.INT)] public int Turnovers { get; set; } [NotNull] [Column("punts", PostgresDataType.INT)] public int Punts { get; set; } [NotNull] [Column("punt_yards", PostgresDataType.INT)] public int PuntYards { get; set; } [NotNull] [Column("time_of_posession", PostgresDataType.INT)] public int TimeOfPossessionSeconds { get; set; } public static TeamGameStatsSql FromCoreEntity(TeamWeekStats stats) { return new TeamGameStatsSql { TeamId = stats.TeamId, Season = stats.Week.Season, Week = stats.Week.Week, PointsFirstQuarter = stats.PointsFirstQuarter, PointsSecondQuarter = stats.PointsSecondQuarter, PointsThirdQuarter = stats.PointsThirdQuarter, PointsFourthQuarter = stats.PointsFourthQuarter, PointsOverTime = stats.PointsOverTime, PointsTotal = stats.PointsTotal, FirstDowns = stats.FirstDowns, TotalYards = stats.TotalYards, PassingYards = stats.PassingYards, RushingYards = stats.RushingYards, Penalties = stats.Penalties, PenaltyYards = stats.PenaltyYards, Turnovers = stats.Turnovers, Punts = stats.Punts, PuntYards = stats.PuntYards, TimeOfPossessionSeconds = stats.TimeOfPossessionSeconds }; } public static TeamWeekStats ToCoreEntity(TeamGameStatsSql sql) { return new TeamWeekStats { TeamId = sql.TeamId, Week = new WeekInfo(sql.Season, sql.Week), PointsFirstQuarter = sql.PointsFirstQuarter, PointsSecondQuarter = sql.PointsSecondQuarter, PointsThirdQuarter = sql.PointsThirdQuarter, PointsFourthQuarter = sql.PointsFourthQuarter, PointsOverTime = sql.PointsOverTime, PointsTotal = sql.PointsTotal, FirstDowns = sql.FirstDowns, TotalYards = sql.TotalYards, PassingYards = sql.PassingYards, RushingYards = sql.RushingYards, Penalties = sql.Penalties, PenaltyYards = sql.PenaltyYards, Turnovers = sql.Turnovers, Punts = sql.Punts, PuntYards = sql.PuntYards, TimeOfPossessionSeconds = sql.TimeOfPossessionSeconds }; } } }
28.145833
68
0.721194
[ "MIT" ]
rushfive/FFDB
DatabaseProviders/R5.FFDB.DbProviders.PostgreSql/Entities/TeamGameStatsSql.cs
4,055
C#
using System; using System.Reflection; using System.Linq; using Modding.Humankind.DevTools; using Modding.Humankind.DevTools.Core; using UnityEngine; using Amplitude.Mercury; using Amplitude.Mercury.Interop; namespace DevTools.Humankind.GUITools.UI { public interface IDataType { } public interface IEmpireSnapshotDataType : IDataType { } public class GameStatsSnapshot { public int Turn { get; set; } public int GameID { get; set; } public int GameSpeedLevel { get; set; } public EmpireSnapshot[] Empires; public int LocalEmpireIndex { get; set; } public int AtmospherePollutionLevel { get; set; } public int AtmospherePollutionStock { get; set; } public int AtmospherePollutionNet { get; set; } public GameStatsSnapshot() { Snapshot(); } public GameStatsSnapshot Snapshot() { Turn = HumankindGame.Turn; GameSpeedLevel = HumankindGame.GameSpeedLevel; if (GameID != HumankindGame.GameID) { GameID = HumankindGame.GameID; Empires = HumankindGame.Empires.Select(empire => new EmpireSnapshot(empire)).ToArray(); } else { var empires = HumankindGame.Empires; for (var i = 0; i < Empires.Length; i++) { Empires[i].Snapshot(empires[i]); } } var pollutionData = Snapshots.PollutionSnapshot.PresentationData; AtmospherePollutionLevel = pollutionData.AtmospherePollutionLevel + 1; AtmospherePollutionStock = (int) pollutionData.AtmospherePollutionStock; AtmospherePollutionNet = (int) pollutionData.AtmospherePollutionNet; return this; } public GameStatsSnapshot SetLocalEmpireIndex(int localEmpireIndex) { LocalEmpireIndex = localEmpireIndex; return this; } } public class EmpireSnapshot : IEmpireSnapshotDataType { public string[] Values; private string primaryColor = "#FFFFFFFF"; private Color color = Color.white; private string secondaryColor = "#000000FF"; private Color contrastColor = Color.black; public string PrimaryColor => primaryColor; public Color Color => color; public string SecondaryColor => secondaryColor; public Color ContrastColor => contrastColor; public string UserName = string.Empty; public int Index { get; private set; } public EmpireSnapshot(HumankindEmpire empire) { Snapshot(empire); } public EmpireSnapshot Snapshot(HumankindEmpire empire) { Index = empire.EmpireIndex; Values = EmpireSnapshotUtils.MakeEmpireSnapshotValues(empire); if (R.Text.NormalizeColor(empire.PrimaryColor) != primaryColor) { primaryColor = R.Text.NormalizeColor(empire.PrimaryColor); if (ColorUtility.TryParseHtmlString(primaryColor, out Color parsedColor)) { color = parsedColor; if (hasBetterContrastWithBlackColor((Color32)parsedColor)) { secondaryColor = "#000000FF"; contrastColor = Color.black; } else { secondaryColor = "#FFFFFFFF"; contrastColor = Color.white; } } } UserName = GetPlayerIdentifierUserName(empire) ?? string.Empty; if (UserName.Length == 0) UserName = PersonaName; return this; } public bool hasBetterContrastWithBlackColor(Color32 bg) { int nThreshold = 105; int bgDelta = Convert.ToInt32((bg.r * 0.299) + (bg.g * 0.587) + (bg.b * 0.114)); return (255 - bgDelta < nThreshold); } private static FieldInfo PlayerIdentifierField = R.GetField<Amplitude.Mercury.Simulation.Empire>("PlayerIdentifier", R.NonPublicInstance); private static string GetPlayerIdentifierUserName(HumankindEmpire empire) { PlayerIdentifier playerIdentifier = (PlayerIdentifier)PlayerIdentifierField.GetValue((Amplitude.Mercury.Simulation.Empire)empire.Simulation); return playerIdentifier.UserName; } public string EmpireIndex => Values[0]; public string PersonaName => Values[1]; public string TerritoryCount => Values[2]; public string CityCount => Values[3]; public string CityCap => Values[4]; public string Stability => Values[5]; public string EraLevel => Values[6]; public string SumOfEraStars => Values[7]; public string SettlementsPopulation => Values[8]; public string EmpirePopulation => Values[9]; public string CombatStrength => Values[10]; public string ArmyCount => Values[11]; public string UnitCount => Values[12]; public string MilitaryUpkeep => Values[13]; public string CompletedTechnologiesCount => Values[14]; public string ResearchNet => Values[15]; public string TechnologicalEraOffset => Values[16]; public string AvailableTechnologiesCount => Values[17]; public string UnlockedTechnologiesCount => Values[18]; public string MoneyStock => Values[19]; public string MoneyNet => Values[20]; public string InfluenceStock => Values[21]; public string InfluenceNet => Values[22]; public string LuxuryResourcesAccessCount => Values[23]; public string StrategicResourcesAccessCount => Values[24]; public string TradeNodesCount => Values[25]; public string PollutionStock => Values[26]; public string PollutionNet => Values[27]; } public static class EmpireSnapshotUtils { public static string[] MakeEmpireSnapshotValues(HumankindEmpire empire) { EmpireInfo empireInfo; try { empireInfo = Snapshots.GameSnapshot.PresentationData.EmpireInfo[empire.EmpireIndex]; } catch (Exception) { empireInfo = new EmpireInfo(); } return new[] { $"{empire.EmpireIndex}", $"{empire.PersonaName}", $"{empire.TerritoryCount}", $"{empire.CityCount}", $"{empire.CityCap}", $"{empire.Stability}", $"{empire.EraLevel}", $"{empire.SumOfEraStars}", $"{empire.SettlementsPopulation}", $"{empire.EmpirePopulation}", $"{empire.CombatStrength}", $"{empire.ArmyCount}", $"{empire.UnitCount}", $"{empire.MilitaryUpkeep}", $"{empire.CompletedTechnologiesCount}", $"{empire.ResearchNet}", $"{empire.TechnologicalEraOffset}", $"{empire.AvailableTechnologiesCount}", $"{empire.UnlockedTechnologiesCount}", $"{empire.MoneyStock}", empire.MoneyNet > 0 ? $"+{empire.MoneyNet}" : $"{empire.MoneyNet}", $"{empire.InfluenceStock}", $"{empire.InfluenceNet}", $"{empire.LuxuryResourcesAccessCount}", $"{empire.StrategicResourcesAccessCount}", $"{empire.TradeNodesCount}", $"{(int)empireInfo.PollutionStock}", $"{(int)empireInfo.PollutionNet}", }; } } }
35.828829
153
0.570153
[ "MIT" ]
Theadd/Humankind-GUI-Tools
UI/Statistics/GameStatsSnapshot.cs
7,954
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview { using static Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Runtime.Extensions; /// <summary>The response to an enumeration operation on DNS resolvers.</summary> public partial class DnsResolverListResult : Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolverListResult, Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolverListResultInternal { /// <summary>Internal Acessors for NextLink</summary> string Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolverListResultInternal.NextLink { get => this._nextLink; set { {_nextLink = value;} } } /// <summary>Backing field for <see cref="NextLink" /> property.</summary> private string _nextLink; /// <summary>The continuation token for the next page of results.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Origin(Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.PropertyOrigin.Owned)] public string NextLink { get => this._nextLink; } /// <summary>Backing field for <see cref="Value" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolver[] _value; /// <summary>Enumeration of the DNS resolvers.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Origin(Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolver[] Value { get => this._value; set => this._value = value; } /// <summary>Creates an new <see cref="DnsResolverListResult" /> instance.</summary> public DnsResolverListResult() { } } /// The response to an enumeration operation on DNS resolvers. public partial interface IDnsResolverListResult : Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Runtime.IJsonSerializable { /// <summary>The continuation token for the next page of results.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Runtime.Info( Required = false, ReadOnly = true, Description = @"The continuation token for the next page of results.", SerializedName = @"nextLink", PossibleTypes = new [] { typeof(string) })] string NextLink { get; } /// <summary>Enumeration of the DNS resolvers.</summary> [Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Runtime.Info( Required = false, ReadOnly = false, Description = @"Enumeration of the DNS resolvers.", SerializedName = @"value", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolver) })] Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolver[] Value { get; set; } } /// The response to an enumeration operation on DNS resolvers. internal partial interface IDnsResolverListResultInternal { /// <summary>The continuation token for the next page of results.</summary> string NextLink { get; set; } /// <summary>Enumeration of the DNS resolvers.</summary> Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Models.Api20200401Preview.IDnsResolver[] Value { get; set; } } }
54.28169
184
0.70602
[ "MIT" ]
Agazoth/azure-powershell
src/DnsResolver/generated/api/Models/Api20200401Preview/DnsResolverListResult.cs
3,784
C#
using System; namespace LanguageServer.Parameters.Workspace { /// <summary> /// For <c>workspace/configuration</c> /// </summary> /// <remarks> /// A <c>ConfigurationItem</c> consist of the configuration section to ask for /// and an additional scope URI. /// </remarks> /// <seealso>Spec 3.6.0</seealso> public class ConfigurationItem { /// <summary> /// The scope to get the configuration section for. /// </summary> /// <seealso>Spec 3.6.0</seealso> public Uri scopeUri { get; set; } /// <summary> /// The configuration section asked for. /// </summary> /// <seealso>Spec 3.6.0</seealso> public string section { get; set; } } }
27.107143
82
0.5639
[ "MIT" ]
matarillo/LanguageServerProtocol
LanguageServer/Parameters/Workspace/ConfigurationItem.cs
761
C#
using Sharpnado.MaterialFrame; using Xamarin.Forms; namespace GitTrends { public class DarkTheme : BaseTheme { public const string PageBackgroundColorHex = "#121212"; const string _offWhite = "#F0EFEF"; const string _primaryTextHex = "#CCBAC4"; const string _primaryTealHex = "#98CDC6"; const string _accentYellowHex = "#FDD59B"; const string _accentOrangeHex = "#FCBAA2"; const string _toolbarTextHex = "#FFFFFF"; const string _textHex = "#FFFFFF"; const string _iconColor = "#FFFFFF"; const string _buttonTextColor = "#FFFFFF"; const string _accentLightBlueHex = "#F0EFEF"; const string _accentPurpleHex = "#C795CA"; const string _accentIndigoHex = "#5D6AB1"; const string _cardSurfaceHex = "#1D2221"; const string _toolbarSurfaceHex = "#1E2423"; const string _circleImageBackgroundHex = "#FFFFFF"; const string _githubButtonSurfaceHex = "#231F20"; //Saturated colors from light theme const string _lightAccentYellowHex = "#FCBC66"; const string _lightAccentOrangeHex = CoralColorHex; const string _lightAccentLightBlueHex = "#66A7FC"; const string _lightAccentPurpleHex = "#8F3795"; const string _lightPrimaryTealHex = LightTealColorHex; //Graph Palette const string _saturatedLightBlueHex = "#2BC3BE"; const string _saturatedIndigoHex = "#5D6AB1"; const string _saturatedYellowHex = "#FFC534"; const string _saturatedPinkHex = "#F2726F"; //Blended Colors const string _white12PercentBlend = "#2F2F2F"; //Surface Elvations const string _surfaceElevation0dpHex = "#121212"; const string _surfaceElevation1dpHex = "#181B1B"; const string _surfaceElevation2dpHex = "#1B1F1F"; const string _surfaceElevation3dpHex = "#1C2120"; const string _surfaceElevation4dpHex = "#1D2221"; const string _surfaceElevation6dpHex = "#1F2625"; const string _surfaceElevation8dpHex = "#212827"; const string _surfaceElevation12dpHex = "#232B2A"; const string _surfaceElevation16dpHex = "#242D2C"; const string _surfaceElevation24dpHex = "#262F2E"; //Surfaces public override Color NavigationBarBackgroundColor { get; } = Color.FromHex(_toolbarSurfaceHex); public override Color NavigationBarTextColor { get; } = Color.FromHex(_toolbarTextHex); public override Color PageBackgroundColor { get; } = Color.FromHex(PageBackgroundColorHex); public override Color PageBackgroundColor_85Opactity { get; } = Color.FromHex(PageBackgroundColorHex).MultiplyAlpha(0.85); //Text public override Color PrimaryTextColor { get; } = Color.FromHex(_primaryTextHex); public override Color TextColor { get; } = Color.FromHex(_textHex); //Chart public override Color TotalViewsColor { get; } = Color.FromHex(_saturatedLightBlueHex); public override Color TotalUniqueViewsColor { get; } = Color.FromHex(_saturatedIndigoHex); public override Color TotalClonesColor { get; } = Color.FromHex(_saturatedYellowHex); public override Color TotalUniqueClonesColor { get; } = Color.FromHex(_saturatedPinkHex); public override Color ChartAxisTextColor { get; } = Color.FromHex(_primaryTextHex); public override Color ChartAxisLineColor { get; } = Color.FromHex(_primaryTextHex); //Components //Splash public override Color SplashScreenStatusColor { get; } = Color.FromHex(_offWhite); //Icons public override Color IconColor { get; } = Color.FromHex(_primaryTealHex); public override Color IconPrimaryColor { get; } = Color.FromHex(_lightPrimaryTealHex); //Buttons public override Color ButtonTextColor { get; } = Color.FromHex(_lightPrimaryTealHex); public override Color ButtonBackgroundColor { get; } = Color.FromHex(_buttonTextColor); //Indicators public override Color ActivityIndicatorColor { get; } = Color.FromHex(_lightPrimaryTealHex); public override Color PullToRefreshColor { get; } = Device.RuntimePlatform is Device.iOS ? Color.FromHex(_lightPrimaryTealHex) : Color.FromHex(_toolbarSurfaceHex); //Card public override Color CardSurfaceColor { get; } = Color.FromHex(_cardSurfaceHex); public override Color CardBorderColor { get; } = Color.FromHex(_cardSurfaceHex); public override Color SeparatorColor { get; } = Color.FromHex(_white12PercentBlend); //Card Stats Color public override Color CardStarsStatsTextColor { get; } = Color.FromHex(_lightAccentYellowHex); public override Color CardStarsStatsIconColor { get; } = Color.FromHex(_lightAccentYellowHex); public override Color CardForksStatsTextColor { get; } = Color.FromHex(_lightPrimaryTealHex); public override Color CardForksStatsIconColor { get; } = Color.FromHex(_lightPrimaryTealHex); public override Color CardIssuesStatsTextColor { get; } = Color.FromHex(_lightAccentOrangeHex); public override Color CardIssuesStatsIconColor { get; } = Color.FromHex(_lightAccentOrangeHex); public override Color CardViewsStatsTextColor { get; } = Color.FromHex(_saturatedLightBlueHex); public override Color CardViewsStatsIconColor { get; } = Color.FromHex(_saturatedLightBlueHex); public override Color CardClonesStatsTextColor { get; } = Color.FromHex(_saturatedYellowHex); public override Color CardClonesStatsIconColor { get; } = Color.FromHex(_saturatedYellowHex); public override Color CardUniqueViewsStatsTextColor { get; } = Color.FromHex(_saturatedIndigoHex); public override Color CardUniqueViewsStatsIconColor { get; } = Color.FromHex(_saturatedIndigoHex); public override Color CardUniqueClonesStatsTextColor { get; } = Color.FromHex(_saturatedPinkHex); public override Color CardUniqueClonesStatsIconColor { get; } = Color.FromHex(_saturatedPinkHex); public override Color CardTrendingStatsColor { get; } = Color.FromHex(_primaryTealHex); //Settings Components public override Color SettingsLabelTextColor { get; } = Color.FromHex(_textHex); public override Color BorderButtonBorderColor { get; } = Color.FromHex(_white12PercentBlend); public override Color BorderButtonFontColor { get; } = Color.FromHex(_textHex); public override Color TrendsChartSettingsSelectionIndicatorColor { get; } = Color.FromHex(_lightPrimaryTealHex); public override Color GitTrendsImageBackgroundColor { get; } = Color.FromHex("4CADA2"); public override Color GitHubButtonSurfaceColor { get; } = Color.FromHex(_githubButtonSurfaceHex); public override Color GitHubHandleColor { get; } = Color.FromHex(_primaryTextHex); public override Color PrimaryColor { get; } = Color.FromHex(_primaryTealHex); public override Color CloseButtonTextColor { get; } = Color.FromHex(_toolbarTextHex); public override Color CloseButtonBackgroundColor { get; } = Color.FromHex(_cardSurfaceHex); public override Color PickerBorderColor { get; } = Color.FromHex(_white12PercentBlend); public override string GitTrendsImageSource { get; } = "GitTrendsWhite"; public override string DefaultProfileImageSource { get; } = "DefaultProfileImageWhite"; public override string DefaultReferringSiteImageSource { get; } = "DefaultReferringSiteImage"; public override MaterialFrame.Theme MaterialFrameTheme { get; } = MaterialFrame.Theme.Dark; } }
51.726619
166
0.761335
[ "MIT" ]
Tiamat-Tech/GitTrends
GitTrends/Themes/DarkTheme.cs
7,192
C#
using System; namespace Sdl.Tridion.Api.IqQuery { /// <summary> /// Query Exception /// </summary> public class QueryException : Exception { public QueryException(string msg) : base(msg) { } public QueryException(string msg, Exception innerException) : base(msg, innerException) { } } }
19.052632
95
0.582873
[ "Apache-2.0" ]
RWS/graphql-client-dotnet
net/src/Sdl.Tridion.Api.Client/IqQuery/API/QueryException.cs
364
C#
using UnityEngine; using System.Collections; public class FlagHold : MonoBehaviour { public FlagTrigger flagHeld; Transform prevParent; public bool hasFlag = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void grabFlag(FlagTrigger flag) { prevParent = flag.transform.parent; flag.transform.parent = gameObject.transform; flagHeld = flag; hasFlag = true; } public void dropFlag() { if (flagHeld != null) { hasFlag = false; flagHeld.transform.parent = prevParent; flagHeld.enableCollider(); flagHeld = null; } } public void dropFlagToBase() { if (flagHeld != null) { hasFlag = false; flagHeld.backToBase(); flagHeld = null; } } }
18.959184
53
0.558665
[ "MIT" ]
Keithdae/Incredible-Ninja-Kart
Assets/Scripts/CTF/FlagHold.cs
931
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using XUnity.AutoTranslator.Plugin.Core.Configuration; using XUnity.AutoTranslator.Plugin.Core.Endpoints; using XUnity.AutoTranslator.Plugin.Core.Extensions; using XUnity.Common.Extensions; using XUnity.Common.Logging; namespace XUnity.AutoTranslator.Plugin.Core { class SpamChecker { private int[] _currentTranslationsQueuedPerSecondRollingWindow = new int[ Settings.TranslationQueueWatchWindow ]; private float? _timeExceededThreshold; private float _translationsQueuedPerSecond; private string[] _previouslyQueuedText = new string[ Settings.PreviousTextStaggerCount ]; private int _staggerTextCursor = 0; private int _concurrentStaggers = 0; private int _lastStaggerCheckFrame = -1; private int _frameForLastQueuedTranslation = -1; private int _consecutiveFramesTranslated = 0; private int _secondForQueuedTranslation = -1; private int _consecutiveSecondsTranslated = 0; private TranslationManager _translationManager; public SpamChecker( TranslationManager translationManager ) { _translationManager = translationManager; } public void PerformChecks( string untranslatedText, TranslationEndpointManager endpoint ) { CheckStaggerText( untranslatedText ); CheckConsecutiveFrames(); CheckConsecutiveSeconds( endpoint ); CheckThresholds( endpoint ); } public void Update() { PeriodicResetFrameCheck(); ResetThresholdTimerIfRequired(); } private void CheckConsecutiveSeconds( TranslationEndpointManager endpoint ) { var currentSecond = (int)Time.time; var lastSecond = currentSecond - 1; if( lastSecond == _secondForQueuedTranslation ) { // we also queued something last frame, lets increment our counter _consecutiveSecondsTranslated++; if( _consecutiveSecondsTranslated > Settings.MaximumConsecutiveSecondsTranslated && endpoint.EnableSpamChecks ) { // Shutdown, this wont be tolerated!!! _translationManager.ClearAllJobs(); Settings.IsShutdown = true; XuaLogger.AutoTranslator.Error( $"SPAM DETECTED: Translations were queued every second for more than {Settings.MaximumConsecutiveSecondsTranslated} consecutive seconds. Shutting down plugin." ); } } else if( currentSecond == _secondForQueuedTranslation ) { // do nothing, there may be multiple translations per frame, that wont increase this counter } else { // but if multiple Update frames has passed, we will reset the counter _consecutiveSecondsTranslated = 0; } _secondForQueuedTranslation = currentSecond; } private void CheckConsecutiveFrames() { var currentFrame = Time.frameCount; var lastFrame = currentFrame - 1; if( lastFrame == _frameForLastQueuedTranslation ) { // we also queued something last frame, lets increment our counter _consecutiveFramesTranslated++; if( _consecutiveFramesTranslated > Settings.MaximumConsecutiveFramesTranslated ) { // Shutdown, this wont be tolerated!!! _translationManager.ClearAllJobs(); Settings.IsShutdown = true; XuaLogger.AutoTranslator.Error( $"SPAM DETECTED: Translations were queued every frame for more than {Settings.MaximumConsecutiveFramesTranslated} consecutive frames. Shutting down plugin." ); } } else if( currentFrame == _frameForLastQueuedTranslation ) { // do nothing, there may be multiple translations per frame, that wont increase this counter } else if( _consecutiveFramesTranslated > 0 ) { // but if multiple Update frames has passed, we will reset the counter _consecutiveFramesTranslated--; } _frameForLastQueuedTranslation = currentFrame; } private void PeriodicResetFrameCheck() { var currentSecond = (int)Time.time; if( currentSecond % 100 == 0 ) { _consecutiveFramesTranslated = 0; } } private void CheckStaggerText( string untranslatedText ) { var currentFrame = Time.frameCount; if( currentFrame != _lastStaggerCheckFrame ) { _lastStaggerCheckFrame = currentFrame; bool wasProblematic = false; for( int i = 0; i < _previouslyQueuedText.Length; i++ ) { var previouslyQueuedText = _previouslyQueuedText[ i ]; if( previouslyQueuedText != null ) { if( untranslatedText.RemindsOf( previouslyQueuedText ) ) { wasProblematic = true; break; } } } if( wasProblematic ) { _concurrentStaggers++; if( _concurrentStaggers > Settings.MaximumStaggers ) { _translationManager.ClearAllJobs(); Settings.IsShutdown = true; XuaLogger.AutoTranslator.Error( $"SPAM DETECTED: Text that is 'scrolling in' is being translated. Disable that feature. Shutting down plugin." ); } } else { _concurrentStaggers = 0; } _previouslyQueuedText[ _staggerTextCursor % _previouslyQueuedText.Length ] = untranslatedText; _staggerTextCursor++; } } private void CheckThresholds( TranslationEndpointManager endpoint ) { if( _translationManager.UnstartedTranslations > Settings.MaxUnstartedJobs ) { _translationManager.ClearAllJobs(); Settings.IsShutdown = true; XuaLogger.AutoTranslator.Error( $"SPAM DETECTED: More than {Settings.MaxUnstartedJobs} queued for translations due to unknown reasons. Shutting down plugin." ); } var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow; var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow; if( previousIdx != newIdx ) { _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0; } _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ]++; var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum(); _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow; if( _translationsQueuedPerSecond > Settings.MaxTranslationsQueuedPerSecond ) { if( !_timeExceededThreshold.HasValue ) { _timeExceededThreshold = Time.time; } if( Time.time - _timeExceededThreshold.Value > Settings.MaxSecondsAboveTranslationThreshold && endpoint.EnableSpamChecks ) { _translationManager.ClearAllJobs(); Settings.IsShutdown = true; XuaLogger.AutoTranslator.Error( $"SPAM DETECTED: More than {Settings.MaxTranslationsQueuedPerSecond} translations per seconds queued for a {Settings.MaxSecondsAboveTranslationThreshold} second period. Shutting down plugin." ); } } else { _timeExceededThreshold = null; } } private void ResetThresholdTimerIfRequired() { var previousIdx = ( (int)( Time.time - Time.deltaTime ) ) % Settings.TranslationQueueWatchWindow; var newIdx = ( (int)Time.time ) % Settings.TranslationQueueWatchWindow; if( previousIdx != newIdx ) { _currentTranslationsQueuedPerSecondRollingWindow[ newIdx ] = 0; } var translationsInWindow = _currentTranslationsQueuedPerSecondRollingWindow.Sum(); _translationsQueuedPerSecond = (float)translationsInWindow / Settings.TranslationQueueWatchWindow; if( _translationsQueuedPerSecond <= Settings.MaxTranslationsQueuedPerSecond ) { _timeExceededThreshold = null; } } } }
36.724138
241
0.635329
[ "MIT" ]
czahoi/XUnity.AutoTranslator
src/XUnity.AutoTranslator.Plugin.Core/SpamChecker.cs
8,522
C#
using UnityEngine; using System; // Debug.Log($"positionInBlendedSamples: {positionInBlendedSamples} halfOfWindowLength:{halfOfWindowLength} bin length 0: {_bins.GetLength(0)} bin length 1: {_bins.GetLength(1)}"); namespace TheAlterscope2 { //This class creates time stretched audio without altering the pitch. public class ConstantPitchTimeScale : MonoBehaviour { public static float ChangeFactor { get; set; } public static int ScaledLength { get; private set; } float[,] _bins; float[] _inputSamples; float[] _blendedSamples; int _binLength; int _halfBinLength; int _numberOfBins; int _rampLength; public void Create(float[] inputSamples, float changeFactor = 1f, int binLength = 4096, float rampProportion = 0.25f) { if (binLength > inputSamples.Length) { float[] minimumLengthArray = new float[binLength]; Array.Copy(inputSamples, minimumLengthArray, inputSamples.Length); inputSamples = minimumLengthArray; // throw new ArgumentOutOfRangeException($"binLength: {binLength} must be less than inputSample.Length: {inputSamples.Length}"); } if (rampProportion > 1f || rampProportion < 0f) throw new ArgumentOutOfRangeException("rampProportion must be between 0 and 1"); if (inputSamples == null) throw new ArgumentException("inputSamples cannot be null"); _inputSamples = new float[inputSamples.Length]; _rampLength = (int)((float)binLength * rampProportion); _halfBinLength = binLength / 2; _binLength = binLength; _numberOfBins = (int)Math.Ceiling((float)_inputSamples.Length / (float)_halfBinLength); inputSamples.CopyTo(_inputSamples, 0); if (changeFactor != 1f) SetChangeFactor(changeFactor); } public void SetChangeFactor(float changeFactor) { if (changeFactor >= 1.5f) throw new ArgumentOutOfRangeException("changeFactor must be less than 1.5"); ChangeFactor = changeFactor; ScaledLength = (int)Math.Ceiling((float)_inputSamples.Length * changeFactor); } public void GetModifiedAudio(out float[] targetSamples) { InitializeBins(); BlendBins(); targetSamples = new float[_blendedSamples.Length]; _blendedSamples.CopyTo(targetSamples, 0); } void InitializeBins() { _bins = new float[_numberOfBins, _binLength]; for (var positionInInputSamples = 0; positionInInputSamples < _inputSamples.Length; ++positionInInputSamples) { _bins[LeftHalfBinNumber(positionInInputSamples) - 1, positionInInputSamples % _halfBinLength] = _inputSamples[positionInInputSamples]; if (RightHalfBinNumber(positionInInputSamples) > 0) _bins[RightHalfBinNumber(positionInInputSamples) - 1, (positionInInputSamples % _halfBinLength) + _halfBinLength] = _inputSamples[positionInInputSamples]; } } int LeftHalfBinNumber(int positionInInputSamples) => (int)((positionInInputSamples / _halfBinLength) + 1); int RightHalfBinNumber(int positionInInputSamples) => LeftHalfBinNumber(positionInInputSamples) - 1; void BlendBins() { int halfOfWindowLength = (int)Math.Ceiling((float)_halfBinLength * ChangeFactor); _blendedSamples = new float[ScaledLength]; var positionInWindow = 0; for (var positionInBlendedSamples = 0; positionInBlendedSamples < _blendedSamples.Length; ++positionInBlendedSamples) { bool isWithinRamp = ((int)((positionInBlendedSamples - _rampLength) / halfOfWindowLength) != (int)(positionInBlendedSamples / halfOfWindowLength)) && positionInBlendedSamples > _rampLength; bool isWithinLastBin = (positionInBlendedSamples / halfOfWindowLength) + 1 == _numberOfBins; if (isWithinRamp && !isWithinLastBin) { float rightScaleAmount = (float)positionInWindow / (float)_rampLength; float leftScaleAmount = (float)(1 - rightScaleAmount); float rightSampleValue = _bins[(positionInBlendedSamples / halfOfWindowLength), positionInBlendedSamples % halfOfWindowLength]; float leftSampleValue = _bins[(positionInBlendedSamples / halfOfWindowLength) - 1, (positionInBlendedSamples % halfOfWindowLength) + halfOfWindowLength]; _blendedSamples[positionInBlendedSamples] = leftSampleValue * leftScaleAmount + rightSampleValue * rightScaleAmount; ++positionInWindow; } else { _blendedSamples[positionInBlendedSamples] = _bins[positionInBlendedSamples / halfOfWindowLength, positionInBlendedSamples % halfOfWindowLength]; positionInWindow = 0; } } } } }
49.361905
205
0.640556
[ "Apache-2.0" ]
mattlandau/TheAlterscope3
TheAlterscope3/Assets/Scripts/ConversationScripts/ConstantPitchTimeScale.cs
5,185
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; using List_ForEach_Action; using List_ListUtils; namespace List_ForEach_Action { public class Driver<T> { public bool Verify(T[] items) { bool retValue = true; retValue &= Test.Eval(VerifyVanilla(items), "Err_1828ahiudioe VerifyVanilla FAILD\n"); retValue &= Test.Eval(VerifyExceptions(items), "Err_848ajode VerifyExceptions FAILD\n"); return retValue; } public bool VerifyVanilla(T[] items) { bool retValue = true; List<T> list = new List<T>(); List<T> visitedItems = new List<T>(); Action<T> action = delegate (T item) { visitedItems.Add(item); }; bool typeNullable = default(T) == null; for (int i = 0; i < items.Length; ++i) list.Add(items[i]); //[] Verify ForEach looks at every item visitedItems.Clear(); list.ForEach(action); retValue &= Test.Eval(VerifyList(list, visitedItems), "Err_282308ahid Verify ForEach looks at every item FAILED\n"); return retValue; } public bool VerifyExceptions(T[] items) { bool retValue = true; List<T> list = new List<T>(); for (int i = 0; i < items.Length; ++i) list.Add(items[i]); //[] Verify Null match retValue &= Test.Eval(VerifyException(list, null, typeof(ArgumentNullException)), "Err_858ahia Expected null match to throw ArgumentNullException"); return retValue; } private bool VerifyException(List<T> list, Action<T> action, Type expectedExceptionType) { bool printException = false; bool retValue = true; try { list.ForEach(action); retValue &= Test.Eval(false, "Err_2987298ahid Expected {0} exception to be thrown", expectedExceptionType); } catch (Exception e) { retValue &= Test.Eval(e.GetType() == expectedExceptionType, "Err_1282haid Expected {0} to be thrown and the following was thrown:\n{1}", expectedExceptionType, e); if (printException) Console.WriteLine("INFO:\n" + e); } return retValue; } private bool VerifyList(List<T> list, List<T> expectedItems) { bool retValue = true; retValue &= Test.Eval(list.Count == expectedItems.Count, "Err_2828ahid Expected Count={0} actual={1}", expectedItems.Count, list.Count); // Do not continue if the expected and actual lengths differ if (!retValue) return false; //Only verify the indexer. List should be in a good enough state that we //do not have to verify consistancy with any other method. for (int i = 0; i < list.Count; ++i) { retValue &= Test.Eval(list[i] == null ? expectedItems[i] == null : list[i].Equals(expectedItems[i]), "Err_19818ayiadb Expceted List[{0}]={1} actual={2}", i, expectedItems[i], list[i]); } return retValue; } public void CallForEach(T[] items, Action<T> action) { List<T> list = new List<T>(); List<T> visitedItems = new List<T>(); for (int i = 0; i < items.Length; ++i) list.Add(items[i]); Assert.Throws<ArgumentNullException>("action", () => list.ForEach(null)); list.ForEach(action); } } } public class TestCase { [Fact] public static void RunTests() { Driver<int> intDriver = new Driver<int>(); Driver<string> stringDriver = new Driver<string>(); int[] intArray; string[] stringArray; int arraySize = 16; int sum = 0; intArray = new int[arraySize]; stringArray = new string[arraySize]; for (int i = 0; i < arraySize; ++i) { intArray[i] = i + 1; stringArray[i] = (i + 1).ToString(); } sum = 0; Test.Eval(intDriver.Verify(new int[0]), "Err_2829ahdi Empty List<int> FAILED\n"); Test.Eval(intDriver.Verify(new int[] { 1 }), "Err_8488ahoid List<int> with 1 item FAILED\n"); Test.Eval(intDriver.Verify(intArray), "Err_8948ajod List<int> with more then 1 item FAILED\n"); intDriver.CallForEach(intArray, delegate (int item) { sum += item; }); Test.Eval(sum == ((arraySize * (arraySize + 1)) / 2), "Err_2790ahid List<int> Expected Sum to return:{0} atcual={1} FAILED\n", (arraySize * (arraySize + 1)) / 2, sum); sum = 0; Test.Eval(stringDriver.Verify(new string[0]), "Err_5088ahisa Empty List<string> FAILED\n"); Test.Eval(stringDriver.Verify(new string[] { "1" }), "Err_3684ahieaz List<string> with 1 item FAILED\n"); Test.Eval(stringDriver.Verify(stringArray), "Err_30250aiwg List<string> with more then 1 item FAILED\n"); stringDriver.CallForEach(stringArray, delegate (string item) { sum += Convert.ToInt32(item); }); Test.Eval(sum == ((arraySize * (arraySize + 1)) / 2), "Err_2790ahid List<string> Expected Sum to return:{0} atcual={1} FAILED\n", (arraySize * (arraySize + 1)) / 2, sum); Assert.True(Test.result); } }
36.189873
178
0.569955
[ "MIT" ]
er0dr1guez/corefx
src/System.Collections/tests/Generic/List/ForEach_Action.cs
5,718
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the waf-regional-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.WAFRegional.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WAFRegional.Model.Internal.MarshallTransformations { /// <summary> /// UpdateRule Request Marshaller /// </summary> public class UpdateRuleRequestMarshaller : IMarshaller<IRequest, UpdateRuleRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateRuleRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateRuleRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.WAFRegional"); string target = "AWSWAF_Regional_20161128.UpdateRule"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetChangeToken()) { context.Writer.WritePropertyName("ChangeToken"); context.Writer.Write(publicRequest.ChangeToken); } if(publicRequest.IsSetRuleId()) { context.Writer.WritePropertyName("RuleId"); context.Writer.Write(publicRequest.RuleId); } if(publicRequest.IsSetUpdates()) { context.Writer.WritePropertyName("Updates"); context.Writer.WriteArrayStart(); foreach(var publicRequestUpdatesListValue in publicRequest.Updates) { context.Writer.WriteObjectStart(); var marshaller = RuleUpdateMarshaller.Instance; marshaller.Marshall(publicRequestUpdatesListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateRuleRequestMarshaller _instance = new UpdateRuleRequestMarshaller(); internal static UpdateRuleRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateRuleRequestMarshaller Instance { get { return _instance; } } } }
35.795276
135
0.600528
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/WAFRegional/Generated/Model/Internal/MarshallTransformations/UpdateRuleRequestMarshaller.cs
4,546
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NSharding.Sharding.Database { /// <summary> /// 数据库表 /// </summary> [Serializable] public class DatabaseTable : SystemBase { /// <summary> /// Name /// </summary> public string Name { get; set; } /// <summary> /// 数据库连接名称 /// </summary> public string DatabaseLinkName { get; set; } } }
19.5
52
0.568047
[ "MIT" ]
tesm/N-Sharding
Src/NSharding.Sharding.Database/DatabaseTable.cs
531
C#
using System; namespace XCode { /// <summary>模型检查模式</summary> public enum ModelCheckModes { /// <summary>初始化时检查所有表。默认值。具有最好性能。</summary> CheckAllTablesWhenInit, /// <summary>第一次使用时检查表。常用于通用实体类等存在大量实体类但不会同时使用所有实体类的场合,避免反向工程生成没有使用到的实体类的数据表。</summary> CheckTableWhenFirstUse } /// <summary>模型检查模式</summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ModelCheckModeAttribute : Attribute { /// <summary>模式</summary> public ModelCheckModes Mode { get; set; } /// <summary>指定实体类的模型检查模式</summary> /// <param name="mode"></param> public ModelCheckModeAttribute(ModelCheckModes mode) { Mode = mode; } } }
29.230769
95
0.655263
[ "MIT" ]
EnhWeb/DC.Framework
src/Ding.XCode/Attributes/ModelCheckModeAttribute.cs
984
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.RecoveryServices.Latest.Outputs { [OutputType] public sealed class ReplicationProtectedItemPropertiesResponse { /// <summary> /// The Current active location of the PE. /// </summary> public readonly string? ActiveLocation; /// <summary> /// The allowed operations on the Replication protected item. /// </summary> public readonly ImmutableArray<string> AllowedOperations; /// <summary> /// The current scenario. /// </summary> public readonly Outputs.CurrentScenarioDetailsResponse? CurrentScenario; /// <summary> /// The consolidated failover health for the VM. /// </summary> public readonly string? FailoverHealth; /// <summary> /// The recovery point ARM Id to which the Vm was failed over. /// </summary> public readonly string? FailoverRecoveryPointId; /// <summary> /// The name. /// </summary> public readonly string? FriendlyName; /// <summary> /// List of health errors. /// </summary> public readonly ImmutableArray<Outputs.HealthErrorResponse> HealthErrors; /// <summary> /// The Last successful failover time. /// </summary> public readonly string? LastSuccessfulFailoverTime; /// <summary> /// The Last successful test failover time. /// </summary> public readonly string? LastSuccessfulTestFailoverTime; /// <summary> /// The name of Policy governing this PE. /// </summary> public readonly string? PolicyFriendlyName; /// <summary> /// The ID of Policy governing this PE. /// </summary> public readonly string? PolicyId; /// <summary> /// The friendly name of the primary fabric. /// </summary> public readonly string? PrimaryFabricFriendlyName; /// <summary> /// The fabric provider of the primary fabric. /// </summary> public readonly string? PrimaryFabricProvider; /// <summary> /// The name of primary protection container friendly name. /// </summary> public readonly string? PrimaryProtectionContainerFriendlyName; /// <summary> /// The protected item ARM Id. /// </summary> public readonly string? ProtectableItemId; /// <summary> /// The type of protected item type. /// </summary> public readonly string? ProtectedItemType; /// <summary> /// The protection status. /// </summary> public readonly string? ProtectionState; /// <summary> /// The protection state description. /// </summary> public readonly string? ProtectionStateDescription; /// <summary> /// The Replication provider custom settings. /// </summary> public readonly object? ProviderSpecificDetails; /// <summary> /// The recovery container Id. /// </summary> public readonly string? RecoveryContainerId; /// <summary> /// The friendly name of recovery fabric. /// </summary> public readonly string? RecoveryFabricFriendlyName; /// <summary> /// The Arm Id of recovery fabric. /// </summary> public readonly string? RecoveryFabricId; /// <summary> /// The name of recovery container friendly name. /// </summary> public readonly string? RecoveryProtectionContainerFriendlyName; /// <summary> /// The recovery provider ARM Id. /// </summary> public readonly string? RecoveryServicesProviderId; /// <summary> /// The consolidated protection health for the VM taking any issues with SRS as well as all the replication units associated with the VM's replication group into account. This is a string representation of the ProtectionHealth enumeration. /// </summary> public readonly string? ReplicationHealth; /// <summary> /// The Test failover state. /// </summary> public readonly string? TestFailoverState; /// <summary> /// The Test failover state description. /// </summary> public readonly string? TestFailoverStateDescription; [OutputConstructor] private ReplicationProtectedItemPropertiesResponse( string? activeLocation, ImmutableArray<string> allowedOperations, Outputs.CurrentScenarioDetailsResponse? currentScenario, string? failoverHealth, string? failoverRecoveryPointId, string? friendlyName, ImmutableArray<Outputs.HealthErrorResponse> healthErrors, string? lastSuccessfulFailoverTime, string? lastSuccessfulTestFailoverTime, string? policyFriendlyName, string? policyId, string? primaryFabricFriendlyName, string? primaryFabricProvider, string? primaryProtectionContainerFriendlyName, string? protectableItemId, string? protectedItemType, string? protectionState, string? protectionStateDescription, object? providerSpecificDetails, string? recoveryContainerId, string? recoveryFabricFriendlyName, string? recoveryFabricId, string? recoveryProtectionContainerFriendlyName, string? recoveryServicesProviderId, string? replicationHealth, string? testFailoverState, string? testFailoverStateDescription) { ActiveLocation = activeLocation; AllowedOperations = allowedOperations; CurrentScenario = currentScenario; FailoverHealth = failoverHealth; FailoverRecoveryPointId = failoverRecoveryPointId; FriendlyName = friendlyName; HealthErrors = healthErrors; LastSuccessfulFailoverTime = lastSuccessfulFailoverTime; LastSuccessfulTestFailoverTime = lastSuccessfulTestFailoverTime; PolicyFriendlyName = policyFriendlyName; PolicyId = policyId; PrimaryFabricFriendlyName = primaryFabricFriendlyName; PrimaryFabricProvider = primaryFabricProvider; PrimaryProtectionContainerFriendlyName = primaryProtectionContainerFriendlyName; ProtectableItemId = protectableItemId; ProtectedItemType = protectedItemType; ProtectionState = protectionState; ProtectionStateDescription = protectionStateDescription; ProviderSpecificDetails = providerSpecificDetails; RecoveryContainerId = recoveryContainerId; RecoveryFabricFriendlyName = recoveryFabricFriendlyName; RecoveryFabricId = recoveryFabricId; RecoveryProtectionContainerFriendlyName = recoveryProtectionContainerFriendlyName; RecoveryServicesProviderId = recoveryServicesProviderId; ReplicationHealth = replicationHealth; TestFailoverState = testFailoverState; TestFailoverStateDescription = testFailoverStateDescription; } } }
36.412322
247
0.631134
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/RecoveryServices/Latest/Outputs/ReplicationProtectedItemPropertiesResponse.cs
7,683
C#
using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace ADepIn.Tests { public class OptionExtensionsTests { private const bool SOME_INNER = true; private const bool NOT_SOME_INNER = !SOME_INNER; private static readonly Option<bool> _some = Option.Some(SOME_INNER); private static readonly Option<bool> _notSome = Option.Some(NOT_SOME_INNER); private static readonly Option<bool> _none = Option.None<bool>(); [Fact] public void _Prerequisites() { Assert.NotEqual(SOME_INNER, NOT_SOME_INNER); Assert.NotEqual(_some, _notSome); Assert.NotEqual(_some, _none); Assert.NotEqual(_notSome, _none); } [Fact] public void Opt() { var obj = new object(); object? @null = null; Assert.Equal(Option.Some(obj), obj.Opt()); Assert.Equal(Option.None<object>(), @null.Opt()); } [Fact] public void Contains_Equatable() { var someContainsInner = _some.Contains(SOME_INNER); var someContainsNotInner = _some.Contains(NOT_SOME_INNER); var noneContainsInner = _none.Contains(SOME_INNER); var noneContainsNotInner = _none.Contains(NOT_SOME_INNER); Assert.True(someContainsInner); Assert.False(someContainsNotInner); Assert.False(noneContainsInner); Assert.False(noneContainsNotInner); } [Fact] public void Contains_Comparer() { var comparer = EqualityComparer<bool>.Default; var someContainsInner = _some.Contains(SOME_INNER, comparer); var someContainsNotInner = _some.Contains(NOT_SOME_INNER, comparer); var noneContainsInner = _none.Contains(SOME_INNER, comparer); var noneContainsNotInner = _none.Contains(NOT_SOME_INNER, comparer); Assert.True(someContainsInner); Assert.False(someContainsNotInner); Assert.False(noneContainsInner); Assert.False(noneContainsNotInner); } [Fact] public void Matches_Equatable() { var someMatchesSome = _some.Matches(_some); var someMatchesNotSome = _some.Matches(_notSome); var someMatchesNone = _some.Matches(_none); var noneMatchesSome = _none.Matches(_some); var noneMatchesNotSome = _none.Matches(_notSome); var noneMatchesNone = _none.Matches(_none); Assert.True(someMatchesSome); Assert.False(someMatchesNotSome); Assert.False(someMatchesNone); Assert.False(noneMatchesSome); Assert.False(noneMatchesNotSome); Assert.False(noneMatchesNone); } [Fact] public void Matches_Comparer() { var comparer = EqualityComparer<bool>.Default; var someMatchesSome = _some.Matches(_some, comparer); var someMatchesNotSome = _some.Matches(_notSome, comparer); var someMatchesNone = _some.Matches(_none, comparer); var noneMatchesSome = _none.Matches(_some, comparer); var noneMatchesNotSome = _none.Matches(_notSome, comparer); var noneMatchesNone = _none.Matches(_none, comparer); Assert.True(someMatchesSome); Assert.False(someMatchesNotSome); Assert.False(someMatchesNone); Assert.False(noneMatchesSome); Assert.False(noneMatchesNotSome); Assert.False(noneMatchesNone); } [Fact] public void Flatten() { var someSome = Option.Some(_some); var someNone = Option.Some(_none); var none = Option.None<Option<bool>>(); var someSomeFlattened = someSome.Flatten(); var someNoneFlattened = someNone.Flatten(); var noneFlattened = none.Flatten(); Assert.Equal(_some, someSomeFlattened); Assert.Equal(_none, someNoneFlattened); Assert.Equal(_none, noneFlattened); } [Fact] public void Take() { var some = _some; var notSome = _notSome; var none = _none; var someTook = some.Take(); var notSomeTook = notSome.Take(); var noneTook = none.Take(); Assert.Equal(_some, someTook); Assert.Equal(_none, some); Assert.Equal(_notSome, notSomeTook); Assert.Equal(_none, notSome); Assert.Equal(none, noneTook); Assert.Equal(_none, none); } [Fact] public void GetOrInsert() { var someMutated = _some; var noneMutated = _none; var someGot = someMutated.GetOrInsert(NOT_SOME_INNER); var noneGot = noneMutated.GetOrInsert(NOT_SOME_INNER); Assert.Equal(SOME_INNER, someGot); Assert.Equal(NOT_SOME_INNER, noneGot); Assert.Equal(_some, someMutated); Assert.Equal(_notSome, noneMutated); } [Fact] public void GetOrInsertWith() { var someMutated = _some; var noneMutated = _none; var someGot = someMutated.GetOrInsertWith(() => NOT_SOME_INNER); var noneGot = noneMutated.GetOrInsertWith(() => NOT_SOME_INNER); Assert.Equal(SOME_INNER, someGot); Assert.Equal(NOT_SOME_INNER, noneGot); Assert.Equal(_some, someMutated); Assert.Equal(_notSome, noneMutated); } [Fact] public void WhereSome() { var items = new[] { _none, _some, _none, _notSome, _none, _none, _some, _notSome }; var itemsWhere = items.Where(x => x.IsSome).Select(x => x.Unwrap()); var itemsWhereSome = items.WhereSome(); Assert.Equal(itemsWhere, itemsWhereSome); } [Fact] public void WhereSelect() { const int halfCount = 5; const int increment = 5; var items = Enumerable.Range(0, halfCount * 2).ToArray(); bool Filter(int x) { return x > halfCount; } int Mutation(int x) { return x + increment; } var itemsWhereThenSelected = items.Where(Filter).Select(Mutation); var itemsWhereSelected = items.WhereSelect(x => Filter(x) ? Option.Some(Mutation(x)) : Option.None<int>()); Assert.Equal(itemsWhereThenSelected, itemsWhereSelected); } } public class OptionTests { private const bool SOME_INNER = true; private const bool NOT_SOME_INNER = !SOME_INNER; private static readonly Option<bool> _some = Option.Some(SOME_INNER); private static readonly Option<bool> _notSome = Option.Some(NOT_SOME_INNER); private static readonly Option<bool> _none = Option.None<bool>(); [Fact] public void _Prerequisites() { Assert.NotEqual(SOME_INNER, NOT_SOME_INNER); Assert.NotEqual(_some, _notSome); Assert.NotEqual(_some, _none); Assert.NotEqual(_notSome, _none); } [Fact] public void IsSome() { Assert.True(_some.IsSome); Assert.False(_none.IsSome); } [Fact] public void IsNone() { Assert.False(_some.IsNone); Assert.True(_none.IsNone); } [Fact] public void Expect() { _some.Expect("This should not throw."); const string message = "This should throw."; var e = Assert.Throws<InvalidOperationException>(() => _none.Expect(message)); Assert.Equal(message, e.Message); } [Fact] public void ExpectNone() { const string message = "This should throw."; var e = Assert.Throws<InvalidOperationException>(() => _some.ExpectNone(message)); _none.ExpectNone("This should not throw."); Assert.Equal(message, e.Message); } [Fact] public void Unwrap() { var someUnwrapped = _some.Unwrap(); Assert.Throws<InvalidOperationException>(() => _none.Unwrap()); Assert.Equal(SOME_INNER, someUnwrapped); } [Fact] public void UnwrapNone() { Assert.Throws<InvalidOperationException>(() => _some.UnwrapNone()); _none.UnwrapNone(); } [Fact] public void UnwrapOr() { var someUnwrapped = _some.UnwrapOr(NOT_SOME_INNER); var noneUnwrapped = _none.UnwrapOr(NOT_SOME_INNER); Assert.Equal(SOME_INNER, someUnwrapped); Assert.Equal(NOT_SOME_INNER, noneUnwrapped); } [Fact] public void UnwrapOrElse() { var someUnwrapped = _some.UnwrapOrElse(() => throw new NotSupportedException()); var noneUnwrapped = _none.UnwrapOrElse(() => NOT_SOME_INNER); Assert.Equal(SOME_INNER, someUnwrapped); Assert.Equal(NOT_SOME_INNER, noneUnwrapped); } [Fact] public void Or() { var someOred = _some.Or(_notSome); var noneOred = _none.Or(_notSome); Assert.Equal(_some, someOred); Assert.Equal(_notSome, noneOred); } [Fact] public void OrElse() { var someOred = _some.OrElse(() => throw new NotSupportedException()); var noneOred = _none.OrElse(() => _notSome); Assert.Equal(_some, someOred); Assert.Equal(_notSome, noneOred); } [Fact] public void And() { var someAnded = _some.And(_notSome); var noneAnded = _none.And(_notSome); Assert.Equal(_notSome, someAnded); Assert.Equal(_none, noneAnded); } [Fact] public void Xor() { var someSomeXored = _some.Xor(_some); var noneSomeXored = _none.Xor(_some); var someNoneXored = _some.Xor(_none); var noneNoneXored = _none.Xor(_none); Assert.Equal(_some, noneSomeXored); Assert.Equal(_some, someNoneXored); Assert.Equal(_none, someSomeXored); Assert.Equal(_none, noneNoneXored); } [Fact] public void Filter() { var someFilteredFalse = _some.Filter(x => { Assert.Equal(SOME_INNER, x); return false; }); var someFilteredTrue = _some.Filter(x => { Assert.Equal(SOME_INNER, x); return true; }); var noneFiltered = _none.Filter(x => throw new NotSupportedException()); Assert.Equal(_some, someFilteredTrue); Assert.Equal(_none, someFilteredFalse); Assert.Equal(_none, noneFiltered); } [Fact] public void As() { const string content = "lots of content goes here"; var obj = Option.Some<object>(content); var str = Option.Some(content); var downcast = str.As<object>(); var upcast = obj.As<string>(); var invalid = obj.As<bool>(); Assert.Equal(str, upcast); Assert.Equal(obj, downcast); Assert.Equal(Option.None<bool>(), invalid); } [Fact] public void Map() { var someMapped = _some.Map(x => { Assert.Equal(SOME_INNER, x); return !x; }); var noneMapped = _none.Map<bool>(x => throw new NotSupportedException()); Assert.Equal(_notSome, someMapped); Assert.Equal(_none, noneMapped); } [Fact] public void MapOr() { var someMapped = _some.MapOr(SOME_INNER, x => { Assert.Equal(SOME_INNER, x); return !x; }); var noneMapped = _none.MapOr(NOT_SOME_INNER, x => throw new NotSupportedException()); Assert.Equal(NOT_SOME_INNER, someMapped); Assert.Equal(NOT_SOME_INNER, noneMapped); } [Fact] public void MapOrElse() { var someMapped = _some.MapOrElse(() => throw new NotSupportedException(), x => { Assert.Equal(SOME_INNER, x); return NOT_SOME_INNER; }); var noneMapped = _none.MapOrElse(() => NOT_SOME_INNER, x => throw new NotSupportedException()); Assert.Equal(NOT_SOME_INNER, someMapped); Assert.Equal(NOT_SOME_INNER, noneMapped); } [Theory] [InlineData("")] [InlineData("a")] [InlineData(" a")] [InlineData("a ")] [InlineData(" a ")] [InlineData(-1)] [InlineData(0)] [InlineData(1)] [InlineData(true)] [InlineData(false)] public void _ToString_Some(object value) { var some = Option.Some(value); var str = some.ToString(); Assert.Equal("Some(" + value + ")", str); } [Fact] public void _ToString_None() { var (noneBool, noneObject) = (Option.None<bool>(), Option.None<object>()); var (boolStr, objectStr) = (noneBool.ToString(), noneObject.ToString()); const string noneStr = "None"; Assert.Equal(noneStr, boolStr); Assert.Equal(noneStr, objectStr); } } }
24.479121
110
0.688185
[ "MIT" ]
ash-hat/Atlas
src/ADepIn.Tests/Tools/Option.cs
11,138
C#
namespace SBWebAPI.Areas.HelpPage.ModelDescriptions { public class EnumValueDescription { public string Documentation { get; set; } public string Name { get; set; } public string Value { get; set; } } }
21.818182
51
0.641667
[ "MIT" ]
sabeell/Projects
SBWebAPI/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs
240
C#
namespace HackF5.UnitySpy.ProcessFacade { using System; using System.Diagnostics; using System.Runtime.InteropServices; using JetBrains.Annotations; /// <summary> /// A MacOS specific facade over a process that provides access to its memory space. /// </summary> [PublicAPI] public class ProcessFacadeMacOSDirect : ProcessFacadeMacOS { public ProcessFacadeMacOSDirect(Process process) : base(process) { } public override void ReadProcessMemory( byte[] buffer, IntPtr processAddress, bool allowPartialRead = false, int? size = default) { var bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { var bufferPointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0); if (0 != ProcessFacadeMacOSDirect.ReadProcessMemory( this.Process.Id, processAddress, bufferPointer, size ?? buffer.Length)) { var error = Marshal.GetLastWin32Error(); if ((error == 299) && allowPartialRead) { return; } throw new InvalidOperationException($"Could not read memory at address {processAddress.ToString("X")}. Error code: {error}"); } } finally { bufferHandle.Free(); } } public override ModuleInfo GetModule(string moduleName) { if (!this.Is64Bits) { throw new NotSupportedException("MacOS for 32 binaries is not supported currently"); } IntPtr baseAddress; uint size = 0; IntPtr buffer = Marshal.AllocCoTaskMem(2048 + 1); string path; try { Marshal.WriteByte(buffer, 2048, 0); // Ensure there will be a null byte after call baseAddress = GetModuleInfo(this.Process.Id, moduleName, ref size, buffer); path = Marshal.PtrToStringAnsi(buffer); } finally { Marshal.FreeCoTaskMem(buffer); } return new ModuleInfo(moduleName, baseAddress, size, path); } [DllImport("macos.dylib", EntryPoint = "read_process_memory_to_buffer", SetLastError = true)] private static extern int ReadProcessMemory( int processId, IntPtr lpBaseAddress, IntPtr lpBuffer, int nSize); [DllImport("macos.dylib", EntryPoint = "get_module_info", SetLastError = true)] private static extern IntPtr GetModuleInfo( int processId, string moduleName, ref uint nSize, IntPtr path); } }
33.640449
145
0.529726
[ "MIT" ]
frcaton/UnitySpy-AvaloniaGui
src/HackF5.UnitySpy/ProcessFacade/ProcessFacadeMacOSDirect.cs
2,996
C#
using SharpDX.DirectInput; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Axiverse.Interface2.Input { public class DirectInputSource : IInputSource { public DirectInput DirectInput { get; set; } public List<Joystick> Joysticks { get; } = new List<Joystick>(); public DirectInputSource() { DirectInput = new DirectInput(); var instances = DirectInput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AllDevices); foreach (var instance in instances) { var joystick = new Joystick(DirectInput, instance.InstanceGuid); joystick.Properties.AxisMode = DeviceAxisMode.Relative; joystick.Properties.BufferSize = 128; Joysticks.Add(joystick); } } public void Acquire() { foreach (var joystick in Joysticks) { joystick.Acquire(); } } public void Release() { foreach (var joystick in Joysticks) { joystick.Unacquire(); } } public void Update() { foreach (var joystick in Joysticks) { try { joystick.Poll(); var data = joystick.GetBufferedData(); foreach (var update in data) { } } catch (Exception) { } } } } }
24.42029
111
0.495549
[ "MIT" ]
AxiverseCode/Axiverse
Source/Libraries/Axiverse.Interface2/Input/DirectInputSource.cs
1,687
C#
using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using DotNet.Cli.Flubu.Infrastructure; using FlubuCore; using FlubuCore.Commanding; using FlubuCore.Context; using FlubuCore.Infrastructure; using FlubuCore.Scripting; using McMaster.Extensions.CommandLineUtils; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace DotNet.Cli.Flubu { public static class Program { private static readonly IServiceCollection Services = new ServiceCollection(); private static IServiceProvider _provider; private static ILogger<CommandExecutor> _logger; private static bool _cleanUpPerformed = false; private static volatile bool _wait = false; public static async Task<int> Main(string[] args) { if (args == null) { args = new string[0]; } var statusCode = await FlubuStartup(args); if (statusCode != 0) { return statusCode; } var cmdApp = _provider.GetRequiredService<CommandLineApplication>(); ICommandExecutor executor = _provider.GetRequiredService<ICommandExecutor>(); Console.CancelKeyPress += OnCancelKeyPress; var result = await executor.ExecuteAsync(); while (_wait) { Thread.Sleep(250); } return result; } private static async Task<int> FlubuStartup(string[] args) { IServiceCollection startUpServiceCollection = new ServiceCollection(); startUpServiceCollection.AddScriptAnalyzers() .AddCoreComponents() .AddCommandComponents(false) .AddParserComponents() .AddScriptAnalyzers(); Services.AddFlubuLogging(startUpServiceCollection); var startupProvider = startUpServiceCollection.BuildServiceProvider(); var parser = startupProvider.GetRequiredService<IFlubuCommandParser>(); var commandArguments = parser.Parse(args); IScriptProvider scriptProvider = startupProvider.GetRequiredService<IScriptProvider>(); IFlubuConfigurationBuilder flubuConfigurationBuilder = new FlubuConfigurationBuilder(); ILoggerFactory loggerFactory = startupProvider.GetRequiredService<ILoggerFactory>(); loggerFactory.AddProvider(new FlubuLoggerProvider()); _logger = startupProvider.GetRequiredService<ILogger<CommandExecutor>>(); var version = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version; _logger.LogInformation($"Flubu v.{version}"); IBuildScript script = null; if (!commandArguments.IsFlubuSetup()) { try { script = await scriptProvider.GetBuildScriptAsync(commandArguments); } catch (BuildScriptLocatorException e) { if (!commandArguments.InteractiveMode) { var str = commandArguments.Debug ? e.ToString() : e.Message; _logger.Log(LogLevel.Error, 1, $"EXECUTION FAILED:\r\n{str}", null, (t, ex) => t); return StatusCodes.BuildScriptNotFound; } } } Services .AddCoreComponents() .AddParserComponents() .AddCommandComponents(interactiveMode: commandArguments.InteractiveMode) .AddScriptAnalyzers() .AddTasks(); Services.AddSingleton(loggerFactory); Services.AddSingleton(commandArguments); if (script != null) { script.ConfigureServices(Services); script.Configure(flubuConfigurationBuilder, loggerFactory); } Services.AddSingleton(flubuConfigurationBuilder.Build()); _provider = Services.BuildServiceProvider(); return 0; } private static void OnCancelKeyPress(object sender, ConsoleCancelEventArgs eventArgs) { if (!_cleanUpPerformed && CleanUpStore.TaskCleanUpActions?.Count > 0) { _wait = true; _logger.LogInformation($"Performing clean up actions:"); var taskSession = _provider.GetService<IFlubuSession>(); foreach (var cleanUpAction in CleanUpStore.TaskCleanUpActions) { cleanUpAction.Invoke(taskSession); _logger.LogInformation($"Finished performing clean up actions."); } _wait = false; } } } }
35.273381
113
0.599225
[ "MIT" ]
Rwing/FlubuCore
src/dotnet-flubu/Program.cs
4,905
C#
using HappyTravel.BaseConnector.Api.Services.Locations; using HappyTravel.EdoContracts.GeoData; using HappyTravel.EdoContracts.GeoData.Enums; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; namespace HappyTravel.BaseConnector.Api.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/{v:apiVersion}/locations")] [Produces("application/json")] public class LocationsController : Controller { public LocationsController(ILocationService locationService) { _locationService = locationService; } /// <summary> /// Gets locations. /// </summary> /// <param name="modified">Last modified date</param> /// <param name="locationType">Location type</param> /// <param name="skip">Skip count</param> /// <param name="take">Take count</param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>Location list</returns> [HttpGet("{modified}")] [ProducesResponseType(typeof(List<Location>), (int)HttpStatusCode.OK)] public async Task<IActionResult> GetLocations([FromRoute] DateTime modified, [FromQuery] LocationTypes locationType, [FromQuery] int skip = 0, [FromQuery] int take = 10000, CancellationToken cancellationToken = default) { return Ok(await _locationService.Get(modified, locationType, skip, take, cancellationToken)); } private readonly ILocationService _locationService; }
33.622222
146
0.730337
[ "MIT" ]
happy-travel/base-connector
HappyTravel.BaseConnector.Api/Controllers/LocationsController.cs
1,515
C#
using System; using System.Collections.Generic; // Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled. // If you have enabled NRTs for your project, then un-comment the following line: // #nullable disable namespace EasyShare.Models { public partial class Projects { public int ProjectId { get; set; } public int CompanyDepartmentId { get; set; } public int CompanyId { get; set; } public string ProjectName { get; set; } public string ProjectDescription { get; set; } public virtual Company Company { get; set; } public virtual Department CompanyDepartment { get; set; } public virtual ProjectTeams ProjectTeams { get; set; } } }
33.652174
96
0.661499
[ "Apache-2.0" ]
andandrijana/EasyShareCap
EasyShare/Models/Projects.cs
776
C#