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
using System; using Windows.Graphics.Display; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using OneNoteServiceSamplesWinUniversal.Common; using OneNoteServiceSamplesWinUniversal.Data; using OneNoteServiceSamplesWinUniversal.OneNoteApi; // The Universal Hub Application project template is documented at http://go.microsoft.com/fwlink/?LinkID=391955 namespace OneNoteServiceSamplesWinUniversal { /// <summary> /// A page that displays a grouped collection of items. /// </summary> public sealed partial class HubPage : SharedBasePage { private readonly NavigationHelper _navigationHelper; private HubContext _hubContext; private readonly ObservableDictionary _defaultViewModel = new ObservableDictionary(); public HubPage() { InitializeComponent(); // Hub is only supported in Portrait orientation DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait; NavigationCacheMode = NavigationCacheMode.Required; _navigationHelper = new NavigationHelper(this); _navigationHelper.LoadState += NavigationHelper_LoadState; _navigationHelper.SaveState += NavigationHelper_SaveState; } /// <summary> /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>. /// </summary> public NavigationHelper NavigationHelper { get { return _navigationHelper; } } /// <summary> /// Gets the view model for this <see cref="Page"/>. /// This can be changed to a strongly typed view model. /// </summary> public ObservableDictionary DefaultViewModel { get { return _defaultViewModel; } } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/> /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { var sampleDataGroups = await SampleDataSource.GetGroupsAsync(); DefaultViewModel["Groups"] = sampleDataGroups; // load our toggle switch states UserData.Provider = AppSettings.GetProviderO365() ? AuthProvider.MicrosoftOffice365 : AuthProvider.MicrosoftAccount; O365ToggleSwitch.IsOn = UserData.Provider == AuthProvider.MicrosoftOffice365; UserData.UseBeta = AppSettings.GetUseBeta(); UseBetaToggleSwitch.IsOn = UserData.UseBeta; } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param> /// <param name="e">Event data that provides an empty dictionary to be populated with /// serializable state.</param> private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e) { // TODO: Save the unique state of the page here. } /// <summary> /// Shows the details of a clicked group in the <see cref="SectionPage"/>. /// </summary> /// <param name="sender">The source of the click event.</param> /// <param name="e">Details about the click event.</param> private void GroupSection_ItemClick(object sender, ItemClickEventArgs e) { var groupId = ((SampleDataGroup)e.ClickedItem).UniqueId; Frame.Navigate(typeof (SectionPage), groupId); } /// <summary> /// Shows the details of an item clicked on in the <see cref="ItemPage"/> /// </summary> /// <param name="sender">The source of the click event.</param> /// <param name="e">Defaults about the click event.</param> private void ItemView_ItemClick(object sender, ItemClickEventArgs e) { _hubContext.ItemId = ((SampleDataItem)e.ClickedItem).UniqueId; Frame.Navigate(typeof(ItemPage), _hubContext); } #region NavigationHelper registration /// <summary> /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// <para> /// Page specific logic should be placed in event handlers for the /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// </para> /// </summary> /// <param name="e">Event data that describes how this page was reached.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { _navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { _navigationHelper.OnNavigatedFrom(e); } #endregion private async void O365ToggleSwitch_Toggled(object sender, RoutedEventArgs e) { var toggleSwitch = (ToggleSwitch)sender; UserData.Provider = toggleSwitch.IsOn ? AuthProvider.MicrosoftOffice365 : AuthProvider.MicrosoftAccount; AppSettings.SetProviderO365(toggleSwitch.IsOn); // kick off getting the access token await Auth.GetAuthToken(UserData.Provider); } private void UseBetaToggleSwitch_Toggled(object sender, RoutedEventArgs e) { var toggleSwitch = (ToggleSwitch)sender; UserData.UseBeta = toggleSwitch.IsOn; AppSettings.SetUseBeta(UserData.UseBeta); } } }
36.88961
119
0.740187
[ "Apache-2.0" ]
OneNoteDev/OneNoteAPISampleWinUniversal
OneNoteServiceSamplesWinUniversal.WindowsPhone/HubPage.xaml.cs
5,683
C#
using System; using Xunit; using System.Collections.Generic; namespace Statistics.Test { public class StatsUnitTest { [Fact] public void ReportsAverageMinMax() { var statsComputer = new StatsComputer(); var listValues = new List<double>{ 1.5, 8.9, 3.2, 4.5 }; var computedStats = statsComputer.CalculateStatistics(listValues); float epsilon = 0.001F; Assert.True(Math.Abs(computedStats.average - 4.525) <= epsilon); Assert.True(Math.Abs(computedStats.max - 8.9) <= epsilon); Assert.True(Math.Abs(computedStats.min - 1.5) <= epsilon); } [Fact] public void ReportsNaNForEmptyInput() { var statsComputer = new StatsComputer(); var list = new List<double> { 1.5, 8.9, 3.2, 4.5, double.NaN }; var computedStats = statsComputer.CalculateStatistics(list); Assert.True(double.IsNaN(computedStats.average)); Assert.True(double.IsNaN(computedStats.min)); Assert.True(double.IsNaN(computedStats.max)); } [Fact] public void RaisesAlertsIfMaxIsMoreThanThreshold() { var emailAlert = new EmailAlert(); var ledAlert = new LEDAlert(); IAlerter[] alerters = { emailAlert, ledAlert }; const float maxThreshold = 10.2F; var statsAlerter = new StatsAlerter(maxThreshold, alerters); statsAlerter.checkAndAlert(new List<double> { 0.2, 11.9, 4.3, 8.5 }); Assert.True(emailAlert.emailSent); Assert.True(ledAlert.ledGlows); } } }
33.62
81
0.587151
[ "MIT" ]
clean-code-craft-tcq-1/start-stats-csharp-RaghavendraSR06
Statistics.Test/StatsUnitTest.cs
1,681
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Core.Model; using Microsoft.AspNetCore.Mvc; using Dapper; using System.Data.SqlClient; namespace Core31.Web.Controllers { /// <summary> /// Dapper 简易ORM测试 /// </summary> public class DapperTestController : Controller { private string connStr = "Data Source=.;Initial Catalog=CzarCms;User ID=sa;Password=123456;" + "Persist Security Info=True;Max Pool Size=50;Min Pool Size=0;Connection Lifetime=300;"; public IActionResult Index() { test_insert(); test_mult_insert(); test_del(); return View(); } /// <summary> /// 查询单条指定的数据 /// </summary> public void test_select_one() { using (var conn = new SqlConnection(connStr)) { string sql_insert = @"select * from [dbo].[content] where id=@id"; var result = conn.QueryFirstOrDefault<Content>(sql_insert, new { id = 5 }); Console.WriteLine($"test_select_one:查到的数据为:"); } } /// <summary> /// 查询多条指定的数据 /// </summary> public void test_select_list() { using (var conn = new SqlConnection(connStr)) { string sql_insert = @"select * from [dbo].[content] where id in @ids"; var result = conn.Query<Content>(sql_insert, new { ids = new int[] { 6, 7 } }); Console.WriteLine($"test_select_one:查到的数据为:"); } } /// <summary> /// 测试插入单条数据 /// </summary> public void test_insert() { var content = new Content { title = "标题1", content = "内容1", }; using (var conn = new SqlConnection(connStr)) { string sql_insert = @"INSERT INTO [Content] (title, [content], status, add_time, modify_time) VALUES (@title,@content,@status,@add_time,@modify_time)"; var result = conn.Execute(sql_insert, content); Console.WriteLine($"test_insert:插入了{result}条数据!"); } } /// <summary> /// 测试一次批量插入两条数据 /// </summary> public void test_mult_insert() { List<Content> contents = new List<Content>() { new Content { title = "批量插入标题1", content = "批量插入内容1", }, new Content { title = "批量插入标题2", content = "批量插入内容2", }, }; using (var conn = new SqlConnection(connStr)) { string sql_insert = @"INSERT INTO [Content] (title, [content], status, add_time, modify_time) VALUES (@title,@content,@status,@add_time,@modify_time)"; var result = conn.Execute(sql_insert, contents); Console.WriteLine($"test_mult_insert:插入了{result}条数据!"); } } /// <summary> /// 测试删除单条数据 /// </summary> public void test_del() { var content = new Content { id = 2, }; using (var conn = new SqlConnection(connStr)) { string sql_insert = @"DELETE FROM [Content] WHERE (id = @id)"; var result = conn.Execute(sql_insert, content); Console.WriteLine($"test_del:删除了{result}条数据!"); } } /// <summary> /// 测试一次批量删除两条数据 /// </summary> public void test_mult_del() { List<Content> contents = new List<Content>() { new Content { id=3, }, new Content { id=4, }, }; using (var conn = new SqlConnection(connStr)) { string sql_insert = @"DELETE FROM [Content] WHERE (id = @id)"; var result = conn.Execute(sql_insert, contents); Console.WriteLine($"test_mult_del:删除了{result}条数据!"); } } /// <summary> /// 测试修改单条数据 /// </summary> public void test_update() { var content = new Content { id = 5, title = "标题5", content = "内容5", }; using (var conn = new SqlConnection(connStr)) { string sql_insert = @"UPDATE [Content] SET title = @title, [content] = @content, modify_time = GETDATE() WHERE (id = @id)"; var result = conn.Execute(sql_insert, content); Console.WriteLine($"test_update:修改了{result}条数据!"); } } /// <summary> /// 测试一次批量修改多条数据 /// </summary> public void test_mult_update() { List<Content> contents = new List<Content>() { new Content { id=6, title = "批量修改标题6", content = "批量修改内容6", }, new Content { id =7, title = "批量修改标题7", content = "批量修改内容7", }, }; using (var conn = new SqlConnection(connStr)) { string sql_insert = @"UPDATE [Content] SET title = @title, [content] = @content, modify_time = GETDATE() WHERE (id = @id)"; var result = conn.Execute(sql_insert, contents); Console.WriteLine($"test_mult_update:修改了{result}条数据!"); } } public void test_select_content_with_comment() { using (var conn = new SqlConnection(connStr)) { string sql_insert = @"select * from content where id=@id; select * from comment where content_id=@id;"; using (var result = conn.QueryMultiple(sql_insert, new { id = 5 })) { var content = result.ReadFirstOrDefault<ContentWithComment>(); content.comments = result.Read<Comment>(); Console.WriteLine($"test_select_content_with_comment:内容5的评论数量{content.comments.Count()}"); } } } } }
30.054545
125
0.46461
[ "MIT" ]
cqkxzyi/ZhangYi.Utilities
doNet/站点/Core3.1-Web/Controllers/DapperTestController.cs
7,032
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading.Tasks; using Microsoft.Bot.StreamingExtensions.PayloadTransport; using Microsoft.Bot.StreamingExtensions.UnitTests.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Bot.StreamingExtensions.UnitTests.Payloads { [TestClass] public class PayloadReceiverTests { [TestMethod] public async Task PayloadReceiver_ReceivePacketsAsync_ReceiveShortHeader_Throws() { var disconnectEvent = new TaskCompletionSource<string>(); var buffer = new byte[20]; var random = new Random(); random.NextBytes(buffer); var transport = new MockTransportReceiver(buffer); var receiver = new PayloadReceiver(); receiver.Disconnected += (sender, e) => { Assert.AreEqual("Stream closed while reading header bytes", e.Reason); disconnectEvent.SetResult("done"); }; receiver.Connect(transport); var result = await disconnectEvent.Task; Assert.AreEqual("done", result); } } }
30.170732
89
0.652385
[ "MIT" ]
russellholmes0410/Botframwork
tests/Microsoft.Bot.StreamingExtensions.Test/Payloads/PayloadReceiverTests.cs
1,239
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using Newtonsoft.Json; namespace QuantConnect { /// <summary> /// Defines a <see cref="JsonConverter"/> to be used when you only want to serialize /// the <see cref="Symbol.Value"/> property instead of the full <see cref="Symbol"/> /// instance /// </summary> public class SymbolValueJsonConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param><param name="value">The value.</param><param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var symbol = value as Symbol; if (symbol != null) { writer.WriteValue(symbol.Value); } else { serializer.Serialize(writer, value); } } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param><param name="objectType">Type of the object.</param><param name="existingValue">The existing value of object being read.</param><param name="serializer">The calling serializer.</param> /// <returns> /// The object value. /// </returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException("The SymbolValueJsonConverter is write-only."); } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { throw new NotImplementedException("The SymbolValueJsonConverter is intended to be decorated on the appropriate member directly."); } } }
43.042857
285
0.645868
[ "Apache-2.0" ]
3ai-co/Lean
Common/SymbolValueJsonConverter.cs
3,015
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")] public partial class COCD_TP145018UK03AssignedCustodianTemplateId : II { private static System.Xml.Serialization.XmlSerializer serializer; private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(COCD_TP145018UK03AssignedCustodianTemplateId)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current COCD_TP145018UK03AssignedCustodianTemplateId object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an COCD_TP145018UK03AssignedCustodianTemplateId object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output COCD_TP145018UK03AssignedCustodianTemplateId object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out COCD_TP145018UK03AssignedCustodianTemplateId obj, out System.Exception exception) { exception = null; obj = default(COCD_TP145018UK03AssignedCustodianTemplateId); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out COCD_TP145018UK03AssignedCustodianTemplateId obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static COCD_TP145018UK03AssignedCustodianTemplateId Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((COCD_TP145018UK03AssignedCustodianTemplateId)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current COCD_TP145018UK03AssignedCustodianTemplateId object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an COCD_TP145018UK03AssignedCustodianTemplateId object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output COCD_TP145018UK03AssignedCustodianTemplateId object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out COCD_TP145018UK03AssignedCustodianTemplateId obj, out System.Exception exception) { exception = null; obj = default(COCD_TP145018UK03AssignedCustodianTemplateId); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out COCD_TP145018UK03AssignedCustodianTemplateId obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static COCD_TP145018UK03AssignedCustodianTemplateId LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this COCD_TP145018UK03AssignedCustodianTemplateId object /// </summary> public virtual COCD_TP145018UK03AssignedCustodianTemplateId Clone() { return ((COCD_TP145018UK03AssignedCustodianTemplateId)(this.MemberwiseClone())); } #endregion } }
48.756614
1,368
0.61172
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/COCD_TP145018UK03AssignedCustodianTemplateId.cs
9,215
C#
namespace DashReportViewer.Shared.Models { public enum ServiceType { AzureDevOps = 1 } }
15.571429
41
0.642202
[ "MIT" ]
ZuechB/DashReportViewer
DashReportViewer.Shared/Models/ServiceType.cs
111
C#
//------------------------------------------------------------------------------ // <auto-generated>This code was generated by LLBLGen Pro v5.3.</auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; namespace EFCore20.Bencher.EntityClasses { /// <summary>Class which represents the entity 'PurchaseOrderDetail'.</summary> public partial class PurchaseOrderDetail : CommonEntityBase { #region Class Extensibility Methods /// <summary>Method called from the constructor</summary> partial void OnCreated(); #endregion /// <summary>Initializes a new instance of the <see cref="PurchaseOrderDetail"/> class.</summary> public PurchaseOrderDetail() : base() { OnCreated(); } /// <summary>Gets or sets the DueDate field. </summary> public System.DateTime DueDate { get; set;} /// <summary>Gets or sets the LineTotal field. </summary> public System.Decimal LineTotal { get; set;} /// <summary>Gets or sets the ModifiedDate field. </summary> public System.DateTime ModifiedDate { get; set;} /// <summary>Gets or sets the OrderQty field. </summary> public System.Int16 OrderQty { get; set;} /// <summary>Gets or sets the ProductId field. </summary> public System.Int32 ProductId { get; set;} /// <summary>Gets or sets the PurchaseOrderDetailId field. </summary> public System.Int32 PurchaseOrderDetailId { get; set;} /// <summary>Gets or sets the PurchaseOrderId field. </summary> public System.Int32 PurchaseOrderId { get; set;} /// <summary>Gets or sets the ReceivedQty field. </summary> public System.Decimal ReceivedQty { get; set;} /// <summary>Gets or sets the RejectedQty field. </summary> public System.Decimal RejectedQty { get; set;} /// <summary>Gets or sets the StockedQty field. </summary> public System.Decimal StockedQty { get; set;} /// <summary>Gets or sets the UnitPrice field. </summary> public System.Decimal UnitPrice { get; set;} /// <summary>Represents the navigator which is mapped onto the association 'PurchaseOrderDetail.Product - Product.PurchaseOrderDetails (m:1)'</summary> public Product Product { get; set;} /// <summary>Represents the navigator which is mapped onto the association 'PurchaseOrderDetail.PurchaseOrderHeader - PurchaseOrderHeader.PurchaseOrderDetails (m:1)'</summary> public PurchaseOrderHeader PurchaseOrderHeader { get; set;} } }
47.843137
177
0.687295
[ "MIT" ]
sanekpr/RawDataAccessBencher
EFCore2.0/Model/EntityClasses/PurchaseOrderDetail.cs
2,442
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi; using osu.Game.Screens.Multi.Lounge.Components; using osu.Game.Users; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Multiplayer { public class TestCaseLoungeRoomsContainer : MultiplayerTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(RoomsContainer), typeof(DrawableRoom) }; [Cached(Type = typeof(IRoomManager))] private TestRoomManager roomManager = new TestRoomManager(); [BackgroundDependencyLoader] private void load() { RoomsContainer container; Child = container = new RoomsContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 0.5f, JoinRequested = joinRequested }; AddStep("clear rooms", () => roomManager.Rooms.Clear()); AddStep("add rooms", () => { for (int i = 0; i < 3; i++) { roomManager.Rooms.Add(new Room { RoomID = { Value = i }, Name = { Value = $"Room {i}" }, Host = { Value = new User { Username = "Host" } }, EndDate = { Value = DateTimeOffset.Now + TimeSpan.FromSeconds(10) } }); } }); AddAssert("has 2 rooms", () => container.Rooms.Count == 3); AddStep("remove first room", () => roomManager.Rooms.Remove(roomManager.Rooms.FirstOrDefault())); AddAssert("has 2 rooms", () => container.Rooms.Count == 2); AddAssert("first room removed", () => container.Rooms.All(r => r.Room.RoomID.Value != 0)); AddStep("select first room", () => container.Rooms.First().Action?.Invoke()); AddAssert("first room selected", () => Room == roomManager.Rooms.First()); AddStep("join first room", () => container.Rooms.First().Action?.Invoke()); AddAssert("first room joined", () => roomManager.Rooms.First().Status.Value is JoinedRoomStatus); } private void joinRequested(Room room) => room.Status.Value = new JoinedRoomStatus(); private class TestRoomManager : IRoomManager { public event Action RoomsUpdated { add { } remove { } } public readonly BindableList<Room> Rooms = new BindableList<Room>(); IBindableList<Room> IRoomManager.Rooms => Rooms; public void CreateRoom(Room room, Action<Room> onSuccess = null, Action<string> onError = null) => Rooms.Add(room); public void JoinRoom(Room room, Action<Room> onSuccess = null, Action<string> onError = null) { } public void PartRoom() { } } private class JoinedRoomStatus : RoomStatus { public override string Message => "Joined"; public override Color4 GetAppropriateColour(OsuColour colours) => colours.Yellow; } } }
35.601942
128
0.54595
[ "MIT" ]
asd7766zxc/osu
osu.Game.Tests/Visual/Multiplayer/TestCaseLoungeRoomsContainer.cs
3,565
C#
// Copyright (c) 2012-2021 VLINGO LABS. All rights reserved. // // This Source Code Form is subject to the terms of the // Mozilla Public License, v. 2.0. If a copy of the MPL // was not distributed with this file, You can obtain // one at https://mozilla.org/MPL/2.0/. using System; using Vlingo.Xoom.Common; namespace Vlingo.Xoom.Actors { public class DirectoryScanner__Proxy : IDirectoryScanner { private const string ActorOfRepresentation1 = "ActorOf<T>(Vlingo.Xoom.Actors.Address)"; private const string ActorOfRepresentation2 = "MaybeActorOf<T>(Vlingo.Xoom.Actors.Address)"; private readonly Actor _actor; private readonly IMailbox _mailbox; public DirectoryScanner__Proxy(Actor actor, IMailbox mailbox) { _actor = actor; _mailbox = mailbox; } public ICompletes<T> ActorOf<T>(IAddress address) { if (!_actor.IsStopped) { Action<IDirectoryScanner> consumer = x => x.ActorOf<T>(address); var completes = new BasicCompletes<T>(_actor.Scheduler); if (_mailbox.IsPreallocated) { _mailbox.Send(_actor, consumer, completes, ActorOfRepresentation1); } else { _mailbox.Send(new LocalMessage<IDirectoryScanner>(_actor, consumer, completes, ActorOfRepresentation1)); } return completes; } _actor.DeadLetters?.FailedDelivery(new DeadLetter(_actor, ActorOfRepresentation1)); return null!; } public ICompletes<Optional<T>> MaybeActorOf<T>(IAddress address) { if (!_actor.IsStopped) { Action<IDirectoryScanner> consumer = x => x.MaybeActorOf<T>(address); var completes = new BasicCompletes<Optional<T>>(_actor.Scheduler); if (_mailbox.IsPreallocated) { _mailbox.Send(_actor, consumer, completes, ActorOfRepresentation2); } else { _mailbox.Send(new LocalMessage<IDirectoryScanner>(_actor, consumer, completes, ActorOfRepresentation2)); } return completes; } _actor.DeadLetters?.FailedDelivery(new DeadLetter(_actor, ActorOfRepresentation2)); return null!; } } }
34.819444
124
0.578779
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Luteceo/vlingo-net-actors
src/Vlingo.Xoom.Actors/DirectoryScanner__Proxy.cs
2,509
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.HDInsight.V20150301Preview.Outputs { /// <summary> /// The HDInsight cluster application GET response. /// </summary> [OutputType] public sealed class ApplicationPropertiesResponse { /// <summary> /// The application state. /// </summary> public readonly string ApplicationState; /// <summary> /// The application type. /// </summary> public readonly string? ApplicationType; /// <summary> /// The list of roles in the cluster. /// </summary> public readonly Outputs.ComputeProfileResponse? ComputeProfile; /// <summary> /// The application create date time. /// </summary> public readonly string CreatedDate; /// <summary> /// The list of errors. /// </summary> public readonly ImmutableArray<Outputs.ErrorsResponse> Errors; /// <summary> /// The list of application HTTPS endpoints. /// </summary> public readonly ImmutableArray<Outputs.ApplicationGetHttpsEndpointResponse> HttpsEndpoints; /// <summary> /// The list of install script actions. /// </summary> public readonly ImmutableArray<Outputs.RuntimeScriptActionResponse> InstallScriptActions; /// <summary> /// The marketplace identifier. /// </summary> public readonly string MarketplaceIdentifier; /// <summary> /// The provisioning state of the application. /// </summary> public readonly string ProvisioningState; /// <summary> /// The list of application SSH endpoints. /// </summary> public readonly ImmutableArray<Outputs.ApplicationGetEndpointResponse> SshEndpoints; /// <summary> /// The list of uninstall script actions. /// </summary> public readonly ImmutableArray<Outputs.RuntimeScriptActionResponse> UninstallScriptActions; [OutputConstructor] private ApplicationPropertiesResponse( string applicationState, string? applicationType, Outputs.ComputeProfileResponse? computeProfile, string createdDate, ImmutableArray<Outputs.ErrorsResponse> errors, ImmutableArray<Outputs.ApplicationGetHttpsEndpointResponse> httpsEndpoints, ImmutableArray<Outputs.RuntimeScriptActionResponse> installScriptActions, string marketplaceIdentifier, string provisioningState, ImmutableArray<Outputs.ApplicationGetEndpointResponse> sshEndpoints, ImmutableArray<Outputs.RuntimeScriptActionResponse> uninstallScriptActions) { ApplicationState = applicationState; ApplicationType = applicationType; ComputeProfile = computeProfile; CreatedDate = createdDate; Errors = errors; HttpsEndpoints = httpsEndpoints; InstallScriptActions = installScriptActions; MarketplaceIdentifier = marketplaceIdentifier; ProvisioningState = provisioningState; SshEndpoints = sshEndpoints; UninstallScriptActions = uninstallScriptActions; } } }
35.156863
99
0.645008
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/HDInsight/V20150301Preview/Outputs/ApplicationPropertiesResponse.cs
3,586
C#
using HSFrameWork.ConfigTable; using System.Collections.Generic; using System.Xml.Serialization; namespace Jyx2 { [XmlType("trigger")] public class Trigger : BaseBean { public override string PK { get { return Key; } } [XmlAttribute] public string Key; [XmlAttribute] public string Name; [XmlAttribute] public string KeyParam; [XmlAttribute] public string CommonParam; public string[] CommonParams { get { return CommonParam.Split(','); } } [XmlAttribute] public string Rule; [XmlAttribute] public string Desc; [XmlAttribute] public string Tag; public static Trigger Get(string pk) { return ConfigTable.Get<Trigger>(pk); } } }
18.851064
57
0.545147
[ "MIT" ]
Leo-YJL/jynew
jyx2/Assets/Scripts/Pojos/Trigger.cs
888
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using GameEvents; namespace GameEventManager { public class GameEventsManager { static private GameEventsManager instance; static public GameEventsManager Instance { get { if (instance == null) { instance = new GameEventsManager (); } return instance; } } private Dictionary<Type, GameEvent.Handler> registeredHandlers = new Dictionary<Type, GameEvent.Handler>(); public void Register<T>(GameEvent.Handler handler) where T : GameEvent { Type type = typeof(T); if (registeredHandlers.ContainsKey(type)) { registeredHandlers[type] += handler; } else { registeredHandlers[type] = handler; } } public void Unregister<T>(GameEvent.Handler handler) where T : GameEvent { Type type = typeof(T); GameEvent.Handler handlers; if (registeredHandlers.TryGetValue(type, out handlers)) { handlers -= handler; if (handlers == null) { registeredHandlers.Remove(type); } else { registeredHandlers[type] = handlers; } } } public void Fire(GameEvent e) { Type type = e.GetType(); GameEvent.Handler handlers; if (registeredHandlers.TryGetValue(type, out handlers)) { handlers(e); } } } }
24.473684
115
0.479032
[ "Unlicense" ]
chjwilliams/DreamTeam
DreamTeam/Assets/Scripts/Utils/GameEventManager.cs
1,862
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /* * AnimationController.cs * Copyright (c) 2006 David Astle * * 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.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; namespace Xclna.Xna.Animation { /// <summary> /// Controls an animation by advancing it's time and affecting /// bone transforms /// </summary> public class AnimationController : GameComponent, IAnimationController { #region Member Variables // Contains the interpolated transforms for all bones in an // animation private AnimationInfo animation; // Multiplied by the time whenever the animation is advanced; determines // the playback speed of the animation private double speedFactor = 1.0; // The elapsed time in the animation, can not be greater than the // animation duration private long elapsedTime = 0; // Used as a buffer to store the total elapsed ticks every frame so that private long elapsed; /// <summary> /// Fired when the controller is not looping and the animation has ended. /// </summary> public event EventHandler AnimationEnded; // True fi the animation is looping private bool isLooping = true; #endregion #region Constructors /// <summary> /// Creates a new animation controller. /// </summary> /// <param name="game">The game to which this controller will be attached.</param> /// <param name="sourceAnimation">The source animation that the controller will use. /// This is stored in the ModelAnimator class.</param> public AnimationController( Game game, AnimationInfo sourceAnimation) : base(game) { animation = sourceAnimation; // This is set so that the controller updates before the // ModelAnimator by default base.UpdateOrder = 0; game.Components.Add(this); } #endregion #region Properties /// <summary> /// Gets or sets a value that determines if the animation is looping. /// </summary> public bool IsLooping { get { return isLooping; } set { isLooping = value; } } /// <summary> /// Gets the total duration, in ticks, of the animation. /// </summary> public long Duration { get { return animation.Duration; } } /// <summary> /// Gets the source animation that this controller is using. /// </summary> public AnimationInfo AnimationSource { get { return animation; } } /// <summary> /// Gets or sets the elapsed time for the animation. /// </summary> public long ElapsedTime { get { return elapsedTime; } set { // Perform argument checking if (value < 0 || value > animation.Duration) throw new ArgumentOutOfRangeException("ElapsedTime", "When setting the ElapsedTime for an animation, the value " + " must be between 0 and the animation duration."); elapsedTime = value; } } /// <summary> /// Gets or sets the value that is multiplied by the time when it is /// advanced to determine the playback speed of the animation. /// </summary> public double SpeedFactor { get { return speedFactor; } set { speedFactor = value; } } #endregion #region Methods /// <summary> /// Called when the current animation reaches the end. /// </summary> /// <param name="args">The event args.</param> protected virtual void OnAnimationEnded(EventArgs args) { if (AnimationEnded != null) AnimationEnded(this, args); } /// <summary> /// Advances the current time in the animation. /// </summary> /// <param name="gameTime">Contains the time by which the animation will be advanced</param> public override void Update(GameTime gameTime) { // Speedfactor * elapsed time since last call to update elapsed = (long)(speedFactor * gameTime.ElapsedGameTime.Ticks); // If the animation is looping if (isLooping) { // Don't do anything if the speedfactor=0 if (elapsed != 0) { elapsedTime = (elapsedTime + elapsed); // If the elapsed time is greater than the duration, // raise the animation ended event and restart the animation if (elapsedTime > animation.Duration) { OnAnimationEnded(null); elapsedTime %= (animation.Duration + 1); } } } // If we aren't looping, don't do anything if the animation is at the end else if (elapsedTime != animation.Duration) { if (elapsed != 0) { // Set the elapsed time to the duration if the animation ends and // raise the AnimationEnded event elapsedTime = elapsedTime + elapsed; if (elapsedTime >= animation.Duration || elapsedTime < 0) { elapsedTime = animation.Duration; OnAnimationEnded(null); } } } } /// <summary> /// Gets the current transform for the given BonePose object in the animation. /// This is only called when a bone pose is affected by the current animation. /// </summary> /// <param name="pose">The BonePose object querying for the current transform in /// the animation.</param> /// <returns>The current transform of the bone.</returns> public virtual Matrix GetCurrentBoneTransform(BonePose pose) { AnimationChannelCollection channels = animation.AnimationChannels; BoneKeyframeCollection channel = channels[pose.Name]; int boneIndex = channel.GetIndexByTime(elapsedTime); return channel[boneIndex].Transform; } /// <summary> /// Returns true if the animation contains a track for the given BonePose. /// </summary> /// <param name="pose">The BonePose to test for track existence.</param> /// <returns>True if the animation contains a track for the given BonePose.</returns> public bool ContainsAnimationTrack(BonePose pose) { return animation.AnimationChannels.AffectsBone(pose.Name); } /// <summary> /// Fired when the tracks change so that different bones can be affected by the controller. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnAnimationTracksChanged(EventArgs e) { if (AnimationTracksChanged != null) AnimationTracksChanged(this, e); } /// <summary> /// Fired when the animation tracks change and different bones are affected. /// </summary> public event EventHandler AnimationTracksChanged; #endregion #region IAnimationController Members #endregion } }
35.444882
100
0.585805
[ "MIT" ]
Yash-Codemaster/KoduGameLab
main/Boku/Anim360/AnimationController.cs
9,003
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTests")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("cc3d006a-7890-46a5-bfda-25c5b60c670b")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29.428571
56
0.752427
[ "MIT" ]
squareJAO/Roleplay-ToolSet
Roleplay-ToolSet/UnitTests/Properties/AssemblyInfo.cs
619
C#
using Neuralm.Services.Common.Domain; using System; namespace Neuralm.Services.TrainingRoomService.Domain { /// <summary> /// Represents the <see cref="User"/> class. /// </summary> public class User : IEntity { /// <summary> /// Gets and sets the id. /// </summary> public Guid Id { get; set; } /// <summary> /// Gets and sets the username. /// </summary> public string Username { get; set; } } }
22.227273
53
0.546012
[ "MIT" ]
neuralm/Neuralm-Server
src/Neuralm.Services/Neuralm.Services.TrainingRoomService/Neuralm.Services.TrainingRoomService.Domain/User.cs
491
C#
//----------------------------------------------------------------------- // <copyright file="UpdateBudgetAllocations.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, 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. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using Activities; using ConfigManager; using Diagnostics; using DynamicAllocationUtilities; using EntityUtilities; using ScheduledActivities; using ScheduledActivities.Schedules; using Utilities.Storage; namespace DynamicAllocationActivityDispatchers { /// <summary> /// Source for activity requests to update budget allocations /// </summary> [SourceName("DynamicAllocations.UpdateBudgetAllocations"), Schedule(typeof(ConfigIntervalSchedule), "DynamicAllocation.UpdateBudgetAllocationsSchedule")] public class UpdateBudgetAllocations : ScheduledActivitySource { /// <summary> /// Gets the time to wait on in-progress requests before moving /// them from in-progress back to the present slot. /// </summary> private static TimeSpan UpdateAllocationsRequestExpiry { get { return Config.GetTimeSpanValue("DynamicAllocation.UpdateAllocationsRequestExpiry"); } } /// <summary>Gets the system auth user id</summary> private static string SystemAuthUserId { get { return Config.GetValue("System.AuthUserId"); } } /// <summary>Creates new scheduled activity requests</summary> public override void CreateScheduledRequests() { LogManager.Log(LogLevels.Trace, "Checking for campaigns to reallocate."); Scheduler.ProcessEntries<string, DateTime, bool>( DynamicAllocationActivitySchedulerRegistries.CampaignsToReallocate, DateTime.UtcNow, UpdateAllocationsRequestExpiry, (campaignEntityId, companyEntityId, allocationStartDate, isInitialAllocation) => this.SubmitUpdateAllocationRequest( campaignEntityId, companyEntityId, allocationStartDate, isInitialAllocation)); } /// <summary>Handler for activity results</summary> /// <param name="request">The request</param> /// <param name="result">The result</param> public override void OnActivityResult(ActivityRequest request, ActivityResult result) { var campaignEntityId = request.Values[EntityActivityValues.CampaignEntityId]; if (!result.Succeeded) { LogManager.Log( LogLevels.Error, true, "Updated budget allocations ({0}) failed for campaign '{1}': {2}\n\nRequest:\n{3}\n\nResult:\n{4}", result.Task, campaignEntityId, result.Error.Message, request.SerializeToXml().Replace("<", "&lt;").Replace(">", "&gt;"), result.SerializeToXml().Replace("<", "&lt;").Replace(">", "&gt;")); } else { LogManager.Log( LogLevels.Information, true, "Updated budget allocations ({0}) for campaign '{1}'.\n\nRequest:\n{2}\n\nResult:\n{3}", result.Task, campaignEntityId, request.SerializeToXml().Replace("<", "&lt;").Replace(">", "&gt;"), result.SerializeToXml().Replace("<", "&lt;").Replace(">", "&gt;")); } Scheduler.RemoveCompletedEntry<string, DateTime, bool>( DynamicAllocationActivitySchedulerRegistries.CampaignsToReallocate, campaignEntityId); } /// <summary>Submits an update allocation request for a campaign</summary> /// <param name="campaignEntityId">Campaign EntityId</param> /// <param name="companyEntityId">Company EntityId</param> /// <param name="allocationStartDate">Allocation start date</param> /// <param name="isInitialAllocation"> /// Whether the allocation is for the initialization phase or regular reallocation /// </param> /// <returns>True if the request was submitted; otherwise, false.</returns> internal bool SubmitUpdateAllocationRequest( string campaignEntityId, string companyEntityId, DateTime allocationStartDate, bool isInitialAllocation) { // Create a request to update allocations for this campaign var request = new ActivityRequest { Task = DynamicAllocationActivityTasks.GetBudgetAllocations, Values = { { EntityActivityValues.AuthUserId, SystemAuthUserId }, { EntityActivityValues.CompanyEntityId, companyEntityId }, { EntityActivityValues.CampaignEntityId, campaignEntityId }, { DynamicAllocationActivityValues.AllocationStartDate, allocationStartDate.ToString("o", CultureInfo.InvariantCulture) }, { DynamicAllocationActivityValues.IsInitialAllocation, isInitialAllocation.ToString() }, } }; // Submit the request and, if successful, move the corresponding // registry item to the in-progress slot. LogManager.Log( LogLevels.Trace, "Submitting {0} request for campaign '{1}' (AllocationStartDate: '{2}')", DynamicAllocationActivityTasks.GetBudgetAllocations, campaignEntityId, allocationStartDate); if (!this.SubmitRequest(request, ActivityRuntimeCategory.Background, true)) { LogManager.Log( LogLevels.Trace, "Unable to submit {0} request for campaign '{1}'!", DynamicAllocationActivityTasks.GetBudgetAllocations, campaignEntityId); return false; } LogManager.Log( LogLevels.Trace, "Submitted {0} request for campaign '{1}'. Moving to InProgress.", DynamicAllocationActivityTasks.GetBudgetAllocations, campaignEntityId); return true; } } }
44.134969
157
0.594245
[ "Apache-2.0" ]
chinnurtb/OpenAdStack
ScheduledActivityDispatchers/DynamicAllocationActivityDispatchers/UpdateBudgetAllocations.cs
7,196
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetCore.Analyzers.Security.SslProtocolsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetCore.Analyzers.Security.SslProtocolsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetCore.Analyzers.Security.UnitTests { public class SslProtocolsAnalyzerTests { [Fact] public async Task DocSample1_CSharp_Violation() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; public class ExampleClass { public void ExampleMethod() { // CA5397 violation for using Tls11 SslProtocols protocols = SslProtocols.Tls11 | SslProtocols.Tls12; } }", GetCSharpResultAt(10, 34, SslProtocolsAnalyzer.DeprecatedRule, "Tls11"), GetCSharpResultAt(10, 55, SslProtocolsAnalyzer.HardcodedRule, "Tls12")); } [Fact] public async Task DocSample1_VB_Violation() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Security.Authentication Public Class TestClass Public Sub ExampleMethod() ' CA5397 violation for using Tls11 Dim sslProtocols As SslProtocols = SslProtocols.Tls11 Or SslProtocols.Tls12 End Sub End Class ", GetBasicResultAt(8, 44, SslProtocolsAnalyzer.DeprecatedRule, "Tls11"), GetBasicResultAt(8, 66, SslProtocolsAnalyzer.HardcodedRule, "Tls12")); } [Fact] public async Task DocSample2_CSharp_Violation() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; public class ExampleClass { public void ExampleMethod() { // CA5397 violation SslProtocols sslProtocols = (SslProtocols) 768; // TLS 1.1 } }", GetCSharpResultAt(10, 37, SslProtocolsAnalyzer.DeprecatedRule, "768")); } [Fact] public async Task DocSample2_VB_Violation() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Security.Authentication Public Class TestClass Public Sub ExampleMethod() ' CA5397 violation Dim sslProtocols As SslProtocols = CType(768, SslProtocols) ' TLS 1.1 End Sub End Class ", GetBasicResultAt(8, 44, SslProtocolsAnalyzer.DeprecatedRule, "768")); } [Fact] public async Task DocSample1_CSharp_Solution() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; public class TestClass { public void Method() { // Let the operating system decide what TLS protocol version to use. // See https://docs.microsoft.com/dotnet/framework/network-programming/tls SslProtocols sslProtocols = SslProtocols.None; } }"); } [Fact] public async Task DocSample1_VB_Solution() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Security.Authentication Public Class TestClass Public Sub ExampleMethod() ' Let the operating system decide what TLS protocol version to use. ' See https://docs.microsoft.com/dotnet/framework/network-programming/tls Dim sslProtocols As SslProtocols = SslProtocols.None End Sub End Class "); } [Fact] public async Task DocSample3_CSharp_Violation() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; public class ExampleClass { public void ExampleMethod() { // CA5398 violation SslProtocols sslProtocols = SslProtocols.Tls12; } }", GetCSharpResultAt(10, 37, SslProtocolsAnalyzer.HardcodedRule, "Tls12")); } [Fact] public async Task DocSample3_VB_Violation() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Security.Authentication Public Class TestClass Public Function ExampleMethod() As SslProtocols ' CA5398 violation Return SslProtocols.Tls12 End Function End Class ", GetBasicResultAt(8, 16, SslProtocolsAnalyzer.HardcodedRule, "Tls12")); } [Fact] public async Task DocSample4_CSharp_Violation() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; public class ExampleClass { public SslProtocols ExampleMethod() { // CA5398 violation return (SslProtocols) 3072; // TLS 1.2 } }", GetCSharpResultAt(10, 16, SslProtocolsAnalyzer.HardcodedRule, "3072")); } [Fact] public async Task DocSample4_VB_Violation() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.Security.Authentication Public Class TestClass Public Function ExampleMethod() As SslProtocols ' CA5398 violation Return CType(3072, SslProtocols) ' TLS 1.2 End Function End Class ", GetBasicResultAt(8, 16, SslProtocolsAnalyzer.HardcodedRule, "3072")); } [Fact] public async Task Argument_Ssl2_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; class TestClass { public void Method(SslStream sslStream, string targetHost, X509CertificateCollection clientCertificates) { sslStream.AuthenticateAsClient(targetHost, clientCertificates, SslProtocols.Ssl2, false); } }", GetCSharpResultAt(11, 72, SslProtocolsAnalyzer.DeprecatedRule, "Ssl2")); } [Fact] public async Task Argument_Tls12_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; class TestClass { public void Method(SslStream sslStream, string targetHost, X509CertificateCollection clientCertificates) { sslStream.AuthenticateAsClient(targetHost, clientCertificates, SslProtocols.Tls12, false); } }", GetCSharpResultAt(11, 72, SslProtocolsAnalyzer.HardcodedRule, "Tls12")); } [Fact] public async Task Argument_None_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; class TestClass { public void Method(SslStream sslStream, string targetHost, X509CertificateCollection clientCertificates) { sslStream.AuthenticateAsClient(targetHost, clientCertificates, SslProtocols.None, false); } }"); } [Fact] public async Task UseSsl3_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { var a = SslProtocols.Ssl3; } }", GetCSharpResultAt(9, 17, SslProtocolsAnalyzer.DeprecatedRule, "Ssl3")); } [Fact] public async Task UseTls_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { var a = SslProtocols.Tls; } }", GetCSharpResultAt(9, 17, SslProtocolsAnalyzer.DeprecatedRule, "Tls")); } [Fact] public async Task UseTls11_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { SslProtocols protocols = SslProtocols.Tls11; } }", GetCSharpResultAt(9, 34, SslProtocolsAnalyzer.DeprecatedRule, "Tls11")); } [Fact] public async Task UseSystemDefault_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { var a = SslProtocols.Default; } }", GetCSharpResultAt(9, 17, SslProtocolsAnalyzer.DeprecatedRule, "Default")); } [Fact] public async Task UseTls12_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { SslProtocols protocols = SslProtocols.Tls12; } }", GetCSharpResultAt(9, 34, SslProtocolsAnalyzer.HardcodedRule, "Tls12")); } [Fact] public async Task UseTls13_Diagnostic() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net48.Default, TestState = { Sources = { @" using System; using System.Security.Authentication; class TestClass { public void Method() { SslProtocols protocols = SslProtocols.Tls13; } }", }, ExpectedDiagnostics = { GetCSharpResultAt(9, 34, SslProtocolsAnalyzer.HardcodedRule, "Tls13"), }, } }.RunAsync(); } [Fact] public async Task UseTls12OrdTls11_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { SslProtocols protocols = SslProtocols.Tls12 | SslProtocols.Tls11; } }", GetCSharpResultAt(9, 34, SslProtocolsAnalyzer.HardcodedRule, "Tls12"), GetCSharpResultAt(9, 55, SslProtocolsAnalyzer.DeprecatedRule, "Tls11")); } [Fact] public async Task Use192CompoundAssignment_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public SslProtocols SslProtocols { get; set; } public void Method() { this.SslProtocols |= (SslProtocols)192; } }", GetCSharpResultAt(11, 30, SslProtocolsAnalyzer.DeprecatedRule, "192")); } [Fact] public async Task Use384SimpleAssignment_Diagnostic() { // 384 = SchProtocols.Tls11Server | SchProtocols.Tls10Client await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public SslProtocols SslProtocols { get; set; } public void Method() { this.SslProtocols = (SslProtocols)384; } }", GetCSharpResultAt(11, 29, SslProtocolsAnalyzer.DeprecatedRule, "384")); } [Fact] public async Task Use768SimpleAssignmentOrExpression_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public SslProtocols SslProtocols { get; set; } public void Method(SslProtocols input) { this.SslProtocols = input | (SslProtocols)768; } }", GetCSharpResultAt(11, 37, SslProtocolsAnalyzer.DeprecatedRule, "768")); } [Fact] public async Task Use12288SimpleAssignmentOrExpression_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public SslProtocols SslProtocols { get; set; } public void Method(SslProtocols input) { this.SslProtocols = input | (SslProtocols)12288; } }", GetCSharpResultAt(11, 37, SslProtocolsAnalyzer.HardcodedRule, "12288")); } [Fact] public async Task UseTls12OrTls11Or192_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public SslProtocols SslProtocols { get; set; } public void Method() { this.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | (SslProtocols)192; } }", GetCSharpResultAt(11, 29, SslProtocolsAnalyzer.HardcodedRule, "Tls12"), GetCSharpResultAt(11, 50, SslProtocolsAnalyzer.DeprecatedRule, "Tls11")); } [Fact] public async Task UseTls12Or192_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { SslProtocols protocols = SslProtocols.Tls12 | (SslProtocols)192; } }", VerifyCS.Diagnostic(SslProtocolsAnalyzer.HardcodedRule).WithSpan(9, 34, 9, 52).WithArguments("Tls12"), VerifyCS.Diagnostic(SslProtocolsAnalyzer.DeprecatedRule).WithSpan(9, 34, 9, 72).WithArguments("3264")); } [Fact] public async Task Use768DeconstructionAssignment_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public SslProtocols SslProtocols { get; set; } public void Method() { int i; (this.SslProtocols, i) = ((SslProtocols)384, 384); } }"); // Ideally we'd handle the IDeconstructionAssignment, but this code pattern seems unlikely. } [Fact] public async Task Use24Plus24SimpleAssignment_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { SslProtocols sslProtocols = (SslProtocols)(24 + 24); } }", GetCSharpResultAt(9, 37, SslProtocolsAnalyzer.DeprecatedRule, "48")); } [Fact] public async Task Use768NotSslProtocols_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Security.Authentication; class TestClass { public void Method() { int i = 384 | 768; } }"); } private static DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(rule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); private static DiagnosticResult GetBasicResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(rule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); } }
27.250441
161
0.653615
[ "Apache-2.0" ]
AndrewZu1337/roslyn-analyzers
src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/SslProtocolsAnalyzerTests.cs
15,453
C#
/*-----------------------Copyright 2017 www.wlniao.com--------------------------- 文件名称:Wlniao\Handler\IResponse.cs 适用环境:NETCoreCLR 1.0/2.0 最后修改:2017年12月11日 02:58:50 功能描述:管道处理接口 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------------------*/ namespace Wlniao.Handler { /// <summary> /// WlniaoHandler统一输出约束 /// </summary> public interface IResponse { } }
37.222222
83
0.59403
[ "Apache-2.0" ]
wlniao/xcore
Wlniao.XCore/Handler/IResponse.cs
1,077
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CollectionUpdateSample { public partial class About { } }
24.5
81
0.417234
[ "Apache-2.0" ]
volvin/MercadoPago-CSharp-SDK
CollectionUpdateSample/CollectionUpdateSample/About.aspx.designer.cs
443
C#
// Copyright © 2015 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using ExtCore.Data.Abstractions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.Primitives; namespace Platformus.Barebone.Backend.Controllers { [Area("Backend")] public class ImageUploaderController : ControllerBase { private IHostingEnvironment hostingEnvironment; public ImageUploaderController(IStorage storage, IHostingEnvironment hostingEnvironment) : base(storage) { this.hostingEnvironment = hostingEnvironment; } [HttpGet] public ActionResult Index() { return this.View(); } [HttpPost] public async Task<IActionResult> Index(IList<IFormFile> files) { foreach (IFormFile source in files) using (FileStream output = System.IO.File.Create(this.GetTempFilepath(source.FileName))) await source.CopyToAsync(output); return this.Content("filename=" + string.Join(",", files.Select(f => f.FileName))); } [HttpGet] public ActionResult GetCroppedImageUrl(string sourceImageUrl, int sourceX, int sourceY, int sourceWidth, int sourceHeight, string destinationBaseUrl, int destinationWidth, int destinationHeight) { string filename = sourceImageUrl.Substring(sourceImageUrl.LastIndexOf("/") + 1); string tempFilepath = this.GetTempFilepath(filename); string destinationFilepath = this.GetFilepath(destinationBaseUrl, filename); using (Image<Rgba32> image = this.LoadImageFromFile(tempFilepath, out IImageFormat imageFormat)) { if (image.Width == destinationWidth && image.Height == destinationHeight) { if (System.IO.File.Exists(destinationFilepath)) System.IO.File.Delete(destinationFilepath); System.IO.File.Move(tempFilepath, destinationFilepath); } else { image.Mutate( i => i.Crop(new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight)).Resize(destinationWidth, destinationHeight) ); if (string.Equals(imageFormat.Name, "Jpeg", StringComparison.OrdinalIgnoreCase)) image.Save(destinationFilepath, new JpegEncoder() { Quality = 80 }); else image.Save(destinationFilepath); } return this.Content(destinationBaseUrl + filename); } } private Image<Rgba32> LoadImageFromFile(string filepath, out IImageFormat imageFormat) { return Image.Load(filepath, out imageFormat); } private string GetTempFilepath(string filename) { return this.GetFilepath(this.GetTempBasePath(), filename); } private string GetFilepath(string basePath, string filename) { basePath = basePath.Replace('/', '\\'); return this.hostingEnvironment.WebRootPath + basePath.Replace('\\', Path.DirectorySeparatorChar) + filename; } private string GetTempBasePath() { char directorySeparatorChar = Path.DirectorySeparatorChar; return $"{directorySeparatorChar}images{directorySeparatorChar}temp{directorySeparatorChar}"; } } }
33.396226
198
0.714124
[ "Apache-2.0" ]
TarasKovalenko/Platformus
src/Platformus.Barebone.Backend/Areas/Backend/Controllers/ImageUploaderController.cs
3,543
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. namespace Microsoft.AspNetCore.Components.Web.Virtualization { /// <summary> /// Contains context for a placeholder in a virtualized list. /// </summary> public readonly struct PlaceholderContext { /// <summary> /// The item index of the placeholder. /// </summary> public int Index { get; } /// <summary> /// The size of the placeholder in pixels. /// <para> /// For virtualized components with vertical scrolling, this would be the height of the placeholder in pixels. /// For virtualized components with horizontal scrolling, this would be the width of the placeholder in pixels. /// </para> /// </summary> public float Size { get; } /// <summary> /// Constructs a new <see cref="PlaceholderContext"/> instance. /// </summary> /// <param name="index">The item index of the placeholder.</param> /// <param name="size">The size of the placeholder in pixels.</param> public PlaceholderContext(int index, float size = 0f) { Index = index; Size = size; } } }
36.081081
119
0.606742
[ "Apache-2.0" ]
belav/aspnetcore
src/Components/Web/src/Virtualization/PlaceholderContext.cs
1,335
C#
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms. #region Using Statements using WaveEngine.Framework.Graphics; using WaveEngine.Framework.Managers; #endregion namespace WaveEngine.Cardboard { /// <summary> /// The cardboard viewer /// </summary> public class CardboardViewer { /// <summary> /// Gets the cardboard Id /// </summary> public string Id { get; private set; } /// <summary> /// Gets the label /// </summary> public string Label { get; private set; } /// <summary> /// Gets the Field Of View /// </summary> public float FoV { get; private set; } /// <summary> /// Gets the Inter Lens distance /// </summary> public float InterLensDistance { get; private set; } /// <summary> /// Gets the baseline lens distance /// </summary> public float BaselineLensDistance { get; private set; } /// <summary> /// Gets the screen lens distance /// </summary> public float ScreenLensDistance { get; private set; } /// <summary> /// Gets the distortion coefficients /// </summary> public float[] DistortionCoefficients { get; private set; } /// <summary> /// Gets the Inverse coefficients /// </summary> public float[] InverseCoefficients { get; private set; } /// <summary> /// Gets the carboard V1 /// </summary> public static CardboardViewer CardboardV1 { get; private set; } /// <summary> /// Gets the carboard V2 /// </summary> public static CardboardViewer CardboardV2 { get; private set; } static CardboardViewer() { CardboardV1 = new CardboardViewer { Id = "CardboardV1", Label = "Cardboard I/O 2014", FoV = 40, InterLensDistance = 0.060f, BaselineLensDistance = 0.035f, ScreenLensDistance = 0.042f, DistortionCoefficients = new float[] { 0.441f, 0.156f }, InverseCoefficients = new float[] { -0.4410035f, 0.42756155f, -0.4804439f, 0.5460139f, -0.58821183f, 0.5733938f, -0.48303202f, 0.33299083f, -0.17573841f, 0.0651772f, -0.01488963f, 0.001559834f } }; CardboardV2 = new CardboardViewer { Id = "CardboardV2", Label = "Cardboard I/O 2015", FoV = 60, InterLensDistance = 0.064f, BaselineLensDistance = 0.035f, ScreenLensDistance = 0.039f, DistortionCoefficients = new float[] { 0.34f, 0.55f }, InverseCoefficients = new float[] { -0.33836704f, -0.18162185f, 0.862655f, -1.2462051f, 1.0560602f, -0.58208317f, 0.21609078f, -0.05444823f, 0.009177956f, -9.904169E-4f, 6.183535E-5f, -1.6981803E-6f } }; } } }
32.542553
216
0.543969
[ "MIT" ]
WaveEngine/Extensions
WaveEngine.Cardboard/Shared/DeviceInfo/CardboardViewer.cs
3,062
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Owin.Security.Providers.Wargaming")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Owin.Security.Providers.Wargaming")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("8f5acd7a-3c19-49d6-ac5f-2368e2534452")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
36.5625
64
0.765812
[ "MIT" ]
AliEbadi/OwinOAuthProviders
src/Owin.Security.Providers.Wargaming/Properties/AssemblyInfo.cs
588
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // Generated with Bot Builder V4 SDK Template for Visual Studio EchoBot v$templateversion$ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using $safeprojectname$.Bots; namespace $safeprojectname$ { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Create the Bot Framework Adapter with error handling enabled. services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. services.AddTransient<IBot, EchoBot>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseDefaultFiles(); app.UseStaticFiles(); //app.UseHttpsRedirection(); app.UseMvc(); } } }
31.728814
106
0.657051
[ "MIT" ]
AlaMohamed/Samples
generators/vsix-vs-win/BotBuilderVSIX-V4/UncompressedProjectTemplates/EchoBot/Startup.cs
1,874
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="INuGetBasedModuleCatalogExtensions.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if NET namespace Catel.Modules { using System.Collections.Generic; using System.Linq; using NuGet; /// <summary> /// INuGetBasedModuleCatalog eExtensions. /// </summary> public static class INuGetBasedModuleCatalogExtensions { /// <summary> /// Gets all package sources. /// </summary> /// <param name="moduleCatalog">The module catalog.</param> /// <param name="allowParentPackageSources">if set to <c>true</c>, allow other packages sources fetched via the parent.</param> /// <returns>IEnumerable&lt;IPackageSource&gt;.</returns> public static IEnumerable<IPackageRepository> GetAllPackageRepositories(this INuGetBasedModuleCatalog moduleCatalog, bool allowParentPackageSources) { Argument.IsNotNull("moduleCatalog", moduleCatalog); var packageRepositories = new List<IPackageRepository>(); packageRepositories.AddRange(moduleCatalog.GetPackageRepositories()); if (allowParentPackageSources) { var compositeNuGetBasedModuleCatalog = moduleCatalog.Parent as CompositeNuGetBasedModuleCatalog; if (compositeNuGetBasedModuleCatalog != null) { var parentPackageRepositories = compositeNuGetBasedModuleCatalog.GetAllPackageRepositories(allowParentPackageSources).ToList(); // Reverse so we have the first parent first and the final parent last parentPackageRepositories.Reverse(); foreach (var parentPackageRepository in parentPackageRepositories) { if (!packageRepositories.Contains(parentPackageRepository)) { packageRepositories.Add(parentPackageRepository); } } } } return packageRepositories; } } } #endif
41
156
0.565523
[ "MIT" ]
uQr/Catel
src/Catel.Extensions.Prism/Catel.Extensions.Prism.Shared/Modules/Extensions/INuGetBasedModuleCatalogExtensions.cs
2,421
C#
using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using NBitcoin; using WalletWasabi.Blockchain.TransactionBuilding; using WalletWasabi.Blockchain.TransactionBuilding.BnB; using WalletWasabi.Blockchain.TransactionOutputs; using WalletWasabi.Fluent.Helpers; using WalletWasabi.Wallets; namespace WalletWasabi.Fluent.ViewModels.Wallets.Send; public partial class ChangeAvoidanceSuggestionViewModel : SuggestionViewModel { [AutoNotify] private string _amount; [AutoNotify] private string _amountFiat; [AutoNotify] private string? _differenceFiat; public ChangeAvoidanceSuggestionViewModel(decimal originalAmount, BuildTransactionResult transactionResult, decimal fiatExchangeRate, bool isOriginal) { TransactionResult = transactionResult; decimal total = transactionResult.CalculateDestinationAmount().ToDecimal(MoneyUnit.BTC); _amountFiat = total.GenerateFiatText(fiatExchangeRate, "USD"); if (!isOriginal) { var fiatTotal = total * fiatExchangeRate; var fiatOriginal = originalAmount * fiatExchangeRate; var fiatDifference = fiatTotal - fiatOriginal; _differenceFiat = (fiatDifference > 0 ? $"{fiatDifference.GenerateFiatText("USD")} More" : $"{Math.Abs(fiatDifference).GenerateFiatText("USD")} Less") .Replace("(", "").Replace(")", ""); } _amount = $"{total} BTC"; } public BuildTransactionResult TransactionResult { get; } public static async IAsyncEnumerable<ChangeAvoidanceSuggestionViewModel> GenerateSuggestionsAsync( TransactionInfo transactionInfo, BitcoinAddress destination, Wallet wallet, [EnumeratorCancellation] CancellationToken cancellationToken) { var selections = ChangelessTransactionCoinSelector.GetAllStrategyResultsAsync( transactionInfo.Coins, transactionInfo.FeeRate, new TxOut(transactionInfo.Amount, destination), cancellationToken).ConfigureAwait(false); await foreach (var selection in selections) { if (selection.Any()) { BuildTransactionResult transaction = TransactionHelpers.BuildChangelessTransaction( wallet, destination, transactionInfo.UserLabels, transactionInfo.FeeRate, selection, tryToSign: false); yield return new ChangeAvoidanceSuggestionViewModel( transactionInfo.Amount.ToDecimal(MoneyUnit.BTC), transaction, wallet.Synchronizer.UsdExchangeRate, isOriginal: false); } } } }
30.195122
99
0.780291
[ "MIT" ]
Trxlz/WalletWasabi
WalletWasabi.Fluent/ViewModels/Wallets/Send/ChangeAvoidanceSuggestionViewModel.cs
2,476
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.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Localization { internal static partial class RequestCultureProviderLoggerExtensions { [LoggerMessage(1, LogLevel.Debug, "{requestCultureProvider} returned the following unsupported cultures '{cultures}'.", EventName = "UnsupportedCulture")] public static partial void UnsupportedCultures(this ILogger logger, string requestCultureProvider, IList<StringSegment> cultures); [LoggerMessage(2, LogLevel.Debug, "{requestCultureProvider} returned the following unsupported UI Cultures '{uiCultures}'.", EventName = "UnsupportedUICulture")] public static partial void UnsupportedUICultures(this ILogger logger, string requestCultureProvider, IList<StringSegment> uiCultures); } }
48.190476
169
0.786561
[ "MIT" ]
48355746/AspNetCore
src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs
1,012
C#
// <copyright file="Group.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using BeanIO.Internal.Config; using BeanIO.Internal.Util; namespace BeanIO.Internal.Parser { /// <summary> /// A Group holds child nodes including records and other groups /// </summary> /// <remarks> /// This class is the dynamic counterpart to the <see cref="GroupConfig"/> and /// holds the current state of a group node during stream processing. /// </remarks> internal class Group : ParserComponent, ISelector { /// <summary> /// map key used to store the state of the 'lastMatchedChild' attribute /// </summary> private const string LAST_MATCHED_KEY = "lastMatched"; private readonly ParserLocal<int> _count = new ParserLocal<int>(0); private readonly ParserLocal<ISelector> _lastMatched = new ParserLocal<ISelector>(); /// <summary> /// Initializes a new instance of the <see cref="Group"/> class. /// </summary> public Group() : base(5) { Order = 1; MaxOccurs = int.MaxValue; } /// <summary> /// Gets the size of a single occurrence of this element, which is used to offset /// field positions for repeating segments and fields. /// </summary> /// <remarks> /// The concept of size is dependent on the stream format. The size of an element in a fixed /// length stream format is determined by the length of the element in characters, while other /// stream formats calculate size based on the number of fields. Some stream formats, /// such as XML, may ignore size settings. /// </remarks> public override int? Size => null; /// <summary> /// Gets or sets a value indicating whether this parser or any descendant of this parser is used to identify /// a record during unmarshalling. /// </summary> public override bool IsIdentifier { get { return false; } set { if (value) throw new NotSupportedException(); } } /// <summary> /// Gets a value indicating whether this node must exist during unmarshalling. /// </summary> public override bool IsOptional => MinOccurs == 0; /// <summary> /// Gets or sets the minimum number of occurrences of this component (within the context of its parent). /// </summary> public int MinOccurs { get; set; } /// <summary> /// Gets or sets the maximum number of occurrences of this component (within the context of its parent). /// </summary> public int? MaxOccurs { get; set; } /// <summary> /// Gets or sets the order of this component (within the context of its parent). /// </summary> public int Order { get; set; } /// <summary> /// Gets or sets the <see cref="IProperty"/> mapped to this component, or null if there is no property mapping. /// </summary> public IProperty Property { get; set; } /// <summary> /// Gets a value indicating whether this component is a record group. /// </summary> public bool IsRecordGroup => true; /// <summary> /// Returns whether this parser and its children match a record being unmarshalled. /// </summary> /// <param name="context">The <see cref="UnmarshallingContext"/></param> /// <returns>true if matched, false otherwise</returns> public override bool Matches(UnmarshallingContext context) { return false; } /// <summary> /// Unmarshals a record /// </summary> /// <param name="context">The <see cref="UnmarshallingContext"/></param> /// <returns>true if this component was present in the unmarshalled record, or false otherwise</returns> public override bool Unmarshal(UnmarshallingContext context) { // this method is only invoked when this group is configured to // unmarshal a bean object that spans multiple records try { var child = _lastMatched.Get(context); child.Unmarshal(context); // read the next record while (true) { context.NextRecord(); if (context.IsEof) { var unsatisfied = Close(context); if (unsatisfied != null) throw context.NewUnsatisfiedRecordException(unsatisfied.Name); break; } child = MatchCurrent(context); if (child == null) { Reset(context); break; } try { child.Unmarshal(context); } catch (AbortRecordUnmarshalligException) { // Ignore aborts } } Property?.CreateValue(context); return true; } catch (UnsatisfiedNodeException ex) { throw context.NewUnsatisfiedRecordException(ex.Node.Name); } } /// <summary> /// Marshals a record /// </summary> /// <param name="context">The <see cref="MarshallingContext"/></param> /// <returns>whether a value was marshalled</returns> public override bool Marshal(MarshallingContext context) { // this method is only invoked when this group is configured to // marshal a bean object that spans multiple records return Children.Cast<IParser>().Aggregate(false, (current, child) => child.Marshal(context) || current); } /// <summary> /// Returns whether this parser or any of its descendant have content for marshalling. /// </summary> /// <param name="context">The <see cref="ParsingContext"/></param> /// <returns>true if there is content for marshalling, false otherwise</returns> public override bool HasContent(ParsingContext context) { if (Property != null) return !ReferenceEquals(Property.GetValue(context), Value.Missing); return Children.Cast<IParser>().Any(child => child.HasContent(context)); } /// <summary> /// Clears the current property value. /// </summary> /// <param name="context">The <see cref="ParsingContext"/></param> public override void ClearValue(ParsingContext context) { Property?.ClearValue(context); } /// <summary> /// Sets the property value for marshaling. /// </summary> /// <param name="context">The <see cref="ParsingContext"/></param> /// <param name="value">the property value</param> public override void SetValue(ParsingContext context, object value) { Property.SetValue(context, value); } /// <summary> /// Returns the unmarshalled property value. /// </summary> /// <param name="context">The <see cref="ParsingContext"/></param> /// <returns>the property value</returns> public override object GetValue(ParsingContext context) { return Property.GetValue(context); } /// <summary> /// Returns the number of times this component was matched within the current /// iteration of its parent component. /// </summary> /// <param name="context">the <see cref="ParsingContext"/></param> /// <returns>the match count</returns> public int GetCount(ParsingContext context) { return _count.Get(context); } /// <summary> /// Sets the number of times this component was matched within the current /// iteration of its parent component. /// </summary> /// <param name="context">the <see cref="ParsingContext"/></param> /// <param name="value">the new count</param> public void SetCount(ParsingContext context, int value) { _count.Set(context, value); } /// <summary> /// Returns a value indicating whether this component has reached its maximum occurrences /// </summary> /// <param name="context">the <see cref="ParsingContext"/></param> /// <returns>true if maximum occurrences has been reached</returns> public bool IsMaxOccursReached(ParsingContext context) { return _lastMatched.Get(context) == null && MaxOccurs != null && GetCount(context) >= MaxOccurs; } /// <summary> /// Finds a parser for marshalling a bean object /// </summary> /// <remarks> /// If matched by this Selector, the method /// should set the bean object on the property tree and return itself. /// </remarks> /// <param name="context">the <see cref="MarshallingContext"/></param> /// <returns>the matched <see cref="ISelector"/> for marshalling the bean object</returns> public ISelector MatchNext(MarshallingContext context) { try { if (Property == null) return InternalMatchNext(context); var componentName = context.ComponentName; if (componentName != null && Name != componentName) return null; var value = context.Bean; if (Property.Defines(value)) { Property.SetValue(context, value); return this; } return null; } catch (UnsatisfiedNodeException ex) { throw new BeanWriterException($"Bean identification failed: expected record type '{ex.Node.Name}'", ex); } } /// <summary> /// Finds a parser for unmarshalling a record based on the current state of the stream. /// </summary> /// <param name="context">the <see cref="UnmarshallingContext"/></param> /// <returns>the matched <see cref="ISelector"/> for unmarshalling the record</returns> public ISelector MatchNext(UnmarshallingContext context) { try { return InternalMatchNext(context); } catch (UnsatisfiedNodeException ex) { throw context.NewUnsatisfiedRecordException(ex.Node.Name); } } /// <summary> /// Finds a parser that matches the input record /// </summary> /// <remarks> /// This method is invoked when <see cref="ISelector.MatchNext(BeanIO.Internal.Parser.UnmarshallingContext)"/> returns /// null, in order to differentiate between unexpected and unidentified record types. /// </remarks> /// <param name="context">the <see cref="UnmarshallingContext"/></param> /// <returns>the matched <see cref="ISelector"/></returns> public ISelector MatchAny(UnmarshallingContext context) { return Children.Cast<ISelector>().Select(x => x.MatchAny(context)).FirstOrDefault(x => x != null); } /// <summary> /// Skips a record or group of records. /// </summary> /// <param name="context">the <see cref="UnmarshallingContext"/></param> public void Skip(UnmarshallingContext context) { // this method is only invoked when this group is configured to // unmarshal a bean object that spans multiple records try { var child = _lastMatched.Get(context); child.Skip(context); // read the next record while (true) { context.NextRecord(); if (context.IsEof) { var unsatisfied = Close(context); if (unsatisfied != null) throw context.NewUnsatisfiedRecordException(unsatisfied.Name); break; } // find the child unmarshaller for the record... child = MatchCurrent(context); if (child == null) { Reset(context); break; } child.Skip(context); } } catch (UnsatisfiedNodeException ex) { throw context.NewUnsatisfiedRecordException(ex.Node.Name); } } /// <summary> /// Checks for any unsatisfied components before the stream is closed. /// </summary> /// <param name="context">the <see cref="ParsingContext"/></param> /// <returns>the first unsatisfied node</returns> public ISelector Close(ParsingContext context) { var lastMatch = _lastMatched.Get(context); if (lastMatch == null && MinOccurs == 0) return null; var pos = lastMatch?.Order ?? 1; var unsatisfied = FindUnsatisfiedChild(context, pos); if (unsatisfied != null) return unsatisfied; if (GetCount(context) < MinOccurs) { // try to find a specific record before reporting any record from this group if (pos > 1) { Reset(context); unsatisfied = FindUnsatisfiedChild(context, 1); if (unsatisfied != null) return unsatisfied; } return this; } return null; } /// <summary> /// Resets the component count of this Selector's children. /// </summary> /// <param name="context">the <see cref="ParsingContext"/></param> public void Reset(ParsingContext context) { _lastMatched.Set(context, null); foreach (var node in Children.Cast<ISelector>()) { node.SetCount(context, 0); node.Reset(context); } } /// <summary> /// Updates a <see cref="IDictionary{TKey,TValue}"/> with the current state of the Writer to allow for restoration at a later time. /// </summary> /// <param name="context">the <see cref="ParsingContext"/></param> /// <param name="ns">a <see cref="string"/> to prefix all state keys with</param> /// <param name="state">the <see cref="IDictionary{TKey,TValue}"/> to update with the latest state</param> public void UpdateState(ParsingContext context, string ns, IDictionary<string, object> state) { state[GetKey(ns, COUNT_KEY)] = _count.Get(context); var lastMatchedChildName = string.Empty; var lastMatch = _lastMatched.Get(context); if (lastMatch != null) lastMatchedChildName = lastMatch.Name; state[GetKey(ns, LAST_MATCHED_KEY)] = lastMatchedChildName; // allow children to update their state foreach (var node in this.Cast<ISelector>()) node.UpdateState(context, ns, state); } /// <summary> /// Restores a <see cref="IDictionary{TKey,TValue}"/> of previously stored state information /// </summary> /// <param name="context">the <see cref="ParsingContext"/></param> /// <param name="ns">a <see cref="string"/> to prefix all state keys with</param> /// <param name="state">the <see cref="IDictionary{TKey,TValue}"/> containing the state to restore</param> public void RestoreState(ParsingContext context, string ns, IReadOnlyDictionary<string, object> state) { var key = GetKey(ns, COUNT_KEY); var n = (int?)state.Get(key); if (n == null) throw new InvalidOperationException($"Missing state information for key '{key}'"); _count.Set(context, n.Value); // determine the last matched child key = GetKey(ns, LAST_MATCHED_KEY); var lastMatchedChildName = (string)state.Get(key); if (lastMatchedChildName == null) throw new InvalidOperationException($"Missing state information for key '{key}'"); if (lastMatchedChildName.Length == 0) { _lastMatched.Set(context, null); lastMatchedChildName = null; } foreach (var child in Children.Cast<ISelector>()) { if (lastMatchedChildName != null && lastMatchedChildName == child.Name) _lastMatched.Set(context, child); child.RestoreState(context, ns, state); } } /// <summary> /// Called by a stream to register variables stored in the parsing context. /// </summary> /// <remarks> /// This method should be overridden by subclasses that need to register /// one or more parser context variables. /// </remarks> /// <param name="locals">set of local variables</param> public override void RegisterLocals(ISet<IParserLocal> locals) { ((Component)Property)?.RegisterLocals(locals); if (locals.Add(_lastMatched)) { locals.Add(_count); base.RegisterLocals(locals); } } /// <summary> /// Returns whether a node is a supported child of this node. /// </summary> /// <remarks> /// Called by <see cref="TreeNode{T}.Add"/>. /// </remarks> /// <param name="child">the node to test</param> /// <returns>true if the child is allowed</returns> public override bool IsSupportedChild(Component child) { return child is ISelector; } /// <summary> /// Called by <see cref="TreeNode{T}.ToString"/> to append node parameters to the output /// </summary> /// <param name="s">The output to append</param> protected override void ToParamString(StringBuilder s) { base.ToParamString(s); s .AppendFormat(", order={0}", Order) .AppendFormat(", occurs={0}", DebugUtil.FormatRange(MinOccurs, MaxOccurs)); if (Property != null) s.AppendFormat(", property={0}", Property); } private ISelector FindUnsatisfiedChild(ParsingContext context, int from) { // find any unsatisfied child foreach (var node in Children.Cast<ISelector>()) { if (node.Order < from) continue; var unsatisfied = node.Close(context); if (unsatisfied != null) return unsatisfied; } return null; } private ISelector InternalMatchNext(ParsingContext context) { /* * A matching record is searched for in 3 stages: * 1. First, we give the last matching node an opportunity to match the next * record if it hasn't reached it's max occurs. * 2. Second, we search for another matching node at the same position/order * or increment the position until we find a matching node or a min occurs * is not met. * 3. Finally, if all nodes in this group have been satisfied and this group * hasn't reached its max occurs, we search nodes from the beginning again * and increment the group count if a node matches. * * If no match is found, there SHOULD be no changes to the state of this node. */ var match = MatchCurrent(context); if (match == null && (MaxOccurs == null || MaxOccurs > 1)) match = MatchAgain(context); if (match != null) return Property != null ? this : match; return null; } private ISelector MatchAgain(ParsingContext context) { ISelector unsatisfied = null; if (_lastMatched.Get(context) != null) { // no need to check if the max occurs was already reached if (MaxOccurs != null && GetCount(context) >= MaxOccurs) return null; // if there was no unsatisfied node and we haven't reached the max occurs, // try to find a match from the beginning again so that the parent can // skip this node var position = 1; foreach (var node in Children.Cast<ISelector>()) { if (node.Order > position) { if (unsatisfied != null) return null; position = node.Order; } if (node.MinOccurs > 0) { // when marshalling, allow records to be skipped that aren't bound to a property if (context.Mode != ParsingMode.Marshalling || node.Property != null) unsatisfied = node; } ISelector match = MatchNext(context, node); if (match != null) { // this is different than reset() because we reset every node // except the one that matched... foreach (var sel in Children.Cast<ISelector>()) { if (ReferenceEquals(sel, node)) continue; sel.SetCount(context, 0); sel.Reset(context); } _count.Set(context, _count.Get(context) + 1); node.SetCount(context, 1); _lastMatched.Set(context, node); return match; } } } return null; } private ISelector MatchCurrent(ParsingContext context) { ISelector match; ISelector unsatisfied = null; ISelector lastMatch = _lastMatched.Get(context); // check the last matching node - do not check records where the max occurs // has already been reached if (lastMatch != null && !lastMatch.IsMaxOccursReached(context)) { match = MatchNext(context, lastMatch); if (match != null) return match; } // set the current position to the order of the last matched node (or default to 1) var position = lastMatch?.Order ?? 1; // iterate over each child foreach (var node in Children.Cast<ISelector>()) { // skip the last node which was already checked if (node == lastMatch) continue; // skip nodes where their order is less than the current position if (node.Order < position) continue; // skip nodes where max occurs has already been met if (node.IsMaxOccursReached(context)) continue; // if no node matched at the current position, increment the position and test the next node if (node.Order > position) { // before increasing the position, we must validate that all // min occurs have been met at the previous position if (unsatisfied != null) { if (lastMatch != null) throw new UnsatisfiedNodeException(unsatisfied); return null; } position = node.Order; } // if the min occurs has not been met for the next node, set the unsatisfied flag so we // can throw an exception before incrementing the position again if (node.GetCount(context) < node.MinOccurs) { // when marshalling, allow records to be skipped that aren't bound to a property if (context.Mode != ParsingMode.Marshalling || node.Property != null) { unsatisfied = node; } } // search the child node for a match match = MatchNext(context, node); if (match != null) { // the group count is incremented only when first invoked if (lastMatch == null) { _count.Set(context, _count.Get(context) + 1); } else { // reset the last group when a new record or group is found // at the same level (this has no effect for a record) lastMatch.Reset(context); } _lastMatched.Set(context, node); return match; } } // if last was not null, we continued checking for matches at the current position, now // we'll check for matches at the beginning (assuming there is no unsatisfied node) if (lastMatch != null && unsatisfied != null) throw new UnsatisfiedNodeException(unsatisfied); return null; } private ISelector MatchNext(ParsingContext context, ISelector child) { switch (context.Mode) { case ParsingMode.Marshalling: return child.MatchNext((MarshallingContext)context); case ParsingMode.Unmarshalling: return child.MatchNext((UnmarshallingContext)context); default: throw new InvalidOperationException($"Invalid mode: {context.Mode}"); } } private string GetKey(string ns, string name) { return $"{ns}.{Name}.{name}"; } private class UnsatisfiedNodeException : BeanIOException { public UnsatisfiedNodeException(ISelector node) { Node = node; } public ISelector Node { get; } } } }
38.378976
139
0.525371
[ "MIT" ]
FubarDevelopment/beanio-net
src/FubarDev.BeanIO/Internal/Parser/Group.cs
27,748
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.ComponentModel; using Azure.Core; namespace Azure.Messaging.EventHubs.Consumer { /// <summary> /// The position of events in an Event Hub partition, typically used in the creation of /// an <see cref="EventHubConsumerClient" />. /// </summary> /// public struct EventPosition : IEquatable<EventPosition> { /// <summary>The token that represents the beginning event in the stream of a partition.</summary> private const string StartOfStreamOffset = "-1"; /// <summary>The token that represents the last event in the stream of a partition.</summary> private const string EndOfStreamOffset = "@latest"; /// <summary> /// Corresponds to the location of the first event present in the partition. Use this /// position to begin receiving from the first event that was enqueued in the partition /// which has not expired due to the retention policy. /// </summary> /// public static EventPosition Earliest => FromOffset(StartOfStreamOffset, false); /// <summary> /// Corresponds to the end of the partition, where no more events are currently enqueued. Use this /// position to begin receiving from the next event to be enqueued in the partition after an <see cref="EventHubConsumerClient"/> /// is created with this position. /// </summary> /// public static EventPosition Latest => FromOffset(EndOfStreamOffset, false); /// <summary> /// The offset of the event identified by this position. /// </summary> /// /// <value>Expected to be <c>null</c> if the event position represents a sequence number or enqueue time.</value> /// /// <remarks> /// The offset is the relative position for event in the context of the stream. The offset /// should not be considered a stable value, as the same offset may refer to a different event /// as events reach the age limit for retention and are no longer visible within the stream. /// </remarks> /// internal string Offset { get; set; } /// <summary> /// Indicates if the specified offset is inclusive of the event which it identifies. This /// information is only relevant if the event position was identified by an offset or sequence number. /// </summary> /// /// <value><c>true</c> if the offset is inclusive; otherwise, <c>false</c>.</value> /// internal bool IsInclusive { get; set; } /// <summary> /// The enqueue time of the event identified by this position. /// </summary> /// /// <value>Expected to be <c>null</c> if the event position represents an offset or sequence number.</value> /// internal DateTimeOffset? EnqueuedTime { get; set; } /// <summary> /// The sequence number of the event identified by this position. /// </summary> /// /// <value>Expected to be <c>null</c> if the event position represents an offset or enqueue time.</value> /// internal long? SequenceNumber { get; set; } /// <summary> /// Corresponds to the event in the partition at the provided offset, inclusive of that event. /// </summary> /// /// <param name="offset">The offset of an event with respect to its relative position in the partition.</param> /// <param name="isInclusive">If true, the event with the <paramref name="offset"/> is included; otherwise the next event in sequence will be received.</param> /// /// <returns>The position of the specified event.</returns> /// public static EventPosition FromOffset(long offset, bool isInclusive = true) => FromOffset(offset.ToString(), isInclusive); /// <summary> /// Corresponds to the event in the partition having a specified sequence number associated with it. /// </summary> /// /// <param name="sequenceNumber">The sequence number assigned to an event when it was enqueued in the partition.</param> /// <param name="isInclusive">If true, the event with the <paramref name="sequenceNumber"/> is included; otherwise the next event in sequence will be received.</param> /// /// <returns>The position of the specified event.</returns> /// public static EventPosition FromSequenceNumber(long sequenceNumber, bool isInclusive = true) { return new EventPosition { SequenceNumber = sequenceNumber, IsInclusive = isInclusive }; } /// <summary> /// Corresponds to a specific date and time within the partition to begin seeking an event; the event enqueued after the /// requested <paramref name="enqueuedTime" /> will become the current position. /// </summary> /// /// <param name="enqueuedTime">The date and time, in UTC, from which the next available event should be chosen.</param> /// /// <returns>The position of the specified event.</returns> /// public static EventPosition FromEnqueuedTime(DateTimeOffset enqueuedTime) { return new EventPosition { EnqueuedTime = enqueuedTime }; } /// <summary> /// Determines whether the specified <see cref="EventPosition" /> is equal to this instance. /// </summary> /// /// <param name="other">The <see cref="EventPosition" /> to compare with this instance.</param> /// /// <returns><c>true</c> if the specified <see cref="EventPosition" /> is equal to this instance; otherwise, <c>false</c>.</returns> /// [EditorBrowsable(EditorBrowsableState.Never)] public bool Equals(EventPosition other) { if (ReferenceEquals(this, other)) { return true; } return (Offset == other.Offset) && (SequenceNumber == other.SequenceNumber) && (EnqueuedTime == other.EnqueuedTime) && (IsInclusive == other.IsInclusive); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> /// [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj switch { EventPosition other => Equals(other), _ => ReferenceEquals(this, obj) }; /// <summary> /// Returns a hash code for this instance. /// </summary> /// /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> /// [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { var hashCode = new HashCodeBuilder(); hashCode.Add(Offset); hashCode.Add(SequenceNumber); hashCode.Add(EnqueuedTime); hashCode.Add(IsInclusive); return hashCode.ToHashCode(); } /// <summary> /// Converts the instance to string representation. /// </summary> /// /// <returns>A <see cref="System.String" /> that represents this instance.</returns> /// [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() => base.ToString(); /// <summary> /// Corresponds to the event in the partition at the provided offset. /// </summary> /// /// <param name="offset">The offset of an event with respect to its relative position in the partition.</param> /// <param name="isInclusive">If true, the event at the <paramref name="offset"/> is included; otherwise the next event in sequence will be received.</param> /// /// <returns>The position of the specified event.</returns> /// private static EventPosition FromOffset(string offset, bool isInclusive) { Argument.AssertNotNullOrWhiteSpace(nameof(offset), offset); return new EventPosition { Offset = offset, IsInclusive = isInclusive }; } /// <summary> /// Determines whether the specified <see cref="EventPosition" /> instances are equal to each other. /// </summary> /// /// <param name="first">The first <see cref="EventPosition" /> to consider.</param> /// <param name="second">The second <see cref="EventPosition" /> to consider.</param> /// /// <returns><c>true</c> if the two specified <see cref="EventPosition" /> instances are equal; otherwise, <c>false</c>.</returns> /// public static bool operator ==(EventPosition first, EventPosition second) => first.Equals(second); /// <summary> /// Determines whether the specified <see cref="EventPosition" /> instances are not equal to each other. /// </summary> /// /// <param name="first">The first <see cref="EventPosition" /> to consider.</param> /// <param name="second">The second <see cref="EventPosition" /> to consider.</param> /// /// <returns><c>true</c> if the two specified <see cref="EventPosition" /> instances are not equal; otherwise, <c>false</c>.</returns> /// public static bool operator !=(EventPosition first, EventPosition second) => (!first.Equals(second)); } }
44.075949
175
0.58185
[ "MIT" ]
Ianmatthews9934/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/EventPosition.cs
10,448
C#
using System; using UnityEngine; namespace UnityMVVM.Binding.Converters { public class TextTransformationConverter : ValueConverterBase { [SerializeField] Transformation _transformation; public override object Convert(object value, Type targetType, object parameter) { switch (_transformation) { case Transformation.ToLower: return value.ToString().ToLower(); case Transformation.ToUpper: return value.ToString().ToUpper(); default: return value; } } public override object ConvertBack(object value, Type targetType, object parameter) { throw new NotImplementedException(); } enum Transformation { ToLower, ToUpper } } }
25.857143
91
0.555801
[ "MIT" ]
aliagamon/Unity-MVVM
Assets/Unity-MVVM/Converters/TextTransformationConverter.cs
907
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SteamBotExample.SteamApi.IEconService.GetTradeOffers { public class TradeSendFromIEconService_Response { [JsonProperty("trade_offers_sent")] public TradeOfferFromIEconService[] TradeOffersSent { get; set; } //received? -> Not needed at the moment } }
22.888889
67
0.793689
[ "MIT" ]
BattleRush/SteamTradeExample-Console
SteamBotExample/SteamApi/IEconService/GetTradeOffers/TradeSendFromIEconService_Response.cs
414
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NumberComparer { class Program { static void Main() { Console.Write("a = "); double a = double.Parse(Console.ReadLine()); Console.Write("b = "); double b = double.Parse(Console.ReadLine()); while (a.CompareTo(b) == 1) { Console.WriteLine("{0} is greater", a); break; } while (a.CompareTo(b) == -1) { Console.WriteLine("{0} is greater", b); break; } while (a.CompareTo(b) == 0) { Console.WriteLine("{0} == {1}", a, b); break; } } } }
23.611111
56
0.442353
[ "MIT" ]
Maxtorque/Console-Input-Output
NumberComparer/Program.cs
852
C#
namespace Piglet.Parser.Configuration { internal class Symbol<T> : ISymbol<T> { public string DebugName { get; set; } public int TokenNumber { get; set; } } }
20.888889
45
0.611702
[ "Apache-2.0" ]
schifflee/AutoIt-Interpreter
PigletParser/Parser/Configuration/Symbol.cs
190
C#
//--------------------------------------------------------------------- // <copyright file="EntityDataSourceViewSchema.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Web.UI.WebControls { using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; using System.Reflection; internal class EntityDataSourceViewSchema : DataTable { internal EntityDataSourceViewSchema(EntityDataSourceWrapperCollection wrappers) { DataColumn column; List<DataColumn> keys = new List<DataColumn>(); PropertyDescriptorCollection properties = wrappers.GetItemProperties(null); MetadataWorkspace workspace = wrappers.Context.MetadataWorkspace; foreach (EntityDataSourceWrapperPropertyDescriptor property in properties) { Type propertyType = property.PropertyType; column = ConstructColumn(property); column.AllowDBNull = property.Column.IsNullable; EntityDataSourcePropertyColumn propertyColumn = property.Column as EntityDataSourcePropertyColumn; if (null!= propertyColumn && propertyColumn.IsKey) { keys.Add(column); } Columns.Add(column); } this.PrimaryKey = keys.ToArray(); } internal EntityDataSourceViewSchema(ITypedList typedList) { PropertyDescriptorCollection properties = typedList.GetItemProperties(null); CreateColumnsFromPropDescs(properties, null); } internal EntityDataSourceViewSchema(IEnumerable results) : this(results, null) { } /// <summary> /// Creates a view schema with a set of typed results and an optional set of keyName properties on those results /// </summary> internal EntityDataSourceViewSchema(IEnumerable results, string[] keyNames) { Type type = GetListItemType(results.GetType()); PropertyInfo[] infos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(type); CreateColumnsFromPropDescs(properties, keyNames); } /// <summary> /// Creates a set of DataTable columns from a collection of property descriptors and an optional /// set of key names from metadata /// </summary> private void CreateColumnsFromPropDescs(PropertyDescriptorCollection properties, string[] keyNames) { List<DataColumn> keys = new List<DataColumn>(); foreach (PropertyDescriptor property in properties) { System.ComponentModel.BrowsableAttribute attr = (System.ComponentModel.BrowsableAttribute)property.Attributes[typeof(System.ComponentModel.BrowsableAttribute)]; if (attr.Browsable) { DataColumn column = ConstructColumn(property); // If there are keyNames, check if this column is one of the keys if (keyNames != null && keyNames.Contains(column.ColumnName)) { keys.Add(column); } this.Columns.Add(column); } } if (keys.Count > 0) { this.PrimaryKey = keys.ToArray(); } } private static DataColumn ConstructColumn(PropertyDescriptor property) { DataColumn column = new DataColumn(); column.ColumnName = property.Name; Type propertyType = property.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type[] typeArguments = propertyType.GetGenericArguments(); Debug.Assert(typeArguments.Length == 1, "should only have one type argument from Nullable<> condition."); column.DataType = typeArguments[0]; column.AllowDBNull = true; } else { column.DataType = propertyType; column.AllowDBNull = !propertyType.IsValueType; } column.ReadOnly = property.IsReadOnly; column.Unique = false; column.AutoIncrement = false; column.MaxLength = -1; return column; } // see System.Data.Objects.DataRecordObjectView.cs private static PropertyInfo GetTypedIndexer(Type type) { PropertyInfo indexer = null; if (typeof(IList).IsAssignableFrom(type) || typeof(ITypedList).IsAssignableFrom(type) || typeof(IListSource).IsAssignableFrom(type)) { System.Reflection.PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); for (int idx = 0; idx < props.Length; idx++) { if (props[idx].GetIndexParameters().Length > 0 && props[idx].PropertyType != typeof(object)) { indexer = props[idx]; //Prefer the standard indexer, if there is one if (indexer.Name == "Item") { break; } } } } return indexer; } // see System.Data.Objects.DataRecordObjectView.cs private static Type GetListItemType(Type type) { Type itemType; if (typeof(Array).IsAssignableFrom(type)) { itemType = type.GetElementType(); } else { PropertyInfo typedIndexer = GetTypedIndexer(type); if (typedIndexer != null) { itemType = typedIndexer.PropertyType; } else { itemType = type; } } return itemType; } } }
36.147541
132
0.545276
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/DataWebControls/System/Data/WebControls/EntityDataSourceViewSchema.cs
6,617
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Runtime.Serialization; using System.Xml.Serialization; namespace Microsoft.WindowsAzure.Commands.Utilities.Websites.Services.GeoEntities { [DataContract] [XmlRoot("GeoRegion", Namespace = UriElements.ServiceNamespace)] public class GeoRegion { [DataMember] public string Name { get; set; } [DataMember] public string Description { get; set; } [DataMember] public int? SortOrder { get; set; } } [CollectionDataContract(Namespace = UriElements.ServiceNamespace)] [XmlRoot("GeoRegions", Namespace = UriElements.ServiceNamespace)] public class GeoRegions : List<GeoRegion> { /// <summary> /// Empty collection /// </summary> public GeoRegions() { } /// <summary> /// Initialize from list /// </summary> /// <param name="regions"></param> public GeoRegions(List<GeoRegion> regions) : base(regions) { } } }
35.038462
87
0.595499
[ "MIT" ]
Andrean/azure-powershell
src/ServiceManagement/Services/Commands.Utilities/Websites/Services/GeoEntities/GeoRegion.cs
1,773
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { public GameObject player; private Vector3 offset; // Start is called before the first frame update private void Start() { offset = transform.position - player.transform.position; } // Update is called once per frame private void LateUpdate() { transform.position = player.transform.position + offset; } }
22.363636
64
0.695122
[ "MIT" ]
christopherromero/Roll-A-Ball
Assets/Scripts/CameraController.cs
494
C#
using System; using SOA.Base; namespace SOA.Common.Primitives { [Serializable] public class ULongGameEventListener : GameEventListener<ULongGameEvent, ULongUnityEvent, ulong> { } }
19.7
99
0.746193
[ "MIT" ]
Luxulicious/SOA
Package/Core/Runtime/Game Events/Primitives/ULongGameEventListener.cs
197
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLFacturacionSB { public class CategoriaBL { Contexto _contexto; public BindingList<Categoria> ListaCategorias { get; set; } public CategoriaBL() { _contexto = new Contexto(); ListaCategorias = new BindingList<Categoria>(); } public BindingList<Categoria> ObtenerCategorias() { _contexto.Categorias.Load(); ListaCategorias = _contexto.Categorias.Local.ToBindingList(); return ListaCategorias; } } public class Categoria { public int Id { get; set; } public string Descripcion { get; set; } } }
22.692308
74
0.6
[ "MIT" ]
StevenPerdomo/Facturacion-SB
FacturacionSB/BLSeguridad/CategoriaBL.cs
887
C#
namespace CFGToolkit.Lexer.Rules { public enum LexerRuleConsumeDecision { Consume = 0, Next = 1, } }
14.444444
40
0.584615
[ "MIT" ]
CFGToolkit/CFGToolkit.Lexer
CFGToolkit.Lexer/Rules/LexerRuleConsumeDecision.cs
132
C#
using Newtonsoft.Json; namespace Finnhub.ClientCore.Model { public class StockExchange { [JsonProperty("code")] public string Code { get; set; } [JsonProperty("name")] public string Name { get; set; } } }
19.307692
40
0.59761
[ "Apache-2.0" ]
dashwort/MarketWatch
Finnhub_client_core/Model/StockExchange.cs
253
C#
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { public enum FontTextureCase { Dynamic = -2, Unicode = -1, [InspectorName("ASCII default set")] ASCII = 0, ASCIIUpperCase = 1, ASCIILowerCase = 2, CustomSet = 3 } public enum FontRenderingMode { Smooth = 0, HintedSmooth = 1, HintedRaster = 2, OSDefault = 3, } public enum AscentCalculationMode { [InspectorName("Legacy version 2 mode (glyph bounding boxes)")] Legacy2x = 0, [InspectorName("Face ascender metric")] FaceAscender = 1, [InspectorName("Face bounding box metric")] FaceBoundingBox = 2 } [NativeHeader("Modules/TextRenderingEditor/TrueTypeFontImporter.h")] public sealed class TrueTypeFontImporter : AssetImporter { public extern int fontSize { get; set; } public extern bool includeFontData { get; set; } public extern AscentCalculationMode ascentCalculationMode { get; set; } public extern string customCharacters { get; set; } public extern int characterSpacing { get; set; } public extern int characterPadding { get; set; } public extern FontRenderingMode fontRenderingMode { get; set; } public extern bool shouldRoundAdvanceValue { get; set; } [NativeProperty("FontNameFromTTFData", false, TargetType.Function)] public extern string fontTTFName { get; } [NativeProperty("ForceTextureCase", false, TargetType.Function)] public extern FontTextureCase fontTextureCase { get; set; } [NativeProperty("MarshalledFontReferences", false, TargetType.Function)] public extern Font[] fontReferences { get; set; } [NativeProperty("MarshalledFontNames", false, TargetType.Function)] public extern string[] fontNames { get; set; } internal extern bool IsFormatSupported(); public extern Font GenerateEditableFont(string path); internal extern Font[] MarshalledLookupFallbackFontReferences(string[] names); internal Font[] LookupFallbackFontReferences(string[] names) { return MarshalledLookupFallbackFontReferences(names); } } }
35.940299
132
0.671512
[ "Unlicense" ]
HelloWindows/AccountBook
client/framework/UnityCsReference-master/Modules/TextRenderingEditor/TrueTypeFontImporter.bindings.cs
2,408
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerRUN : PlayerFSMState { public Transform marker; public float movespeed = 3.0f; void Start () { marker = GameObject.FindGameObjectWithTag("Marker").transform; } // Update is called once per frame void Update () { //transform.position = marker.position; transform.position = Vector3.MoveTowards( transform.position, marker.position, movespeed * Time.deltaTime); if(Vector3.Distance(transform.position,marker.position) < 0.01f) { // 다시 IDLE로 돌아간다. GetComponent<FSMManager>().SetState(PlayerState.IDLE); } } }
25.096774
73
0.602828
[ "MIT" ]
YooMinJUn/JJUNIV-Unity
Assets/Script/Player/PlayerRUN.cs
794
C#
#region Header /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (c) 2007-2008 James Nies and NArrange contributors. * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution. * * 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *<author>James Nies</author> *<contributor>Justin Dearing</contributor> *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #endregion Header namespace NArrange.Core.Configuration { using System.Threading; /// <summary> /// Binary operator expression. /// </summary> public class BinaryOperatorExpression : IConditionExpression { #region Fields /// <summary> /// Left condition expression. /// </summary> private readonly IConditionExpression _left; /// <summary> /// Operator type. /// </summary> private readonly BinaryExpressionOperator _operatorType; /// <summary> /// Right condition expression. /// </summary> private readonly IConditionExpression _right; #endregion Fields #region Constructors /// <summary> /// Creates a new operator expression. /// </summary> /// <param name="operatorType">Type of the operator.</param> /// <param name="left">The left expression.</param> /// <param name="right">The right expression.</param> public BinaryOperatorExpression( BinaryExpressionOperator operatorType, IConditionExpression left, IConditionExpression right) { _operatorType = operatorType; _left = left; _right = right; } #endregion Constructors #region Properties /// <summary> /// Gets the left expression. /// </summary> public IConditionExpression Left { get { return _left; } } /// <summary> /// Gets the expression operator. /// </summary> public BinaryExpressionOperator Operator { get { return _operatorType; } } /// <summary> /// Gets the right expression. /// </summary> public IConditionExpression Right { get { return _right; } } #endregion Properties #region Methods /// <summary> /// Gets the string representation of this expression. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { string operatorString = string.Empty; switch (_operatorType) { case BinaryExpressionOperator.Equal: operatorString = "=="; break; case BinaryExpressionOperator.Contains: operatorString = ":"; break; case BinaryExpressionOperator.And: operatorString = "And"; break; case BinaryExpressionOperator.Or: operatorString = "Or"; break; default: operatorString = EnumUtilities.ToString(_operatorType); break; } return string.Format( Thread.CurrentThread.CurrentCulture, "({0} {1} {2})", Left, operatorString, Right); } #endregion Methods } }
30.674699
78
0.568342
[ "Apache-2.0" ]
adgistics/Adgistics.Build
NArrange/src/Backup/NArrange.Core/Configuration/BinaryOperatorExpression.cs
5,092
C#
namespace BrightChain.Engine.Enumerations { public enum BrightTagType { Filename, UserAssigned, SystemAssigned, } }
15.3
42
0.620915
[ "Apache-2.0" ]
BrightChain/BrightChain
src/BrightChain.Engine/Enumerations/BrightTagType.cs
155
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Detour : LevelManager { public enum LevelType { eShortWall1, eShortWall2, eSemiT_Wall1, eSemiT_Wall2, e2SemiT_Wall1, eDeadZone1, e2DeadZone1, END, } public LevelType levelType; public GameObject wall; public GameObject tWall; public GameObject deadZone; public override void PlaceOtherObjs() { if (levelType == LevelType.eShortWall1) { ShortWall1(); levelTimes++; } else if (levelType == LevelType.eShortWall2) { ShortWall2(); levelTimes++; } else if (levelType == LevelType.eSemiT_Wall1) { SemiT_Wall1(); levelTimes++; } else if (levelType == LevelType.eSemiT_Wall2) { SemiT_Wall2(); levelTimes++; } else if (levelType == LevelType.e2SemiT_Wall1) { TwoSemiT_Wall1(); levelTimes++; } else if (levelType == LevelType.eDeadZone1) { DeadZone1(); levelTimes++; } else if (levelType == LevelType.e2DeadZone1) { TwoDeadZone1(); levelTimes++; } } public override int GetCurrentLevel() { return (int)levelType; } public override int GetLevelNumbers() { return (int)LevelType.END; } public override void SetCurrenLevel() { levelType++; } //只有一面矮牆壁 private void ShortWall1() { Vector3 wallSize = new Vector3(Random.Range(4, 10f), 0.3f, 0.2f); //agent Rigidbody rigidbody = agent.GetComponent<Rigidbody>(); rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; agent.transform.position = ChooseRandomRectPosition(transform.position, -9, 9, -9, -13) + new Vector3(0, 0.5f, 0); agent.transform.rotation = noRotation; //target food Rigidbody targetRigidbody = targetFood.GetComponent<Rigidbody>(); targetRigidbody.velocity = Vector3.zero; targetRigidbody.angularVelocity = Vector3.zero; targetFood.transform.position = ChooseRandomRectPosition(transform.position, -9f, 9f, 9f, 14f) + new Vector3(0, 0.5f, 0); //other //牆壁 GameObject wall1 = Instantiate(wall) as GameObject; objsList.Add(wall1); wall1.transform.localScale = wallSize; wall1.transform.position = targetFood.transform.position + new Vector3(-wallSize.x / 2, -0.5f, -2); } //矮牆壁左右再隨機生成一面矮牆 private void ShortWall2() { Vector3 wallSize = new Vector3(Random.Range(4, 10f), 0.3f, 0.2f); //agent Rigidbody rigidbody = agent.GetComponent<Rigidbody>(); rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; agent.transform.position = ChooseRandomRectPosition(transform.position, -9, 9, -9, -13) + new Vector3(0, 0.5f, 0); agent.transform.rotation = noRotation; //target food Rigidbody targetRigidbody = targetFood.GetComponent<Rigidbody>(); targetRigidbody.velocity = Vector3.zero; targetRigidbody.angularVelocity = Vector3.zero; targetFood.transform.position = ChooseRandomRectPosition(transform.position, -9f, 9f, 9f, 14f) + new Vector3(0, 0.5f, 0); //other //牆壁 GameObject wall1 = Instantiate(wall) as GameObject; objsList.Add(wall1); wall1.transform.localScale = wallSize; wall1.transform.position = targetFood.transform.position + new Vector3(-wallSize.x / 2, -0.5f, -2); //左或右牆壁 float[,] wall2Pos = { { 1f, 0 }, //左邊 { wallSize.x-1, 0} }; //右邊 GameObject wall2 = Instantiate(wall) as GameObject; objsList.Add(wall2); wall2.transform.localScale = wallSize; wall2.transform.position = ChooseRandomFixedPosition(wall1.transform.position, wall2Pos); wall2.transform.rotation = Quaternion.Euler(0, -90f, 0); } private void SemiT_Wall1() { Vector3 wallSize = new Vector3(Random.Range(4, 10f), 3f, 0.2f); //agent Rigidbody rigidbody = agent.GetComponent<Rigidbody>(); rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; agent.transform.position = ChooseRandomRectPosition(transform.position, -9, 9, -9, -13) + new Vector3(0, 0.5f, 0); agent.transform.rotation = noRotation; //target food Rigidbody targetRigidbody = targetFood.GetComponent<Rigidbody>(); targetRigidbody.velocity = Vector3.zero; targetRigidbody.angularVelocity = Vector3.zero; targetFood.transform.position = ChooseRandomRectPosition(transform.position, -9f, 9f, 9f, 14f) + new Vector3(0, 0.5f, 0); //other //牆壁 GameObject wall1 = Instantiate(tWall) as GameObject; objsList.Add(wall1); wall1.transform.localScale = wallSize; wall1.transform.position = targetFood.transform.position + new Vector3(-wallSize.x / 2, -0.5f, -2); } private void SemiT_Wall2() { Vector3 wallSize = new Vector3(Random.Range(4, 10f), 3f, 0.2f); //agent Rigidbody rigidbody = agent.GetComponent<Rigidbody>(); rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; agent.transform.position = ChooseRandomRectPosition(transform.position, -9, 9, -9, -13) + new Vector3(0, 0.5f, 0); agent.transform.rotation = noRotation; //target food Rigidbody targetRigidbody = targetFood.GetComponent<Rigidbody>(); targetRigidbody.velocity = Vector3.zero; targetRigidbody.angularVelocity = Vector3.zero; targetFood.transform.position = ChooseRandomRectPosition(transform.position, -9f, 9f, 9f, 14f) + new Vector3(0, 0.5f, 0); //other //牆壁 GameObject wall1 = Instantiate(tWall) as GameObject; objsList.Add(wall1); wall1.transform.localScale = wallSize; wall1.transform.position = targetFood.transform.position + new Vector3(-wallSize.x / 2, -0.5f, -2); //左或右牆壁 float[,] wall2Pos = { { 1f, 0 }, //左邊 { wallSize.x-1, 0} }; //右邊 GameObject wall2 = Instantiate(tWall) as GameObject; objsList.Add(wall2); wall2.transform.localScale = wallSize; wall2.transform.position = ChooseRandomFixedPosition(wall1.transform.position, wall2Pos); wall2.transform.rotation = Quaternion.Euler(0, -90f, 0); } private void TwoSemiT_Wall1() { Vector3 wallSize = new Vector3(Random.Range(4, 8f), 3f, 0.2f); //agent Rigidbody rigidbody = agent.GetComponent<Rigidbody>(); rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; agent.transform.position = ChooseRandomRectPosition(transform.position, 0f, 0f, -11, -15) + new Vector3(0, 0.5f, 0); agent.transform.rotation = noRotation; //target food Rigidbody targetRigidbody = targetFood.GetComponent<Rigidbody>(); targetRigidbody.velocity = Vector3.zero; targetRigidbody.angularVelocity = Vector3.zero; targetFood.transform.position = ChooseRandomRectPosition(transform.position, 0f, 0f, 7.5f, -10f) + new Vector3(0, 0.5f, 0); //other //左牆壁 GameObject wall1 = Instantiate(tWall) as GameObject; objsList.Add(wall1); wall1.transform.localScale = wallSize; wall1.transform.position = targetFood.transform.position + new Vector3(-0.3f, -0.5f, -1); wall1.transform.rotation = Quaternion.Euler(0, -135f, 0); //右牆壁 GameObject wall2 = Instantiate(tWall) as GameObject; objsList.Add(wall2); wall2.transform.localScale = wallSize; wall2.transform.position = wall1.transform.position + new Vector3(0.3f, 0, 0); wall2.transform.rotation = Quaternion.Euler(0, -45f, 0); } private void DeadZone1() { Vector3 deadZoneSize = new Vector3(Random.Range(4, 10f), 0.1f, Random.Range(0.2f, 1f)); //agent Rigidbody rigidbody = agent.GetComponent<Rigidbody>(); rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; agent.transform.position = ChooseRandomRectPosition(transform.position, -9, 9, -9, -13) + new Vector3(0, 0.5f, 0); agent.transform.rotation = noRotation; //target food Rigidbody targetRigidbody = targetFood.GetComponent<Rigidbody>(); targetRigidbody.velocity = Vector3.zero; targetRigidbody.angularVelocity = Vector3.zero; targetFood.transform.position = ChooseRandomRectPosition(transform.position, -9f, 9f, 9f, 14f) + new Vector3(0, 0.5f, 0); //other //Lava GameObject deadZone1 = Instantiate(deadZone) as GameObject; objsList.Add(deadZone1); deadZone1.transform.localScale = deadZoneSize; deadZone1.transform.position = targetFood.transform.position + new Vector3(-deadZoneSize.x / 2, -0.5f, -1.5f); } private void TwoDeadZone1() { Vector3 wallSize = new Vector3(Random.Range(4, 8f), 0.1f, Random.Range(0.2f, 1f)); //agent Rigidbody rigidbody = agent.GetComponent<Rigidbody>(); rigidbody.velocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; agent.transform.position = ChooseRandomRectPosition(transform.position, 0f, 0f, -11, -15) + new Vector3(0, 0.5f, 0); agent.transform.rotation = noRotation; //target food Rigidbody targetRigidbody = targetFood.GetComponent<Rigidbody>(); targetRigidbody.velocity = Vector3.zero; targetRigidbody.angularVelocity = Vector3.zero; targetFood.transform.position = ChooseRandomRectPosition(transform.position, 0f, 0f, 7.5f, -10f) + new Vector3(0, 0.5f, 0); //other //左牆壁 GameObject deadZone1 = Instantiate(deadZone) as GameObject; objsList.Add(deadZone1); deadZone1.transform.localScale = wallSize; deadZone1.transform.position = targetFood.transform.position + new Vector3(-0.3f, -0.5f, -1.5f); deadZone1.transform.rotation = Quaternion.Euler(0, -135f, 0); //右牆壁 GameObject deadZone2 = Instantiate(deadZone) as GameObject; objsList.Add(deadZone2); deadZone2.transform.localScale = wallSize; deadZone2.transform.position = targetFood.transform.position + new Vector3(0.3f, -0.5f, -2f); deadZone2.transform.rotation = Quaternion.Euler(0, -45f, 0); } }
40.354478
131
0.6319
[ "MIT" ]
linliu0624/AnimalAI_HPPO
Unity/Task/Detour.cs
10,935
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.Buffers; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using SixLabors.ImageSharp.Common.Helpers; using SixLabors.ImageSharp.Compression.Zlib; using SixLabors.ImageSharp.Formats.Png.Chunks; using SixLabors.ImageSharp.Formats.Png.Filters; using SixLabors.ImageSharp.IO; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Metadata; using SixLabors.ImageSharp.Metadata.Profiles.Exif; using SixLabors.ImageSharp.Metadata.Profiles.Xmp; using SixLabors.ImageSharp.PixelFormats; namespace SixLabors.ImageSharp.Formats.Png { /// <summary> /// Performs the png decoding operation. /// </summary> internal sealed class PngDecoderCore : IImageDecoderInternals { /// <summary> /// Reusable buffer. /// </summary> private readonly byte[] buffer = new byte[4]; /// <summary> /// Gets or sets a value indicating whether the metadata should be ignored when the image is being decoded. /// </summary> private readonly bool ignoreMetadata; /// <summary> /// Gets or sets a value indicating whether to read the IHDR and tRNS chunks only. /// </summary> private readonly bool colorMetadataOnly; /// <summary> /// Used the manage memory allocations. /// </summary> private readonly MemoryAllocator memoryAllocator; /// <summary> /// The stream to decode from. /// </summary> private BufferedReadStream currentStream; /// <summary> /// The png header. /// </summary> private PngHeader header; /// <summary> /// The number of bytes per pixel. /// </summary> private int bytesPerPixel; /// <summary> /// The number of bytes per sample. /// </summary> private int bytesPerSample; /// <summary> /// The number of bytes per scanline. /// </summary> private int bytesPerScanline; /// <summary> /// The palette containing color information for indexed png's. /// </summary> private byte[] palette; /// <summary> /// The palette containing alpha channel color information for indexed png's. /// </summary> private byte[] paletteAlpha; /// <summary> /// Previous scanline processed. /// </summary> private IMemoryOwner<byte> previousScanline; /// <summary> /// The current scanline that is being processed. /// </summary> private IMemoryOwner<byte> scanline; /// <summary> /// The index of the current scanline being processed. /// </summary> private int currentRow = Adam7.FirstRow[0]; /// <summary> /// The current number of bytes read in the current scanline. /// </summary> private int currentRowBytesRead; /// <summary> /// Gets or sets the png color type. /// </summary> private PngColorType pngColorType; /// <summary> /// The next chunk of data to return. /// </summary> private PngChunk? nextChunk; /// <summary> /// Initializes a new instance of the <see cref="PngDecoderCore"/> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="options">The decoder options.</param> public PngDecoderCore(Configuration configuration, IPngDecoderOptions options) { this.Configuration = configuration ?? Configuration.Default; this.memoryAllocator = this.Configuration.MemoryAllocator; this.ignoreMetadata = options.IgnoreMetadata; } internal PngDecoderCore(Configuration configuration, bool colorMetadataOnly) { this.Configuration = configuration ?? Configuration.Default; this.memoryAllocator = this.Configuration.MemoryAllocator; this.colorMetadataOnly = colorMetadataOnly; this.ignoreMetadata = true; } /// <inheritdoc/> public Configuration Configuration { get; } /// <summary> /// Gets the dimensions of the image. /// </summary> public Size Dimensions => new(this.header.Width, this.header.Height); /// <inheritdoc/> public Image<TPixel> Decode<TPixel>(BufferedReadStream stream, CancellationToken cancellationToken) where TPixel : unmanaged, IPixel<TPixel> { var metadata = new ImageMetadata(); PngMetadata pngMetadata = metadata.GetPngMetadata(); this.currentStream = stream; this.currentStream.Skip(8); Image<TPixel> image = null; try { while (this.TryReadChunk(out PngChunk chunk)) { try { switch (chunk.Type) { case PngChunkType.Header: this.ReadHeaderChunk(pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.Physical: this.ReadPhysicalChunk(metadata, chunk.Data.GetSpan()); break; case PngChunkType.Gamma: this.ReadGammaChunk(pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.Data: if (image is null) { this.InitializeImage(metadata, out image); } this.ReadScanlines(chunk, image.Frames.RootFrame, pngMetadata); break; case PngChunkType.Palette: byte[] pal = new byte[chunk.Length]; chunk.Data.GetSpan().CopyTo(pal); this.palette = pal; break; case PngChunkType.Transparency: byte[] alpha = new byte[chunk.Length]; chunk.Data.GetSpan().CopyTo(alpha); this.paletteAlpha = alpha; this.AssignTransparentMarkers(alpha, pngMetadata); break; case PngChunkType.Text: this.ReadTextChunk(metadata, pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.CompressedText: this.ReadCompressedTextChunk(metadata, pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.InternationalText: this.ReadInternationalTextChunk(metadata, chunk.Data.GetSpan()); break; case PngChunkType.Exif: if (!this.ignoreMetadata) { byte[] exifData = new byte[chunk.Length]; chunk.Data.GetSpan().CopyTo(exifData); this.MergeOrSetExifProfile(metadata, new ExifProfile(exifData), replaceExistingKeys: true); } break; case PngChunkType.End: goto EOF; case PngChunkType.ProprietaryApple: PngThrowHelper.ThrowInvalidChunkType("Proprietary Apple PNG detected! This PNG file is not conform to the specification and cannot be decoded."); break; } } finally { chunk.Data?.Dispose(); // Data is rented in ReadChunkData() } } EOF: if (image is null) { PngThrowHelper.ThrowNoData(); } return image; } finally { this.scanline?.Dispose(); this.previousScanline?.Dispose(); } } /// <inheritdoc/> public IImageInfo Identify(BufferedReadStream stream, CancellationToken cancellationToken) { var metadata = new ImageMetadata(); PngMetadata pngMetadata = metadata.GetPngMetadata(); this.currentStream = stream; this.currentStream.Skip(8); try { while (this.TryReadChunk(out PngChunk chunk)) { try { switch (chunk.Type) { case PngChunkType.Header: this.ReadHeaderChunk(pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.Physical: if (this.colorMetadataOnly) { this.SkipChunkDataAndCrc(chunk); break; } this.ReadPhysicalChunk(metadata, chunk.Data.GetSpan()); break; case PngChunkType.Gamma: if (this.colorMetadataOnly) { this.SkipChunkDataAndCrc(chunk); break; } this.ReadGammaChunk(pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.Data: // Spec says tRNS must be before IDAT so safe to exit. if (this.colorMetadataOnly) { goto EOF; } this.SkipChunkDataAndCrc(chunk); break; case PngChunkType.Transparency: byte[] alpha = new byte[chunk.Length]; chunk.Data.GetSpan().CopyTo(alpha); this.paletteAlpha = alpha; this.AssignTransparentMarkers(alpha, pngMetadata); if (this.colorMetadataOnly) { goto EOF; } break; case PngChunkType.Text: if (this.colorMetadataOnly) { this.SkipChunkDataAndCrc(chunk); break; } this.ReadTextChunk(metadata, pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.CompressedText: if (this.colorMetadataOnly) { this.SkipChunkDataAndCrc(chunk); break; } this.ReadCompressedTextChunk(metadata, pngMetadata, chunk.Data.GetSpan()); break; case PngChunkType.InternationalText: if (this.colorMetadataOnly) { this.SkipChunkDataAndCrc(chunk); break; } this.ReadInternationalTextChunk(metadata, chunk.Data.GetSpan()); break; case PngChunkType.Exif: if (this.colorMetadataOnly) { this.SkipChunkDataAndCrc(chunk); break; } if (!this.ignoreMetadata) { byte[] exifData = new byte[chunk.Length]; chunk.Data.GetSpan().CopyTo(exifData); this.MergeOrSetExifProfile(metadata, new ExifProfile(exifData), replaceExistingKeys: true); } break; case PngChunkType.End: goto EOF; default: if (this.colorMetadataOnly) { this.SkipChunkDataAndCrc(chunk); } break; } } finally { chunk.Data?.Dispose(); // Data is rented in ReadChunkData() } } EOF: if (this.header.Width == 0 && this.header.Height == 0) { PngThrowHelper.ThrowNoHeader(); } return new ImageInfo(new PixelTypeInfo(this.CalculateBitsPerPixel()), this.header.Width, this.header.Height, metadata); } finally { this.scanline?.Dispose(); this.previousScanline?.Dispose(); } } /// <summary> /// Reads the least significant bits from the byte pair with the others set to 0. /// </summary> /// <param name="buffer">The source buffer</param> /// <param name="offset">THe offset</param> /// <returns>The <see cref="int"/></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte ReadByteLittleEndian(ReadOnlySpan<byte> buffer, int offset) => (byte)(((buffer[offset] & 0xFF) << 16) | (buffer[offset + 1] & 0xFF)); /// <summary> /// Attempts to convert a byte array to a new array where each value in the original array is represented by the /// specified number of bits. /// </summary> /// <param name="source">The bytes to convert from. Cannot be empty.</param> /// <param name="bytesPerScanline">The number of bytes per scanline</param> /// <param name="bits">The number of bits per value.</param> /// <param name="buffer">The new array.</param> /// <returns>The resulting <see cref="ReadOnlySpan{Byte}"/> array.</returns> private bool TryScaleUpTo8BitArray(ReadOnlySpan<byte> source, int bytesPerScanline, int bits, out IMemoryOwner<byte> buffer) { if (bits >= 8) { buffer = null; return false; } buffer = this.memoryAllocator.Allocate<byte>(bytesPerScanline * 8 / bits, AllocationOptions.Clean); ref byte sourceRef = ref MemoryMarshal.GetReference(source); ref byte resultRef = ref buffer.GetReference(); int mask = 0xFF >> (8 - bits); int resultOffset = 0; for (int i = 0; i < bytesPerScanline; i++) { byte b = Unsafe.Add(ref sourceRef, i); for (int shift = 0; shift < 8; shift += bits) { int colorIndex = (b >> (8 - bits - shift)) & mask; Unsafe.Add(ref resultRef, resultOffset) = (byte)colorIndex; resultOffset++; } } return true; } /// <summary> /// Reads the data chunk containing physical dimension data. /// </summary> /// <param name="metadata">The metadata to read to.</param> /// <param name="data">The data containing physical data.</param> private void ReadPhysicalChunk(ImageMetadata metadata, ReadOnlySpan<byte> data) { var physicalChunk = PhysicalChunkData.Parse(data); metadata.ResolutionUnits = physicalChunk.UnitSpecifier == byte.MinValue ? PixelResolutionUnit.AspectRatio : PixelResolutionUnit.PixelsPerMeter; metadata.HorizontalResolution = physicalChunk.XAxisPixelsPerUnit; metadata.VerticalResolution = physicalChunk.YAxisPixelsPerUnit; } /// <summary> /// Reads the data chunk containing gamma data. /// </summary> /// <param name="pngMetadata">The metadata to read to.</param> /// <param name="data">The data containing physical data.</param> private void ReadGammaChunk(PngMetadata pngMetadata, ReadOnlySpan<byte> data) { if (data.Length < 4) { // Ignore invalid gamma chunks. return; } // For example, a gamma of 1/2.2 would be stored as 45455. // The value is encoded as a 4-byte unsigned integer, representing gamma times 100000. pngMetadata.Gamma = BinaryPrimitives.ReadUInt32BigEndian(data) * 1e-5F; } /// <summary> /// Initializes the image and various buffers needed for processing /// </summary> /// <typeparam name="TPixel">The type the pixels will be</typeparam> /// <param name="metadata">The metadata information for the image</param> /// <param name="image">The image that we will populate</param> private void InitializeImage<TPixel>(ImageMetadata metadata, out Image<TPixel> image) where TPixel : unmanaged, IPixel<TPixel> { image = Image.CreateUninitialized<TPixel>( this.Configuration, this.header.Width, this.header.Height, metadata); this.bytesPerPixel = this.CalculateBytesPerPixel(); this.bytesPerScanline = this.CalculateScanlineLength(this.header.Width) + 1; this.bytesPerSample = 1; if (this.header.BitDepth >= 8) { this.bytesPerSample = this.header.BitDepth / 8; } this.previousScanline = this.memoryAllocator.Allocate<byte>(this.bytesPerScanline, AllocationOptions.Clean); this.scanline = this.Configuration.MemoryAllocator.Allocate<byte>(this.bytesPerScanline, AllocationOptions.Clean); } /// <summary> /// Calculates the correct number of bits per pixel for the given color type. /// </summary> /// <returns>The <see cref="int"/></returns> private int CalculateBitsPerPixel() { switch (this.pngColorType) { case PngColorType.Grayscale: case PngColorType.Palette: return this.header.BitDepth; case PngColorType.GrayscaleWithAlpha: return this.header.BitDepth * 2; case PngColorType.Rgb: return this.header.BitDepth * 3; case PngColorType.RgbWithAlpha: return this.header.BitDepth * 4; default: PngThrowHelper.ThrowNotSupportedColor(); return -1; } } /// <summary> /// Calculates the correct number of bytes per pixel for the given color type. /// </summary> /// <returns>The <see cref="int"/></returns> private int CalculateBytesPerPixel() { switch (this.pngColorType) { case PngColorType.Grayscale: return this.header.BitDepth == 16 ? 2 : 1; case PngColorType.GrayscaleWithAlpha: return this.header.BitDepth == 16 ? 4 : 2; case PngColorType.Palette: return 1; case PngColorType.Rgb: return this.header.BitDepth == 16 ? 6 : 3; case PngColorType.RgbWithAlpha: default: return this.header.BitDepth == 16 ? 8 : 4; } } /// <summary> /// Calculates the scanline length. /// </summary> /// <param name="width">The width of the row.</param> /// <returns> /// The <see cref="int"/> representing the length. /// </returns> private int CalculateScanlineLength(int width) { int mod = this.header.BitDepth == 16 ? 16 : 8; int scanlineLength = width * this.header.BitDepth * this.bytesPerPixel; int amount = scanlineLength % mod; if (amount != 0) { scanlineLength += mod - amount; } return scanlineLength / mod; } /// <summary> /// Reads the scanlines within the image. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="chunk">The png chunk containing the compressed scanline data.</param> /// <param name="image"> The pixel data.</param> /// <param name="pngMetadata">The png metadata</param> private void ReadScanlines<TPixel>(PngChunk chunk, ImageFrame<TPixel> image, PngMetadata pngMetadata) where TPixel : unmanaged, IPixel<TPixel> { using var deframeStream = new ZlibInflateStream(this.currentStream, this.ReadNextDataChunk); deframeStream.AllocateNewBytes(chunk.Length, true); DeflateStream dataStream = deframeStream.CompressedStream; if (this.header.InterlaceMethod == PngInterlaceMode.Adam7) { this.DecodeInterlacedPixelData(dataStream, image, pngMetadata); } else { this.DecodePixelData(dataStream, image, pngMetadata); } } /// <summary> /// Decodes the raw pixel data row by row /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="compressedStream">The compressed pixel data stream.</param> /// <param name="image">The image to decode to.</param> /// <param name="pngMetadata">The png metadata</param> private void DecodePixelData<TPixel>(DeflateStream compressedStream, ImageFrame<TPixel> image, PngMetadata pngMetadata) where TPixel : unmanaged, IPixel<TPixel> { while (this.currentRow < this.header.Height) { Span<byte> scanlineSpan = this.scanline.GetSpan(); while (this.currentRowBytesRead < this.bytesPerScanline) { int bytesRead = compressedStream.Read(scanlineSpan, this.currentRowBytesRead, this.bytesPerScanline - this.currentRowBytesRead); if (bytesRead <= 0) { return; } this.currentRowBytesRead += bytesRead; } this.currentRowBytesRead = 0; switch ((FilterType)scanlineSpan[0]) { case FilterType.None: break; case FilterType.Sub: SubFilter.Decode(scanlineSpan, this.bytesPerPixel); break; case FilterType.Up: UpFilter.Decode(scanlineSpan, this.previousScanline.GetSpan()); break; case FilterType.Average: AverageFilter.Decode(scanlineSpan, this.previousScanline.GetSpan(), this.bytesPerPixel); break; case FilterType.Paeth: PaethFilter.Decode(scanlineSpan, this.previousScanline.GetSpan(), this.bytesPerPixel); break; default: PngThrowHelper.ThrowUnknownFilter(); break; } this.ProcessDefilteredScanline(scanlineSpan, image, pngMetadata); this.SwapScanlineBuffers(); this.currentRow++; } } /// <summary> /// Decodes the raw interlaced pixel data row by row /// <see href="https://github.com/juehv/DentalImageViewer/blob/8a1a4424b15d6cc453b5de3f273daf3ff5e3a90d/DentalImageViewer/lib/jiu-0.14.3/net/sourceforge/jiu/codecs/PNGCodec.java"/> /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="compressedStream">The compressed pixel data stream.</param> /// <param name="image">The current image.</param> /// <param name="pngMetadata">The png metadata.</param> private void DecodeInterlacedPixelData<TPixel>(DeflateStream compressedStream, ImageFrame<TPixel> image, PngMetadata pngMetadata) where TPixel : unmanaged, IPixel<TPixel> { int pass = 0; int width = this.header.Width; Buffer2D<TPixel> imageBuffer = image.PixelBuffer; while (true) { int numColumns = Adam7.ComputeColumns(width, pass); if (numColumns == 0) { pass++; // This pass contains no data; skip to next pass continue; } int bytesPerInterlaceScanline = this.CalculateScanlineLength(numColumns) + 1; while (this.currentRow < this.header.Height) { while (this.currentRowBytesRead < bytesPerInterlaceScanline) { int bytesRead = compressedStream.Read(this.scanline.GetSpan(), this.currentRowBytesRead, bytesPerInterlaceScanline - this.currentRowBytesRead); if (bytesRead <= 0) { return; } this.currentRowBytesRead += bytesRead; } this.currentRowBytesRead = 0; Span<byte> scanSpan = this.scanline.Slice(0, bytesPerInterlaceScanline); Span<byte> prevSpan = this.previousScanline.Slice(0, bytesPerInterlaceScanline); switch ((FilterType)scanSpan[0]) { case FilterType.None: break; case FilterType.Sub: SubFilter.Decode(scanSpan, this.bytesPerPixel); break; case FilterType.Up: UpFilter.Decode(scanSpan, prevSpan); break; case FilterType.Average: AverageFilter.Decode(scanSpan, prevSpan, this.bytesPerPixel); break; case FilterType.Paeth: PaethFilter.Decode(scanSpan, prevSpan, this.bytesPerPixel); break; default: PngThrowHelper.ThrowUnknownFilter(); break; } Span<TPixel> rowSpan = imageBuffer.DangerousGetRowSpan(this.currentRow); this.ProcessInterlacedDefilteredScanline(this.scanline.GetSpan(), rowSpan, pngMetadata, Adam7.FirstColumn[pass], Adam7.ColumnIncrement[pass]); this.SwapScanlineBuffers(); this.currentRow += Adam7.RowIncrement[pass]; } pass++; this.previousScanline.Clear(); if (pass < 7) { this.currentRow = Adam7.FirstRow[pass]; } else { pass = 0; break; } } } /// <summary> /// Processes the de-filtered scanline filling the image pixel data /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="defilteredScanline">The de-filtered scanline</param> /// <param name="pixels">The image</param> /// <param name="pngMetadata">The png metadata.</param> private void ProcessDefilteredScanline<TPixel>(ReadOnlySpan<byte> defilteredScanline, ImageFrame<TPixel> pixels, PngMetadata pngMetadata) where TPixel : unmanaged, IPixel<TPixel> { Span<TPixel> rowSpan = pixels.PixelBuffer.DangerousGetRowSpan(this.currentRow); // Trim the first marker byte from the buffer ReadOnlySpan<byte> trimmed = defilteredScanline.Slice(1, defilteredScanline.Length - 1); // Convert 1, 2, and 4 bit pixel data into the 8 bit equivalent. IMemoryOwner<byte> buffer = null; try { ReadOnlySpan<byte> scanlineSpan = this.TryScaleUpTo8BitArray( trimmed, this.bytesPerScanline - 1, this.header.BitDepth, out buffer) ? buffer.GetSpan() : trimmed; switch (this.pngColorType) { case PngColorType.Grayscale: PngScanlineProcessor.ProcessGrayscaleScanline( this.header, scanlineSpan, rowSpan, pngMetadata.HasTransparency, pngMetadata.TransparentL16.GetValueOrDefault(), pngMetadata.TransparentL8.GetValueOrDefault()); break; case PngColorType.GrayscaleWithAlpha: PngScanlineProcessor.ProcessGrayscaleWithAlphaScanline( this.header, scanlineSpan, rowSpan, this.bytesPerPixel, this.bytesPerSample); break; case PngColorType.Palette: PngScanlineProcessor.ProcessPaletteScanline( this.header, scanlineSpan, rowSpan, this.palette, this.paletteAlpha); break; case PngColorType.Rgb: PngScanlineProcessor.ProcessRgbScanline( this.Configuration, this.header, scanlineSpan, rowSpan, this.bytesPerPixel, this.bytesPerSample, pngMetadata.HasTransparency, pngMetadata.TransparentRgb48.GetValueOrDefault(), pngMetadata.TransparentRgb24.GetValueOrDefault()); break; case PngColorType.RgbWithAlpha: PngScanlineProcessor.ProcessRgbaScanline( this.Configuration, this.header, scanlineSpan, rowSpan, this.bytesPerPixel, this.bytesPerSample); break; } } finally { buffer?.Dispose(); } } /// <summary> /// Processes the interlaced de-filtered scanline filling the image pixel data /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="defilteredScanline">The de-filtered scanline</param> /// <param name="rowSpan">The current image row.</param> /// <param name="pngMetadata">The png metadata.</param> /// <param name="pixelOffset">The column start index. Always 0 for none interlaced images.</param> /// <param name="increment">The column increment. Always 1 for none interlaced images.</param> private void ProcessInterlacedDefilteredScanline<TPixel>(ReadOnlySpan<byte> defilteredScanline, Span<TPixel> rowSpan, PngMetadata pngMetadata, int pixelOffset = 0, int increment = 1) where TPixel : unmanaged, IPixel<TPixel> { // Trim the first marker byte from the buffer ReadOnlySpan<byte> trimmed = defilteredScanline.Slice(1, defilteredScanline.Length - 1); // Convert 1, 2, and 4 bit pixel data into the 8 bit equivalent. IMemoryOwner<byte> buffer = null; try { ReadOnlySpan<byte> scanlineSpan = this.TryScaleUpTo8BitArray( trimmed, this.bytesPerScanline, this.header.BitDepth, out buffer) ? buffer.GetSpan() : trimmed; switch (this.pngColorType) { case PngColorType.Grayscale: PngScanlineProcessor.ProcessInterlacedGrayscaleScanline( this.header, scanlineSpan, rowSpan, pixelOffset, increment, pngMetadata.HasTransparency, pngMetadata.TransparentL16.GetValueOrDefault(), pngMetadata.TransparentL8.GetValueOrDefault()); break; case PngColorType.GrayscaleWithAlpha: PngScanlineProcessor.ProcessInterlacedGrayscaleWithAlphaScanline( this.header, scanlineSpan, rowSpan, pixelOffset, increment, this.bytesPerPixel, this.bytesPerSample); break; case PngColorType.Palette: PngScanlineProcessor.ProcessInterlacedPaletteScanline( this.header, scanlineSpan, rowSpan, pixelOffset, increment, this.palette, this.paletteAlpha); break; case PngColorType.Rgb: PngScanlineProcessor.ProcessInterlacedRgbScanline( this.header, scanlineSpan, rowSpan, pixelOffset, increment, this.bytesPerPixel, this.bytesPerSample, pngMetadata.HasTransparency, pngMetadata.TransparentRgb48.GetValueOrDefault(), pngMetadata.TransparentRgb24.GetValueOrDefault()); break; case PngColorType.RgbWithAlpha: PngScanlineProcessor.ProcessInterlacedRgbaScanline( this.header, scanlineSpan, rowSpan, pixelOffset, increment, this.bytesPerPixel, this.bytesPerSample); break; } } finally { buffer?.Dispose(); } } /// <summary> /// Decodes and assigns marker colors that identify transparent pixels in non indexed images. /// </summary> /// <param name="alpha">The alpha tRNS array.</param> /// <param name="pngMetadata">The png metadata.</param> private void AssignTransparentMarkers(ReadOnlySpan<byte> alpha, PngMetadata pngMetadata) { if (this.pngColorType == PngColorType.Rgb) { if (alpha.Length >= 6) { if (this.header.BitDepth == 16) { ushort rc = BinaryPrimitives.ReadUInt16LittleEndian(alpha.Slice(0, 2)); ushort gc = BinaryPrimitives.ReadUInt16LittleEndian(alpha.Slice(2, 2)); ushort bc = BinaryPrimitives.ReadUInt16LittleEndian(alpha.Slice(4, 2)); pngMetadata.TransparentRgb48 = new Rgb48(rc, gc, bc); pngMetadata.HasTransparency = true; return; } byte r = ReadByteLittleEndian(alpha, 0); byte g = ReadByteLittleEndian(alpha, 2); byte b = ReadByteLittleEndian(alpha, 4); pngMetadata.TransparentRgb24 = new Rgb24(r, g, b); pngMetadata.HasTransparency = true; } } else if (this.pngColorType == PngColorType.Grayscale) { if (alpha.Length >= 2) { if (this.header.BitDepth == 16) { pngMetadata.TransparentL16 = new L16(BinaryPrimitives.ReadUInt16LittleEndian(alpha.Slice(0, 2))); } else { pngMetadata.TransparentL8 = new L8(ReadByteLittleEndian(alpha, 0)); } pngMetadata.HasTransparency = true; } } } /// <summary> /// Reads a header chunk from the data. /// </summary> /// <param name="pngMetadata">The png metadata.</param> /// <param name="data">The <see cref="T:ReadOnlySpan{byte}"/> containing data.</param> private void ReadHeaderChunk(PngMetadata pngMetadata, ReadOnlySpan<byte> data) { this.header = PngHeader.Parse(data); this.header.Validate(); pngMetadata.BitDepth = (PngBitDepth)this.header.BitDepth; pngMetadata.ColorType = this.header.ColorType; pngMetadata.InterlaceMethod = this.header.InterlaceMethod; this.pngColorType = this.header.ColorType; } /// <summary> /// Reads a text chunk containing image properties from the data. /// </summary> /// <param name="baseMetadata">The <see cref="ImageMetadata"/> object.</param> /// <param name="metadata">The metadata to decode to.</param> /// <param name="data">The <see cref="T:Span"/> containing the data.</param> private void ReadTextChunk(ImageMetadata baseMetadata, PngMetadata metadata, ReadOnlySpan<byte> data) { if (this.ignoreMetadata) { return; } int zeroIndex = data.IndexOf((byte)0); // Keywords are restricted to 1 to 79 bytes in length. if (zeroIndex is < PngConstants.MinTextKeywordLength or > PngConstants.MaxTextKeywordLength) { return; } ReadOnlySpan<byte> keywordBytes = data.Slice(0, zeroIndex); if (!this.TryReadTextKeyword(keywordBytes, out string name)) { return; } string value = PngConstants.Encoding.GetString(data.Slice(zeroIndex + 1)); if (!this.TryReadTextChunkMetadata(baseMetadata, name, value)) { metadata.TextData.Add(new PngTextData(name, value, string.Empty, string.Empty)); } } /// <summary> /// Reads the compressed text chunk. Contains a uncompressed keyword and a compressed text string. /// </summary> /// <param name="baseMetadata">The <see cref="ImageMetadata"/> object.</param> /// <param name="metadata">The metadata to decode to.</param> /// <param name="data">The <see cref="T:Span"/> containing the data.</param> private void ReadCompressedTextChunk(ImageMetadata baseMetadata, PngMetadata metadata, ReadOnlySpan<byte> data) { if (this.ignoreMetadata) { return; } int zeroIndex = data.IndexOf((byte)0); if (zeroIndex < PngConstants.MinTextKeywordLength || zeroIndex > PngConstants.MaxTextKeywordLength) { return; } byte compressionMethod = data[zeroIndex + 1]; if (compressionMethod != 0) { // Only compression method 0 is supported (zlib datastream with deflate compression). return; } ReadOnlySpan<byte> keywordBytes = data.Slice(0, zeroIndex); if (!this.TryReadTextKeyword(keywordBytes, out string name)) { return; } ReadOnlySpan<byte> compressedData = data.Slice(zeroIndex + 2); if (this.TryUncompressTextData(compressedData, PngConstants.Encoding, out string uncompressed) && !this.TryReadTextChunkMetadata(baseMetadata, name, uncompressed)) { metadata.TextData.Add(new PngTextData(name, uncompressed, string.Empty, string.Empty)); } } /// <summary> /// Checks if the given text chunk is actually storing parsable metadata. /// </summary> /// <param name="baseMetadata">The <see cref="ImageMetadata"/> object to store the parsed metadata in.</param> /// <param name="chunkName">The name of the text chunk.</param> /// <param name="chunkText">The contents of the text chunk.</param> /// <returns>True if metadata was successfully parsed from the text chunk. False if the /// text chunk was not identified as metadata, and should be stored in the metadata /// object unmodified.</returns> private bool TryReadTextChunkMetadata(ImageMetadata baseMetadata, string chunkName, string chunkText) { if (chunkName.Equals("Raw profile type exif", StringComparison.OrdinalIgnoreCase) && this.TryReadLegacyExifTextChunk(baseMetadata, chunkText)) { // Successfully parsed legacy exif data from text return true; } // TODO: "Raw profile type iptc", potentially others? // No special chunk data identified return false; } /// <summary> /// Reads exif data encoded into a text chunk with the name "raw profile type exif". /// This method was used by ImageMagick, exiftool, exiv2, digiKam, etc, before the /// 2017 update to png that allowed a true exif chunk. /// </summary> /// <param name="metadata">The <see cref="ImageMetadata"/> to store the decoded exif tags into.</param> /// <param name="data">The contents of the "raw profile type exif" text chunk.</param> private bool TryReadLegacyExifTextChunk(ImageMetadata metadata, string data) { ReadOnlySpan<char> dataSpan = data.AsSpan(); dataSpan = dataSpan.TrimStart(); if (!StringEqualsInsensitive(dataSpan.Slice(0, 4), "exif".AsSpan())) { // "exif" identifier is missing from the beginning of the text chunk return false; } // Skip to the data length dataSpan = dataSpan.Slice(4).TrimStart(); int dataLengthEnd = dataSpan.IndexOf('\n'); int dataLength = ParseInt32(dataSpan.Slice(0, dataSpan.IndexOf('\n'))); // Skip to the hex-encoded data dataSpan = dataSpan.Slice(dataLengthEnd).Trim(); // Sequence of bytes for the exif header ("Exif" ASCII and two zero bytes). // This doesn't actually allocate. ReadOnlySpan<byte> exifHeader = new byte[] { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 }; if (dataLength < exifHeader.Length) { // Not enough room for the required exif header, this data couldn't possibly be valid return false; } // Parse the hex-encoded data into the byte array we are going to hand off to ExifProfile byte[] exifBlob = new byte[dataLength - exifHeader.Length]; try { // Check for the presence of the exif header in the hex-encoded binary data byte[] tempExifBuf = exifBlob; if (exifBlob.Length < exifHeader.Length) { // Need to allocate a temporary array, this should be an extremely uncommon (TODO: impossible?) case tempExifBuf = new byte[exifHeader.Length]; } HexConverter.HexStringToBytes(dataSpan.Slice(0, exifHeader.Length * 2), tempExifBuf); if (!tempExifBuf.AsSpan().Slice(0, exifHeader.Length).SequenceEqual(exifHeader)) { // Exif header in the hex data is not valid return false; } // Skip over the exif header we just tested dataSpan = dataSpan.Slice(exifHeader.Length * 2); dataLength -= exifHeader.Length; // Load the hex-encoded data, one line at a time for (int i = 0; i < dataLength;) { ReadOnlySpan<char> lineSpan = dataSpan; int newlineIndex = dataSpan.IndexOf('\n'); if (newlineIndex != -1) { lineSpan = dataSpan.Slice(0, newlineIndex); } i += HexConverter.HexStringToBytes(lineSpan, exifBlob.AsSpan().Slice(i)); dataSpan = dataSpan.Slice(newlineIndex + 1); } } catch { return false; } this.MergeOrSetExifProfile(metadata, new ExifProfile(exifBlob), replaceExistingKeys: false); return true; } /// <summary> /// Compares two ReadOnlySpan&lt;char&gt;s in a case-insensitive method. /// This is only needed because older frameworks are missing the extension method. /// </summary> /// <param name="span1">The first <see cref="Span{T}"/> to compare.</param> /// <param name="span2">The second <see cref="Span{T}"/> to compare.</param> /// <returns>True if the spans were identical, false otherwise.</returns> private static bool StringEqualsInsensitive(ReadOnlySpan<char> span1, ReadOnlySpan<char> span2) { #pragma warning disable IDE0022 // Use expression body for methods #if NETSTANDARD2_1 || NETCOREAPP2_1_OR_GREATER return span1.Equals(span2, StringComparison.OrdinalIgnoreCase); #else return span1.ToString().Equals(span2.ToString(), StringComparison.OrdinalIgnoreCase); #endif #pragma warning restore IDE0022 // Use expression body for methods } /// <summary> /// int.Parse() a ReadOnlySpan&lt;char&gt;, with a fallback for older frameworks. /// </summary> /// <param name="span">The <see cref="int"/> to parse.</param> /// <returns>The parsed <see cref="int"/>.</returns> private static int ParseInt32(ReadOnlySpan<char> span) { #pragma warning disable IDE0022 // Use expression body for methods #if NETSTANDARD2_1 || NETCOREAPP2_1_OR_GREATER return int.Parse(span); #else return int.Parse(span.ToString()); #endif #pragma warning restore IDE0022 // Use expression body for methods } /// <summary> /// Sets the <see cref="ExifProfile"/> in <paramref name="metadata"/> to <paramref name="newProfile"/>, /// or copies exif tags if <paramref name="metadata"/> already contains an <see cref="ExifProfile"/>. /// </summary> /// <param name="metadata">The <see cref="ImageMetadata"/> to store the exif data in.</param> /// <param name="newProfile">The <see cref="ExifProfile"/> to copy exif tags from.</param> /// <param name="replaceExistingKeys">If <paramref name="metadata"/> already contains an <see cref="ExifProfile"/>, /// controls whether existing exif tags in <paramref name="metadata"/> will be overwritten with any conflicting /// tags from <paramref name="newProfile"/>.</param> private void MergeOrSetExifProfile(ImageMetadata metadata, ExifProfile newProfile, bool replaceExistingKeys) { if (metadata.ExifProfile is null) { // No exif metadata was loaded yet, so just assign it metadata.ExifProfile = newProfile; } else { // Try to merge existing keys with the ones from the new profile foreach (IExifValue newKey in newProfile.Values) { if (replaceExistingKeys || metadata.ExifProfile.GetValueInternal(newKey.Tag) is null) { metadata.ExifProfile.SetValueInternal(newKey.Tag, newKey.GetValue()); } } } } /// <summary> /// Reads a iTXt chunk, which contains international text data. It contains: /// - A uncompressed keyword. /// - Compression flag, indicating if a compression is used. /// - Compression method. /// - Language tag (optional). /// - A translated keyword (optional). /// - Text data, which is either compressed or uncompressed. /// </summary> /// <param name="metadata">The metadata to decode to.</param> /// <param name="data">The <see cref="T:Span"/> containing the data.</param> private void ReadInternationalTextChunk(ImageMetadata metadata, ReadOnlySpan<byte> data) { if (this.ignoreMetadata) { return; } PngMetadata pngMetadata = metadata.GetPngMetadata(); int zeroIndexKeyword = data.IndexOf((byte)0); if (zeroIndexKeyword < PngConstants.MinTextKeywordLength || zeroIndexKeyword > PngConstants.MaxTextKeywordLength) { return; } byte compressionFlag = data[zeroIndexKeyword + 1]; if (!(compressionFlag == 0 || compressionFlag == 1)) { return; } byte compressionMethod = data[zeroIndexKeyword + 2]; if (compressionMethod != 0) { // Only compression method 0 is supported (zlib datastream with deflate compression). return; } int langStartIdx = zeroIndexKeyword + 3; int languageLength = data.Slice(langStartIdx).IndexOf((byte)0); if (languageLength < 0) { return; } string language = PngConstants.LanguageEncoding.GetString(data.Slice(langStartIdx, languageLength)); int translatedKeywordStartIdx = langStartIdx + languageLength + 1; int translatedKeywordLength = data.Slice(translatedKeywordStartIdx).IndexOf((byte)0); string translatedKeyword = PngConstants.TranslatedEncoding.GetString(data.Slice(translatedKeywordStartIdx, translatedKeywordLength)); ReadOnlySpan<byte> keywordBytes = data.Slice(0, zeroIndexKeyword); if (!this.TryReadTextKeyword(keywordBytes, out string keyword)) { return; } int dataStartIdx = translatedKeywordStartIdx + translatedKeywordLength + 1; if (compressionFlag == 1) { ReadOnlySpan<byte> compressedData = data.Slice(dataStartIdx); if (this.TryUncompressTextData(compressedData, PngConstants.TranslatedEncoding, out string uncompressed)) { pngMetadata.TextData.Add(new PngTextData(keyword, uncompressed, language, translatedKeyword)); } } else if (this.IsXmpTextData(keywordBytes)) { XmpProfile xmpProfile = new XmpProfile(data.Slice(dataStartIdx).ToArray()); metadata.XmpProfile = xmpProfile; } else { string value = PngConstants.TranslatedEncoding.GetString(data.Slice(dataStartIdx)); pngMetadata.TextData.Add(new PngTextData(keyword, value, language, translatedKeyword)); } } /// <summary> /// Decompresses a byte array with zlib compressed text data. /// </summary> /// <param name="compressedData">Compressed text data bytes.</param> /// <param name="encoding">The string encoding to use.</param> /// <param name="value">The uncompressed value.</param> /// <returns>The <see cref="bool"/>.</returns> private bool TryUncompressTextData(ReadOnlySpan<byte> compressedData, Encoding encoding, out string value) { using (var memoryStream = new MemoryStream(compressedData.ToArray())) using (var bufferedStream = new BufferedReadStream(this.Configuration, memoryStream)) using (var inflateStream = new ZlibInflateStream(bufferedStream)) { if (!inflateStream.AllocateNewBytes(compressedData.Length, false)) { value = null; return false; } var uncompressedBytes = new List<byte>(); // Note: this uses a buffer which is only 4 bytes long to read the stream, maybe allocating a larger buffer makes sense here. int bytesRead = inflateStream.CompressedStream.Read(this.buffer, 0, this.buffer.Length); while (bytesRead != 0) { uncompressedBytes.AddRange(this.buffer.AsSpan(0, bytesRead).ToArray()); bytesRead = inflateStream.CompressedStream.Read(this.buffer, 0, this.buffer.Length); } value = encoding.GetString(uncompressedBytes.ToArray()); return true; } } /// <summary> /// Reads the next data chunk. /// </summary> /// <returns>Count of bytes in the next data chunk, or 0 if there are no more data chunks left.</returns> private int ReadNextDataChunk() { if (this.nextChunk != null) { return 0; } this.currentStream.Read(this.buffer, 0, 4); if (this.TryReadChunk(out PngChunk chunk)) { if (chunk.Type == PngChunkType.Data) { return chunk.Length; } this.nextChunk = chunk; } return 0; } /// <summary> /// Reads a chunk from the stream. /// </summary> /// <param name="chunk">The image format chunk.</param> /// <returns> /// The <see cref="PngChunk"/>. /// </returns> private bool TryReadChunk(out PngChunk chunk) { if (this.nextChunk != null) { chunk = this.nextChunk.Value; this.nextChunk = null; return true; } if (!this.TryReadChunkLength(out int length)) { chunk = default; // IEND return false; } while (length < 0 || length > (this.currentStream.Length - this.currentStream.Position)) { // Not a valid chunk so try again until we reach a known chunk. if (!this.TryReadChunkLength(out length)) { chunk = default; return false; } } PngChunkType type = this.ReadChunkType(); // If we're reading color metadata only we're only interested in the IHDR and tRNS chunks. // We can skip all other chunk data in the stream for better performance. if (this.colorMetadataOnly && type != PngChunkType.Header && type != PngChunkType.Transparency) { chunk = new PngChunk(length, type); return true; } long pos = this.currentStream.Position; chunk = new PngChunk( length: length, type: type, data: this.ReadChunkData(length)); this.ValidateChunk(chunk); // Restore the stream position for IDAT chunks, because it will be decoded later and // was only read to verifying the CRC is correct. if (type == PngChunkType.Data) { this.currentStream.Position = pos; } return true; } /// <summary> /// Validates the png chunk. /// </summary> /// <param name="chunk">The <see cref="PngChunk"/>.</param> private void ValidateChunk(in PngChunk chunk) { uint inputCrc = this.ReadChunkCrc(); if (chunk.IsCritical) { Span<byte> chunkType = stackalloc byte[4]; BinaryPrimitives.WriteUInt32BigEndian(chunkType, (uint)chunk.Type); uint validCrc = Crc32.Calculate(chunkType); validCrc = Crc32.Calculate(validCrc, chunk.Data.GetSpan()); if (validCrc != inputCrc) { string chunkTypeName = Encoding.ASCII.GetString(chunkType); PngThrowHelper.ThrowInvalidChunkCrc(chunkTypeName); } } } /// <summary> /// Reads the cycle redundancy chunk from the data. /// </summary> [MethodImpl(InliningOptions.ShortMethod)] private uint ReadChunkCrc() { uint crc = 0; if (this.currentStream.Read(this.buffer, 0, 4) == 4) { crc = BinaryPrimitives.ReadUInt32BigEndian(this.buffer); } return crc; } /// <summary> /// Skips the chunk data and the cycle redundancy chunk read from the data. /// </summary> /// <param name="chunk">The image format chunk.</param> [MethodImpl(InliningOptions.ShortMethod)] private void SkipChunkDataAndCrc(in PngChunk chunk) { this.currentStream.Skip(chunk.Length); this.currentStream.Skip(4); } /// <summary> /// Reads the chunk data from the stream. /// </summary> /// <param name="length">The length of the chunk data to read.</param> [MethodImpl(InliningOptions.ShortMethod)] private IMemoryOwner<byte> ReadChunkData(int length) { // We rent the buffer here to return it afterwards in Decode() IMemoryOwner<byte> buffer = this.Configuration.MemoryAllocator.Allocate<byte>(length, AllocationOptions.Clean); this.currentStream.Read(buffer.GetSpan(), 0, length); return buffer; } /// <summary> /// Identifies the chunk type from the chunk. /// </summary> /// <exception cref="ImageFormatException"> /// Thrown if the input stream is not valid. /// </exception> [MethodImpl(InliningOptions.ShortMethod)] private PngChunkType ReadChunkType() { if (this.currentStream.Read(this.buffer, 0, 4) == 4) { return (PngChunkType)BinaryPrimitives.ReadUInt32BigEndian(this.buffer); } else { PngThrowHelper.ThrowInvalidChunkType(); // The IDE cannot detect the throw here. return default; } } /// <summary> /// Attempts to read the length of the next chunk. /// </summary> /// <returns> /// Whether the length was read. /// </returns> [MethodImpl(InliningOptions.ShortMethod)] private bool TryReadChunkLength(out int result) { if (this.currentStream.Read(this.buffer, 0, 4) == 4) { result = BinaryPrimitives.ReadInt32BigEndian(this.buffer); return true; } result = default; return false; } /// <summary> /// Tries to reads a text chunk keyword, which have some restrictions to be valid: /// Keywords shall contain only printable Latin-1 characters and should not have leading or trailing whitespace. /// See: https://www.w3.org/TR/PNG/#11zTXt /// </summary> /// <param name="keywordBytes">The keyword bytes.</param> /// <param name="name">The name.</param> /// <returns>True, if the keyword could be read and is valid.</returns> private bool TryReadTextKeyword(ReadOnlySpan<byte> keywordBytes, out string name) { name = string.Empty; // Keywords shall contain only printable Latin-1. foreach (byte c in keywordBytes) { if (!((c >= 32 && c <= 126) || (c >= 161 && c <= 255))) { return false; } } // Keywords should not be empty or have leading or trailing whitespace. name = PngConstants.Encoding.GetString(keywordBytes); if (string.IsNullOrWhiteSpace(name) || name.StartsWith(" ") || name.EndsWith(" ")) { return false; } return true; } private bool IsXmpTextData(ReadOnlySpan<byte> keywordBytes) => keywordBytes.SequenceEqual(PngConstants.XmpKeyword); private void SwapScanlineBuffers() { IMemoryOwner<byte> temp = this.previousScanline; this.previousScanline = this.scanline; this.scanline = temp; } } }
40.350789
190
0.512806
[ "Apache-2.0" ]
BananchickPasha/ImageSharp
src/ImageSharp/Formats/Png/PngDecoderCore.cs
63,956
C#
using Xunit; namespace Jint.Tests.Ecma { public class Test_12_10_1 : EcmaTest { [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorStrictFunction() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-1-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorEvalWhereTheContainerFunctionIsStrict() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-10-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void StrictModeSyntaxerrorIsThrownWhenUsingWithstatementInStrictModeCode() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-11-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void StrictModeSyntaxerrorIsThrownWhenUsingWithStatement() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-11gs.js", true); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorStrictEval() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-12-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void StrictModeSyntaxerrorIsnTThrownWhenWithstatementBodyIsInStrictModeCode() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-13-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void StrictModeSyntaxerrorIsThrownWhenTheGetterOfALiteralObjectUtilizesWithstatement() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-14-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void StrictModeSyntaxerrorIsThrownWhenTheRhsOfADotPropertyAssignmentUtilizesWithstatement() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-15-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void StrictModeSyntaxerrorIsThrownWhenTheRhsOfAnObjectIndexerAssignmentUtilizesWithstatement() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-16-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorNestedFunctionWhereContainerIsStrict() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-2-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorNestedStrictFunction() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-3-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorStrictFunction2() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-4-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementAllowedInNestedFunctionEvenIfItsContainerFunctionIsStrict() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-5-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorFunctionExpressionWhereTheContainerFunctionIsDirectlyEvaledFromStrictCode() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-7-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorFunctionExpressionWhereTheContainerFunctionIsStrict() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-8-s.js", false); } [Fact] [Trait("Category", "12.10.1")] public void WithStatementInStrictModeThrowsSyntaxerrorStrictFunctionExpression() { RunTest(@"TestCases/ch12/12.10/12.10.1/12.10.1-9-s.js", false); } } }
32.057377
137
0.623114
[ "BSD-2-Clause" ]
B-Esmaili/jint
Jint.Tests.Ecma/Ecma/12.10.1.cs
3,911
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class CharacterMicrogamePool : MonoBehaviour { public bool shuffleMicrogames = true; public MicrogameBatch[] microgameBatches; public int[] speedUpTimes; public Stage.Microgame bossMicrogame; public bool skipBossMicrogame; [System.Serializable] public struct MicrogameBatch { public int pick; public Stage.Microgame[] pool; } void Update() { if (Application.isPlaying) return; for (int i = 0; i < microgameBatches.Length; i++) { microgameBatches[i].pick = Mathf.Min(microgameBatches[i].pool.Length, microgameBatches[i].pick); } } }
22.151515
108
0.692202
[ "MIT" ]
Anxeal/NitoriWare
Assets/Scripts/Stage/CharacterMicrogamePool.cs
733
C#
using System; using XSocketsClient.Common.Event.Arguments; using XSocketsClient.Common.Event.Interface; using XSocketsClient.Common.Interfaces; namespace XSocketsClient.Helpers { public static partial class XSocketHelper { /// <summary> /// If possible use the extension-method ToTextArgs for the controller instead /// </summary> /// <param name="client"></param> /// <param name="obj"></param> /// <param name="eventname"></param> /// <returns></returns> public static ITextArgs AsTextArgs(this IXSocketClient client, object obj, string eventname) { return new TextArgs { @event = eventname.ToLower(), data = client.Serializer.SerializeToString(obj) }; } /// <summary> /// Builds a ITextArgs object from a JSON string and a event name /// </summary> /// <param name="json"></param> /// <param name="eventname"></param> /// <returns></returns> public static ITextArgs AsTextArgsForJson(this string json, string eventname) { return new TextArgs { @event = eventname.ToLower(), data = json }; } /// <summary> /// Use when sending binary data /// </summary> /// <param name="obj"></param> /// <param name="eventname"></param> /// <returns></returns> public static IBinaryArgs AsBinaryArgs(this byte[] obj, string eventname) { return new BinaryArgs { @event = eventname.ToLower(), data = obj }; } /// <summary> /// Deserialize JSON to a strongly typed object /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T Deserialize<T>(this IXSocketClient client, string json) { return client.Serializer.DeserializeFromString<T>(json); } /// <summary> /// If possible use the extension-method ToTextArgs for the controller instead /// </summary> /// <param name="client"></param> /// <param name="obj"></param> /// <returns></returns> public static string Serialize(this IXSocketClient client, object obj) { return client.Serializer.SerializeToString(obj); } /// <summary> /// Deserialize JSON to a strongly typed object. /// </summary> /// <param name="client"></param> /// <param name="targetType"></param> /// <param name="json"></param> /// <returns></returns> internal static object GetObject(this IXSocketClient client, Type targetType, string json) { return client.Serializer.DeserializeFromString(json, targetType); } } }
36.448718
114
0.5758
[ "MIT" ]
clairernovotny/XSocketsClient
src/XSocketsClient/XSocketsClient/Helpers/Transformation.cs
2,845
C#
using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks.Attributes; using FlubuCore.Tasks.FileSystem; using FlubuCore.Tasks.Process; namespace FlubuCore.Tasks.NetCore { public class DotnetCleanTask : ExecuteDotnetTaskBase<DotnetCleanTask> { private string _description; private bool _cleanBuildDir; private bool _cleanOutputDir; private string _projectName; private List<(string path, bool recreate)> _directoriesToClean = new List<(string path, bool recreate)>(); public DotnetCleanTask() : base(StandardDotnetCommands.Clean) { } protected override string Description { get { if (string.IsNullOrEmpty(_description)) { return $"Executes dotnet command Clean"; } return _description; } set { _description = value; } } /// <summary> /// The MSBuild project file to publish. If a project file is not specified, MSBuild searches the current working directory for a file that has a file extension that ends in `proj` and uses that file. /// </summary> /// <param name="projectName"></param> /// <returns></returns> public DotnetCleanTask Project(string projectName) { _projectName = projectName; return this; } /// <summary> /// Clean a specific framework. /// </summary> /// <param name="framework"></param> /// <returns></returns> [ArgKey("--framework", "-f")] public DotnetCleanTask Framework(string framework) { WithArgumentsKeyFromAttribute(framework); return this; } /// <summary> /// Clean a specific framework. /// </summary> /// <param name="framework"></param> /// <returns></returns> [ArgKey("--framework", "-f")] public DotnetCleanTask Framework(Framework framework) { WithArgumentsKeyFromAttribute(framework.ToString()); return this; } /// <summary> /// Clean a specific configuration. /// </summary> /// <param name="configuration"></param> /// <returns></returns> [ArgKey("--configuration", "-c")] public DotnetCleanTask Configuration(string configuration) { WithArgumentsKeyFromAttribute(configuration); return this; } /// <summary> /// Clean a specific configuration. /// </summary> /// <param name="configuration"></param> /// <returns></returns> [ArgKey("--configuration", "-c")] public DotnetCleanTask Configuration(Configuration configuration) { WithArgumentsKeyFromAttribute(configuration.ToString()); return this; } /// <summary> /// Set the verbosity level of the command. /// </summary> /// <param name="verbosity"></param> /// <returns></returns> [ArgKey("--verbosity", "-v")] public DotnetCleanTask Verbosity(VerbosityOptions verbosity) { WithArgumentsKeyFromAttribute(verbosity.ToString().ToLower()); return this; } /// <summary> /// Task deletes added directory. /// </summary> /// <param name="directory">The directory do delete</param> /// <param name="recreate">If <c>true</c> directory is recreated. Otherwise deleted.</param> /// <returns></returns> public DotnetCleanTask AddDirectoryToClean(string directory, bool recreate) { _directoriesToClean.Add((directory, recreate)); return this; } /// <summary> /// If set output directory specified in <see cref="BuildProps.OutputDir"/> is deleted and recreated. /// </summary> /// <returns></returns> public DotnetCleanTask CleanOutputDir() { _cleanOutputDir = true; return this; } /// <summary> /// If set Build directory specified in <see cref="BuildProps.BuildDir"/> is deleted and recreated. /// </summary> /// <returns></returns> public DotnetCleanTask CleanBuildDir() { _cleanBuildDir = true; return this; } protected override void BeforeExecute(ITaskContextInternal context, IRunProgramTask runProgramTask) { var args = GetArguments(); if (string.IsNullOrEmpty(_projectName)) { if (args.Count == 0 || args[0].StartsWith("-")) { var solustionFileName = context.Properties.Get<string>(BuildProps.SolutionFileName, null); if (solustionFileName != null) { InsertArgument(0, solustionFileName); } } } else { InsertArgument(0, _projectName); } if (!args.Exists(x => x == "-c" || x == "--configuration")) { var configuration = context.Properties.Get<string>(BuildProps.BuildConfiguration, null); if (configuration != null) { Configuration(configuration); } } string buildDir = context.Properties.Get<string>(DotNetBuildProps.BuildDir, null); if (!string.IsNullOrEmpty(buildDir) && _cleanBuildDir) { CreateDirectoryTask createDirectoryTask = new CreateDirectoryTask(buildDir, true); createDirectoryTask.Execute(context); } string outputDir = context.Properties.Get<string>(DotNetBuildProps.OutputDir, null); if (!string.IsNullOrEmpty(outputDir) && _cleanOutputDir) { CreateDirectoryTask createDirectoryTask = new CreateDirectoryTask(outputDir, true); createDirectoryTask.Execute(context); } foreach (var dir in _directoriesToClean) { if (dir.recreate) { CreateDirectoryTask createDirectoryTask = new CreateDirectoryTask(dir.path, true); createDirectoryTask.Execute(context); } else { DeleteDirectoryTask task = new DeleteDirectoryTask(dir.path, false); task.Execute(context); } } base.BeforeExecute(context, runProgramTask); } } }
33.179612
208
0.546452
[ "MIT" ]
Rwing/FlubuCore
src/FlubuCore/Tasks/NetCore/DotnetCleanTask.cs
6,837
C#
using Amazon.Runtime.Internal.Util; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Serilog; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GeolettApi.Web.Configuration { public static class SerilogConfiguration { public static void ConfigureSerilog(IConfigurationRoot configuration) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Destructure.ByTransforming<RequestMetrics>(JsonConvert.SerializeObject) .CreateLogger(); } } }
27.869565
88
0.709828
[ "MIT" ]
kartverket/GeolettAp
src/GeolettApi.Web/Configuration/SerilogConfiguration.cs
643
C#
namespace AgileObjects.AgileMapper.UnitTests.Orms.Configuration { using System.Threading.Tasks; using Common; using Infrastructure; using TestClasses; public abstract class WhenConfiguringConstructorDataSources<TOrmContext> : OrmTestClassBase<TOrmContext> where TOrmContext : ITestDbContext, new() { protected WhenConfiguringConstructorDataSources(ITestContext<TOrmContext> context) : base(context) { } #region Project -> Ctor Parameter by Type protected Task RunShouldApplyAConfiguredConstantByParameterType() => RunTest(DoShouldApplyAConfiguredConstantByParameterType); protected Task RunShouldErrorApplyingAConfiguredConstantByParameterType() => RunTestAndExpectThrow(DoShouldApplyAConfiguredConstantByParameterType); private static async Task DoShouldApplyAConfiguredConstantByParameterType(TOrmContext context, IMapper mapper) { var product = new Product { Name = "Prod.One" }; await context.Products.Add(product); await context.SaveChanges(); mapper.WhenMapping .From<Product>() .ProjectedTo<ProductStruct>() .Map("Bananas!") .ToCtor<string>(); var productDto = context .Products .ProjectUsing(mapper).To<ProductStruct>() .ShouldHaveSingleItem(); productDto.ProductId.ShouldBe(product.ProductId); productDto.Name.ShouldBe("Bananas!"); } #endregion #region Project -> Ctor Parameter by Name protected Task RunShouldApplyAConfiguredExpressionByParameterName() => RunTest(DoShouldApplyAConfiguredExpressionByParameterName); protected Task RunShouldErrorApplyingAConfiguredExpressionByParameterName() => RunTestAndExpectThrow(DoShouldApplyAConfiguredExpressionByParameterName); private static async Task DoShouldApplyAConfiguredExpressionByParameterName(TOrmContext context, IMapper mapper) { var product = new Product { Name = "Prod.One" }; await context.Products.Add(product); await context.SaveChanges(); mapper.WhenMapping .From<Product>() .ProjectedTo<ProductStruct>() .Map(p => "2 * 3 = " + (2 * 3)) .ToCtor("name"); var productDto = context .Products .ProjectUsing(mapper).To<ProductStruct>() .ShouldHaveSingleItem(); productDto.ProductId.ShouldBe(product.ProductId); productDto.Name.ShouldBe("2 * 3 = 6"); } #endregion } }
34.7
120
0.631484
[ "MIT" ]
WeiiWang/AgileMapper
AgileMapper.UnitTests.Orms/Configuration/WhenConfiguringConstructorDataSources.cs
2,778
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Management.Internal.Resources.Models; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.Management.Internal.Resources { public static partial class ResourceManagementClientExtensions { /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IResourceManagementClient. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetLongRunningOperationStatus(this IResourceManagementClient operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IResourceManagementClient)s).GetLongRunningOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IResourceManagementClient. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(this IResourceManagementClient operations, string operationStatusLink) { return operations.GetLongRunningOperationStatusAsync(operationStatusLink, CancellationToken.None); } } }
44.532468
163
0.666083
[ "MIT" ]
LaudateCorpus1/azure-powershell
src/ResourceManager/Common/Commands.ResourceManager.Common/Generated/ResourceManagementClientExtensions.cs
3,353
C#
//! \file ImageEDT.cs //! \date Sun Feb 15 10:13:07 2015 //! \brief Active Soft image format implementation. // // Copyright (C) 2015 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.AdPack { internal class EdtMetaData : ImageMetaData { public uint CompSize; public uint ExtraSize; } internal class Ed8MetaData : ImageMetaData { public int PaletteSize; public uint CompSize; } internal class BitReader { int m_bits = 1; protected void ResetBits () { m_bits = 1; } protected int NextBit (Stream input) { if (1 == m_bits) { m_bits = input.ReadByte(); if (-1 == m_bits) throw new InvalidFormatException ("Unexpected end of input"); m_bits |= 0x100; } int bit = m_bits & 1; m_bits >>= 1; return bit; } protected int ReadBits (int data, int count, Stream input) { while (count > 0) { data = (data << 1) | NextBit (input); --count; } return data; } protected int CountBits (Stream input) { int bit = 1, count = 0; while (count < 0x20 && 1 == bit) { ++count; bit = NextBit (input); } if (--count != 0) return ReadBits (1, count, input); else return 1; } } [Export(typeof(ImageFormat))] public class EdtFormat : ImageFormat { public override string Tag { get { return "EDT"; } } public override string Description { get { return "Active Soft RGB image format"; } } public override uint Signature { get { return 0x5552542eu; } } // '.TRU' public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("EdtFormat.Write not implemented"); } public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (0x22); if (!header.AsciiEqual (".TRUE\x8d\x5d\x8c\xcb\x00")) return null; uint width = header.ToUInt16 (0x0e); uint height = header.ToUInt16 (0x10); uint comp_size = header.ToUInt32 (0x1a); uint extra_size = header.ToUInt32 (0x1e); if (extra_size % 3 != 0 || 0 == extra_size) return null; return new EdtMetaData { Width = width, Height = height, BPP = 24, CompSize = comp_size, ExtraSize = extra_size, }; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { var meta = (EdtMetaData)info; stream.Position = 0x22; using (var reader = new Reader (stream.AsStream, meta)) { reader.Unpack(); return ImageData.Create (meta, PixelFormats.Bgr24, null, reader.Data, (int)meta.Width*3); } } internal sealed class Reader : BitReader, IDisposable { MemoryStream m_packed; MemoryStream m_extra; byte[] m_output; int[] ShiftTable = new int[32]; public byte[] Data { get { return m_output; } } public Reader (Stream file, EdtMetaData info) { byte[] packed = new byte[info.CompSize]; file.Read (packed, 0, packed.Length); m_packed = new MemoryStream (packed, false); byte[] extra = new byte[info.ExtraSize]; file.Read (extra, 0, extra.Length); m_extra = new MemoryStream (extra, false); m_output = new byte[info.Width*info.Height*3]; int stride = (int)info.Width * 3; int offset = stride * -4; int i = 0; while (offset != 0) { int shift = offset - 9; for (int j = 0; j < 7; ++j) { ShiftTable[i++] = shift; shift += 3; } offset += stride; } offset = -12; while (offset != 0) { ShiftTable[i++] = offset; offset += 3; } } public void Unpack () { int dst = 0; if (3 != m_extra.Read (m_output, dst, 3)) throw new InvalidFormatException ("Unexpected end of input"); dst += 3; while (dst < m_output.Length) { if (1 == NextBit (m_packed)) { if (0 == NextBit (m_packed)) { int offset = ShiftTable[ReadBits (0, 5, m_packed)]; if (dst < -offset) return; int count = CountBits (m_packed) * 3; Binary.CopyOverlapped (m_output, dst + offset, dst, count); dst += count; } else { int offset = -3; if (1 == NextBit (m_packed)) { offset = ShiftTable[(0x11191718 >> ((ReadBits (0, 2, m_packed) << 3)) & 0xFF)]; if (dst < -offset) return; } for (int i = 0; i < 3; ++i) { int b = m_output[dst+offset]; if (b < 2) b = 2; else if (b > 0xfd) b = 0xfd; if (1 == NextBit (m_packed)) { int b2 = 1 + NextBit (m_packed); if (0 == NextBit (m_packed)) b -= b2; else b += b2; } m_output[dst++] = (byte)b; } } } else { if (3 != m_extra.Read (m_output, dst, 3)) throw new InvalidFormatException ("Unexpected end of input"); dst += 3; } } } #region IDisposable Members bool disposed = false; public void Dispose () { if (!disposed) { m_packed.Dispose(); m_extra.Dispose(); disposed = true; } GC.SuppressFinalize (this); } #endregion } } [Export(typeof(ImageFormat))] public class Ed8Format : ImageFormat { public override string Tag { get { return "ED8"; } } public override string Description { get { return "Active Soft indexed image format"; } } public override uint Signature { get { return 0x6942382eu; } } // '.8Bi' public Ed8Format () { Extensions = new string[] { "ed8", "sal" }; } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("Ed8Format.Write not implemented"); } public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (0x1A); if (!header.AsciiEqual (".8Bit\x8d\x5d\x8c\xcb\x00")) return null; uint width = header.ToUInt16 (0x0e); uint height = header.ToUInt16 (0x10); int palette_size = header.ToInt32 (0x12); uint comp_size = header.ToUInt32 (0x16); if (palette_size > 0x100) return null; return new Ed8MetaData { Width = width, Height = height, BPP = 8, PaletteSize = palette_size, CompSize = comp_size, }; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { var meta = (Ed8MetaData)info; var reader = new Reader (stream.AsStream, meta); reader.Unpack(); var palette = new BitmapPalette (reader.Palette); return ImageData.Create (info, PixelFormats.Indexed8, palette, reader.Data, (int)info.Width); } internal class Reader : BitReader { Stream m_input; byte[] m_data; Color[] m_palette; int m_width; public Color[] Palette { get { return m_palette; } } public byte[] Data { get { return m_data; } } private static readonly sbyte[] ShiftTable = new sbyte[] { // (-1,0) (0,1) (-2,0) (-1,1) (1,1) (0,2) (-2,1) (2,1) -0x10, 0x01, -0x20, -0x0F, 0x11, 0x02, -0x1F, 0x21, // (-2,2) (-1,2) (1,2) (2,2) (0,3) (-1,3) -0x1E, -0x0E, 0x12, 0x22, 0x03, -0x0D }; public Reader (Stream file, Ed8MetaData info) { m_width = (int)info.Width; m_input = file; m_data = new byte[info.Width * info.Height]; } public void Unpack () { m_input.Position = 0x1A; m_palette = ReadColorMap (m_input, 0x100, PaletteFormat.Bgr); int data_pos = 0; while (data_pos < m_data.Length) { m_data[data_pos++] = (byte)ReadBits (0, 8, m_input); if (m_data.Length == data_pos) break; if (1 == NextBit (m_input)) continue; int prev_code = -1; while (data_pos < m_data.Length) { int code = 0; if (1 == NextBit (m_input)) { if (1 == NextBit (m_input)) code = NextBit (m_input) + 1; code = (code << 1) + NextBit (m_input) + 1; } code = (code << 1) + NextBit (m_input); if (code == prev_code) break; prev_code = code; int count = CountBits (m_input); if (prev_code >= 2) ++count; if (data_pos + count > m_data.Length) throw new InvalidFormatException(); int shift = ShiftTable[prev_code]; int offset = (shift >> 4) - (shift & 0xf) * m_width; Binary.CopyOverlapped (m_data, data_pos+offset, data_pos, count); data_pos += count; } } } } } }
35.95122
111
0.443691
[ "MIT" ]
coregameHD/GARbro
ArcFormats/ActiveSoft/ImageEDT.cs
13,266
C#
using System.Collections.Generic; using System.Globalization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace SimpleAPI { public class Startup { public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; }); services .AddMvc() .AddNewtonsoftJson(options => options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { var supportedCultures = new List<CultureInfo> { new CultureInfo("en"), new CultureInfo("fi") }; var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }; app.UseRequestLocalization(options); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
29.174603
115
0.695321
[ "MIT" ]
atkins126/I18N
Samples/ASP.NET/Core/WebAPI/SimpleAPI/Startup.cs
1,840
C#
using System; using AutoMapper; using RuneForge.Data.Orders; using RuneForge.Game.Buildings; using RuneForge.Game.Orders.Implementations; using RuneForge.Game.Units; namespace RuneForge.Game.AutoMapper.Resolvers { public class AttackOrderTargetEntityIdValueResolver : IValueResolver<AttackOrder, AttackOrderDto, string> { public string Resolve(AttackOrder source, AttackOrderDto destination, string destMember, ResolutionContext context) { if (source.TargetEntity == null) return null; else { string typeName = source.TargetEntity.GetType().Name; int id = source.TargetEntity switch { Unit unit => unit.Id, Building building => building.Id, _ => throw new NotSupportedException($"Unable to resaolve an integer Id for the entity of type {typeName}"), }; return $"{typeName}:{id}"; } } } }
32.25
128
0.604651
[ "MIT" ]
RuneForge/RuneForge
Source/RuneForge.Game/AutoMapper/Resolvers/AttackOrderTargetEntityIdValueResolver.cs
1,034
C#
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Hazelcast.Util; namespace Hazelcast.Client.Protocol.Util { /// <summary>Builder for appending buffers that grows capacity as necessary.</summary> internal class BufferBuilder { /// <summary>Buffer's default initial capacity</summary> public const int InitialCapacity = 4096; private readonly IClientProtocolBuffer _protocolBuffer; private int _capacity; private int _position; /// <summary> /// Construct a buffer builder with a default growth increment of /// <see cref="InitialCapacity" /> /// </summary> public BufferBuilder() : this(InitialCapacity) { } /// <summary>Construct a buffer builder with an initial capacity that will be rounded up to the nearest power of 2.</summary> /// <param name="initialCapacity">at which the capacity will start.</param> private BufferBuilder(int initialCapacity) { _capacity = QuickMath.NextPowerOfTwo(initialCapacity); _protocolBuffer = new SafeBuffer(new byte[_capacity]); } /// <summary>Append a source buffer to the end of the internal buffer, resizing the internal buffer as required.</summary> /// <param name="srcBuffer">from which to copy.</param> /// <param name="srcOffset">in the source buffer from which to copy.</param> /// <param name="length">in bytes to copy from the source buffer.</param> /// <returns>the builder for fluent API usage.</returns> public virtual BufferBuilder Append(IClientProtocolBuffer srcBuffer, int srcOffset, int length) { EnsureCapacity(length); srcBuffer.GetBytes(srcOffset, _protocolBuffer.ByteArray(), _position, length); _position += length; return this; } /// <summary> /// The /// <see cref="IClientProtocolBuffer" /> /// that encapsulates the internal buffer. /// </summary> /// <returns> /// the /// <see cref="IClientProtocolBuffer" /> /// that encapsulates the internal buffer. /// </returns> public virtual IClientProtocolBuffer Buffer() { return _protocolBuffer; } /// <summary>The current capacity of the buffer.</summary> /// <returns>the current capacity of the buffer.</returns> public virtual int Capacity() { return _capacity; } /// <summary>The current position of the buffer that has been used by accumulate operations.</summary> /// <returns>the current position of the buffer that has been used by accumulate operations.</returns> public virtual int Position() { return _position; } private void EnsureCapacity(int additionalCapacity) { var requiredCapacity = _position + additionalCapacity; if (requiredCapacity < 0) { var s = string.Format("Insufficient capacity: position={0} additional={1}", _position, additionalCapacity); throw new InvalidOperationException(s); } if (requiredCapacity > _capacity) { var newCapacity = QuickMath.NextPowerOfTwo(requiredCapacity); var newBuffer = new byte[newCapacity]; Array.Copy(_protocolBuffer.ByteArray(), 0, newBuffer, 0, _capacity); _capacity = newCapacity; _protocolBuffer.Wrap(newBuffer); } } } }
39.33945
133
0.617771
[ "Apache-2.0" ]
asimarslan/hazelcast-csharp-client
Hazelcast.Net/Hazelcast.Client.Protocol.Util/BufferBuilder.cs
4,288
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.PersonalizeRuntime")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Personalize Runtime. Amazon Personalize is a machine learning service that makes it easy for developers to create individualized recommendations for customers using their applications.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Personalize Runtime. Amazon Personalize is a machine learning service that makes it easy for developers to create individualized recommendations for customers using their applications.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon Personalize Runtime. Amazon Personalize is a machine learning service that makes it easy for developers to create individualized recommendations for customers using their applications.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon Personalize Runtime. Amazon Personalize is a machine learning service that makes it easy for developers to create individualized recommendations for customers using their applications.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon Personalize Runtime. Amazon Personalize is a machine learning service that makes it easy for developers to create individualized recommendations for customers using their applications.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon Personalize Runtime. Amazon Personalize is a machine learning service that makes it easy for developers to create individualized recommendations for customers using their applications.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.103.1")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
56.932203
282
0.790712
[ "Apache-2.0" ]
playstudios/aws-sdk-net
sdk/src/Services/PersonalizeRuntime/Properties/AssemblyInfo.cs
3,359
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.TestModels.ArubaModel { using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Infrastructure; public class ArubaContext : DbContext { static ArubaContext() { Database.SetInitializer(new ArubaInitializer()); } public DbSet<ArubaAllTypes> AllTypes { get; set; } public DbSet<ArubaBaseline> Baselines { get; set; } public DbSet<ArubaBug> Bugs { get; set; } public DbSet<ArubaConfig> Configs { get; set; } public DbSet<ArubaFailure> Failures { get; set; } public DbSet<ArubaOwner> Owners { get; set; } public DbSet<ArubaRun> Runs { get; set; } public DbSet<ArubaTask> Tasks { get; set; } public DbSet<ArubaPerson> People { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<ModelNamespaceConvention>(); modelBuilder.Entity<ArubaFailure>().ToTable("ArubaFailures"); modelBuilder.Entity<ArubaBaseline>().ToTable("ArubaBaselines"); modelBuilder.Entity<ArubaTestFailure>().ToTable("ArubaTestFailures"); // composite key, non-integer key modelBuilder.Entity<ArubaTask>().HasKey(k => new { k.Id, k.Name }); // need to map key explicitly, otherwise we get into invalid state modelBuilder.Entity<ArubaRun>().HasMany(r => r.Tasks).WithRequired().Map(m => { }); // non-generated key modelBuilder.Entity<ArubaOwner>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); modelBuilder.Entity<ArubaRun>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); modelBuilder.Entity<ArubaRun>().HasRequired(r => r.RunOwner).WithRequiredDependent(o => o.OwnedRun); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c6_smalldatetime).HasColumnType("smalldatetime"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c7_decimal_28_4).HasColumnType("decimal").HasPrecision(28, 4); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c8_numeric_28_4).HasColumnType("numeric").HasPrecision(28, 4); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c11_money).HasColumnType("money"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c12_smallmoney).HasColumnType("smallmoney"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c13_varchar_512_).HasMaxLength(512).IsVariableLength().IsUnicode(false); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c14_char_512_).HasMaxLength(512).IsFixedLength().IsUnicode(false); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c15_text).HasColumnType("text"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c16_binary_512_).HasMaxLength(512).IsFixedLength(); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c17_varbinary_512_).HasMaxLength(512).IsVariableLength(); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c18_image).HasColumnType("image"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c19_nvarchar_512_).HasMaxLength(512).IsVariableLength().IsUnicode(true); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c20_nchar_512_).HasMaxLength(512).IsFixedLength().IsUnicode(true); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c21_ntext).HasColumnType("ntext"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c24_varchar_max_).IsMaxLength().IsVariableLength().IsUnicode(false); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c25_nvarchar_max_).IsMaxLength().IsVariableLength().IsUnicode(true); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c26_varbinary_max_).IsMaxLength().IsVariableLength(); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c28_date).HasColumnType("date"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c29_datetime2).HasColumnType("datetime2"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c35_timestamp).HasColumnType("timestamp"); modelBuilder.Entity<ArubaAllTypes>().Property(p => p.c38_shortenum).HasColumnType("smallint"); // self reference modelBuilder.Entity<ArubaPerson>().HasOptional(p => p.Partner).WithOptionalPrincipal(); modelBuilder.Entity<ArubaPerson>().HasMany(p => p.Children).WithMany(p => p.Parents); // entity splitting modelBuilder.Entity<ArubaBug>().Map(m => { m.Properties(p => new { p.Id, p.Comment }); m.ToTable("Bugs1"); }); modelBuilder.Entity<ArubaBug>().Map(m => { m.Properties(p => new { p.Number, p.Resolution }); m.ToTable("Bugs2"); }); modelBuilder.Entity<ArubaOwner>().Property(o => o.FirstName).HasMaxLength(30); #if NETCOREAPP modelBuilder.Entity<ArubaAllTypes>().Ignore(x => x.c31_geography); modelBuilder.Entity<ArubaAllTypes>().Ignore(x => x.c32_geometry); modelBuilder.Entity<ArubaAllTypes>().Ignore(x => x.c36_geometry_linestring); modelBuilder.Entity<ArubaAllTypes>().Ignore(x => x.c37_geometry_polygon); modelBuilder.Entity<ArubaMachineConfig>().Ignore(x => x.Location); modelBuilder.Entity<ArubaRun>().Ignore(x => x.Geometry); #endif } } }
61.414894
137
0.661181
[ "Apache-2.0" ]
DenisBalan/ef6
test/FunctionalTests/TestModels/ArubaModel/ArubaContext.cs
5,775
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Rideshare.Data.Migrations { public partial class CarPhotoColumn : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<byte[]>( name: "Photo", table: "Cars", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Photo", table: "Cars"); } } }
24.916667
71
0.571906
[ "MIT" ]
ivanrk/Rideshare
Rideshare.Data/Migrations/20190716151430_CarPhotoColumn.cs
600
C#
// // Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle ("System.Net.AuthenticationManager.dll")] [assembly: AssemblyDescription ("System.Net.AuthenticationManager.dll")] [assembly: AssemblyDefaultAlias ("System.Net.AuthenticationManager.dll")] [assembly: AssemblyCompany ("Xamarin, Inc.")] [assembly: AssemblyProduct ("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright ("Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)")] [assembly: AssemblyVersion ("4.0.0.0")] [assembly: AssemblyInformationalVersion ("4.0.0.0")] [assembly: AssemblyFileVersion ("4.0.0.0")] [assembly: AssemblyDelaySign (true)] [assembly: AssemblyKeyFile ("../../msfinal.pub")] [assembly: ReferenceAssembly]
45.285714
90
0.760778
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/class/Facades/System.Net.AuthenticationManager/AssemblyInfo.cs
1,902
C#
using System; using pdxpartyparrot.Core.Effects; using pdxpartyparrot.Core.World; using pdxpartyparrot.Game.State; using UnityEngine; using UnityEngine.AI; namespace pdxpartyparrot.Game.Level { [RequireComponent(typeof(NavMeshSurface))] public abstract class LevelHelper : MonoBehaviour { [SerializeField] private string _nextLevel; [Space(10)] [SerializeField] private EffectTrigger _levelEnterEffect; [SerializeField] private EffectTrigger _levelExitEffect; private NavMeshSurface _navMeshSurface; #region Unity Lifecycle protected virtual void Awake() { _navMeshSurface = GetComponent<NavMeshSurface>(); GameStateManager.Instance.GameManager.RegisterLevelHelper(this); GameStateManager.Instance.GameManager.GameStartServerEvent += GameStartServerEventHandler; GameStateManager.Instance.GameManager.GameStartClientEvent += GameStartClientEventHandler; GameStateManager.Instance.GameManager.GameReadyEvent += GameReadyEventHandler; GameStateManager.Instance.GameManager.GameOverEvent += GameOverEventHandler; } protected virtual void OnDestroy() { if(GameStateManager.HasInstance && null != GameStateManager.Instance.GameManager) { GameStateManager.Instance.GameManager.GameOverEvent -= GameOverEventHandler; GameStateManager.Instance.GameManager.GameReadyEvent -= GameReadyEventHandler; GameStateManager.Instance.GameManager.GameStartClientEvent -= GameStartClientEventHandler; GameStateManager.Instance.GameManager.GameStartServerEvent -= GameStartServerEventHandler; GameStateManager.Instance.GameManager.UnRegisterLevelHelper(this); } } #endregion protected void TransitionLevel() { // load the next level if we have one if(!string.IsNullOrWhiteSpace(_nextLevel)) { if(null != _levelExitEffect) { _levelExitEffect.Trigger(DoLevelTransition); } else { DoLevelTransition(); } } else { GameStateManager.Instance.GameManager.GameOver(); } } private void DoLevelTransition() { GameStateManager.Instance.GameManager.GameUnReady(); GameStateManager.Instance.GameManager.TransitionScene(_nextLevel, null); } #region Event Handlers protected virtual void GameStartServerEventHandler(object sender, EventArgs args) { // TODO: better to do this before we drop the loading screen and spawn stuff _navMeshSurface.BuildNavMesh(); SpawnManager.Instance.Initialize(); } protected virtual void GameStartClientEventHandler(object sender, EventArgs args) { // TODO: we really should communicate our ready state to the server // and then have it communicate back to us when everybody is ready if(null != _levelEnterEffect) { _levelEnterEffect.Trigger(GameStateManager.Instance.GameManager.GameReady); } else { GameStateManager.Instance.GameManager.GameReady(); } } protected virtual void GameReadyEventHandler(object sender, EventArgs args) { } protected virtual void GameOverEventHandler(object sender, EventArgs args) { } #endregion } }
34.576923
106
0.656007
[ "Apache-2.0" ]
pdxparrot/ssj2019
Assets/Scripts/Game/Level/LevelHelper.cs
3,598
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; namespace Cheer.App_Start { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.IgnoreList.Clear(); AddDefaultIgnorePatterns(bundles.IgnoreList); bundles.Add( new StyleBundle("~/css/app") .Include("~/css/app.css") ); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/scripts/modernizrlib").Include( "~/scripts/modernizr/modernizr.js")); bundles.Add( new ScriptBundle("~/scripts/vendor") .Include("~/scripts/jquery/dist/jquery.js") .Include("~/scripts/fastclick/lib/fastclick.js") .Include("~/scripts/foundation/js/foundation/foundation.js") .Include("~/scripts/foundation/js/foundation/foundation.abide.js") .Include("~/scripts/foundation/js/foundation/foundation.clearing.js") .Include("~/scripts/foundation/js/foundation/foundation.interchange.js") .Include("~/scripts/foundation/js/foundation/foundation.topbar.js") .Include("~/scripts/app.js") ); } private static void AddDefaultIgnorePatterns(IgnoreList ignoreList) { if (ignoreList == null) { throw new ArgumentNullException("BundleConfig ignore list."); } ignoreList.Ignore("*.intellisense.js"); ignoreList.Ignore("*-vsdoc.js"); } } }
36.711538
112
0.580409
[ "MIT" ]
chrisjsherm/OrganizationCMS
Cheer/App_Start/BundleConfig.cs
1,911
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Globalization; using System.Management.Automation; using Microsoft.Azure.Commands.DataFactoryV2.Models; using Microsoft.Azure.Commands.DataFactoryV2.Properties; namespace Microsoft.Azure.Commands.DataFactoryV2 { [Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DataFactoryV2IntegrationRuntimeKey",DefaultParameterSetName = ParameterSetNames.ByIntegrationRuntimeName,SupportsShouldProcess = true),OutputType(typeof(PSIntegrationRuntimeKeys))] public class NewAzureDataFactoryIntegrationRuntimeKeyCommand : IntegrationRuntimeCmdlet { [Parameter( Mandatory = true, HelpMessage = Constants.HelpIntegrationRuntimeKeyName)] [ValidateNotNullOrEmpty] [ValidateSet("AuthKey1", "AuthKey2", IgnoreCase = true)] public string KeyName { get; set; } [Parameter(Mandatory = false, HelpMessage = Constants.HelpDontAskConfirmation)] public SwitchParameter Force { get; set; } public override void ExecuteCmdlet() { this.ByResourceId(); this.ByIntegrationRuntimeObject(); if (string.IsNullOrWhiteSpace(KeyName)) { throw new PSArgumentNullException("KeyName"); } PSIntegrationRuntimeKeys authKey = null; Action regenerateIntegrationRuntimeAuthKey = () => { authKey = DataFactoryClient.RegenerateIntegrationRuntimeAuthKeyAsync( ResourceGroupName, DataFactoryName, Name, KeyName).ConfigureAwait(true).GetAwaiter().GetResult(); }; ConfirmAction( Force.IsPresent, // prompt only if the integration runtime exists string.Format( CultureInfo.InvariantCulture, Resources.ContinueRegenerateAuthKey, KeyName, Name), // Process message, string.Format( CultureInfo.InvariantCulture, Resources.RegenerateAuthKey, KeyName, Name), // Target Name, regenerateIntegrationRuntimeAuthKey, () => DataFactoryClient.CheckIntegrationRuntimeExistsAsync( ResourceGroupName, DataFactoryName, Name).ConfigureAwait(true).GetAwaiter().GetResult()); WriteObject(authKey); } } }
42.012195
257
0.582583
[ "MIT" ]
3quanfeng/azure-powershell
src/DataFactory/DataFactoryV2/IntegrationRuntimes/NewAzureDataFactoryIntegrationRuntimeKeyCommand.cs
3,366
C#
using System; namespace Profiles.ORCID.Utilities.ProfilesRNSDLL.BLL.ORCID { public partial class PersonOthername : ProfilesRNSDLL.DAL.ORCID.PersonOthername { # region Constructors public PersonOthername() : base() { } # endregion // Constructors # region Public Methods public override void DBRulesCG(ProfilesRNSDLL.BO.ORCID.PersonOthername bo) { /*! Check for missing values */ if (bo.PersonIDIsNull) { bo.PersonIDErrors += "Required." + Environment.NewLine; bo.HasError = true; } else { } /*! Check for out of Range values */ if (!bo.OtherNameIsNull) { if (bo.OtherName.Length > 500) { bo.OtherNameErrors += "This field has more characters than the maximum that can be stored, i.e. 500 characters." + Environment.NewLine; bo.HasError = true; } } } # endregion // Public Methods } }
27.609756
158
0.518551
[ "BSD-3-Clause" ]
CTSIatUCSF/ProfilesRNS
Website/SourceCode/Profiles/Profiles/ORCID/Utilities/ProfilesRNSDLL/_CG/BLL/ORCID/PersonOthername.cs
1,132
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/d3d11.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.DirectX; /// <include file='D3D11_COUNTER_DESC.xml' path='doc/member[@name="D3D11_COUNTER_DESC"]/*' /> public partial struct D3D11_COUNTER_DESC { /// <include file='D3D11_COUNTER_DESC.xml' path='doc/member[@name="D3D11_COUNTER_DESC.Counter"]/*' /> public D3D11_COUNTER Counter; /// <include file='D3D11_COUNTER_DESC.xml' path='doc/member[@name="D3D11_COUNTER_DESC.MiscFlags"]/*' /> public uint MiscFlags; }
43.235294
145
0.744218
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/d3d11/D3D11_COUNTER_DESC.cs
737
C#
using MediatR; using Microsoft.EntityFrameworkCore; using OSS.App.Data; using OSS.Domain.Entities; using System.Threading; using System.Threading.Tasks; namespace OSS.App.LeaveRequests.Commands.ToggleLeaveRequestApproval { public class ToggleLeaveRequestApprovalCommandHandler : IRequestHandler<ToggleLeaveRequestApprovalCommand, LeaveRequest> { private readonly AppIdentityDbContext _context; public ToggleLeaveRequestApprovalCommandHandler(AppIdentityDbContext context) { _context = context; } public async Task<LeaveRequest> Handle(ToggleLeaveRequestApprovalCommand request, CancellationToken cancellationToken) { LeaveRequest lr = await _context.LeaveRequests.FindAsync(request.Id); lr.IsApproved = !lr.IsApproved; _context.Attach(lr).State = EntityState.Modified; await _context.SaveChangesAsync(); return lr; } } }
31.193548
126
0.720786
[ "MIT" ]
nagasudhirpulla/open_shift_scheduler
src/OSS.App/LeaveRequests/Commands/ToggleLeaveRequestApproval/ToggleLeaveRequestApprovalCommandHandler.cs
969
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.ComponentModel.Design; using System.Collections; using System.Reflection; using System.Runtime.InteropServices; namespace System.ComponentModel { public sealed partial class LicenseManager { // A private implementation of a LicenseContext used for instantiating // managed objects exposed to COM. It has memory for the license key // of a single Type. private class CLRLicenseContext : LicenseContext { private readonly Type _type; private string _key; private CLRLicenseContext(Type type, LicenseUsageMode mode) { UsageMode = mode; _type = type; } public static CLRLicenseContext CreateDesignContext(Type type) { return new CLRLicenseContext(type, LicenseUsageMode.Designtime); } public static CLRLicenseContext CreateRuntimeContext(Type type, string key) { var cxt = new CLRLicenseContext(type, LicenseUsageMode.Runtime); if (key != null) { cxt.SetSavedLicenseKey(type, key); } return cxt; } public override LicenseUsageMode UsageMode { get; } public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) { if (type == _type) { return _key; } return null; } public override void SetSavedLicenseKey(Type type, string key) { if (type == _type) { _key = key; } } } // Used from IClassFactory2 when retrieving LicInfo private class LicInfoHelperLicenseContext : LicenseContext { private Hashtable _savedLicenseKeys = new Hashtable(); public bool Contains(string assemblyName) => _savedLicenseKeys.Contains(assemblyName); public override LicenseUsageMode UsageMode => LicenseUsageMode.Designtime; public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) => null; public override void SetSavedLicenseKey(Type type, string key) { _savedLicenseKeys[type.AssemblyQualifiedName] = key; } } // This is a helper class that supports the CLR's IClassFactory2 marshaling // support. private class LicenseInteropHelper { // Used to validate a type and retrieve license details // when activating a managed COM server from an IClassFactory2 instance. public static bool ValidateAndRetrieveLicenseDetails( LicenseContext context, Type type, out License license, out string licenseKey) { if (context == null) { context = LicenseManager.CurrentContext; } return LicenseManager.ValidateInternalRecursive( context, type, instance: null, allowExceptions: false, out license, out licenseKey); } // The CLR invokes this when instantiating an unmanaged COM // object. The purpose is to decide which IClassFactory method to // use. public static LicenseContext GetCurrentContextInfo(Type type, out bool isDesignTime, out string key) { LicenseContext licContext = LicenseManager.CurrentContext; isDesignTime = licContext.UsageMode == LicenseUsageMode.Designtime; key = null; if (!isDesignTime) { key = licContext.GetSavedLicenseKey(type, resourceAssembly: null); } return licContext; } } } }
34.309524
112
0.560028
[ "MIT" ]
ARhj/corefx
src/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.LicenseInteropHelper.cs
4,323
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using ASC.Core; using ASC.Core.Users; using ASC.Files.Core; using ASC.MessagingSystem; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Files.Helpers; using ASC.Web.Files.Resources; using ASC.Web.Studio.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Threading; using System.Web; using File = ASC.Files.Core.File; using SecurityContext = ASC.Core.SecurityContext; namespace ASC.Web.Files.Utils { public static class FileUploader { public static File Exec(string folderId, string title, long contentLength, Stream data) { return Exec(folderId, title, contentLength, data, !FilesSettings.UpdateIfExist); } public static File Exec(string folderId, string title, long contentLength, Stream data, bool createNewIfExist, bool deleteConvertStatus = true) { if (contentLength <= 0) throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile); var file = VerifyFileUpload(folderId, title, contentLength, !createNewIfExist); using (var dao = Global.DaoFactory.GetFileDao()) { file = dao.SaveFile(file, data); } FileMarker.MarkAsNew(file); if (FileConverter.EnableAsUploaded && FileConverter.MustConvert(file)) FileConverter.ExecAsync(file, deleteConvertStatus); return file; } public static File VerifyFileUpload(string folderId, string fileName, bool updateIfExists, string relativePath = null) { fileName = Global.ReplaceInvalidCharsAndTruncate(fileName); if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(fileName))) throw new NotSupportedException(FilesCommonResource.ErrorMassage_NotSupportedFormat); folderId = GetFolderId(folderId, string.IsNullOrEmpty(relativePath) ? null : relativePath.Split('/').ToList()); using (var fileDao = Global.DaoFactory.GetFileDao()) { var file = fileDao.GetFile(folderId, fileName); if (updateIfExists && CanEdit(file)) { file.Title = fileName; file.ConvertedType = null; file.Comment = FilesCommonResource.CommentUpload; file.Version++; file.VersionGroup++; file.Encrypted = false; return file; } } return new File {FolderID = folderId, Title = fileName}; } public static File VerifyFileUpload(string folderId, string fileName, long fileSize, bool updateIfExists) { if (fileSize <= 0) throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile); var maxUploadSize = GetMaxFileSize(folderId); if (fileSize > maxUploadSize) throw FileSizeComment.GetFileSizeException(maxUploadSize); var file = VerifyFileUpload(folderId, fileName, updateIfExists); file.ContentLength = fileSize; return file; } private static bool CanEdit(File file) { return file != null && Global.GetFilesSecurity().CanEdit(file) && !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor() && !EntryManager.FileLockedForMe(file.ID) && !FileTracker.IsEditing(file.ID) && file.RootFolderType != FolderType.TRASH && !file.Encrypted; } private static string GetFolderId(object folderId, IList<string> relativePath) { using (var folderDao = Global.DaoFactory.GetFolderDao()) { var folder = folderDao.GetFolder(folderId); if (folder == null) throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound); if (!Global.GetFilesSecurity().CanCreate(folder)) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create); if (relativePath != null && relativePath.Any()) { var subFolderTitle = Global.ReplaceInvalidCharsAndTruncate(relativePath.FirstOrDefault()); if (!string.IsNullOrEmpty(subFolderTitle)) { folder = folderDao.GetFolder(subFolderTitle, folder.ID); if (folder == null) { folderId = folderDao.SaveFolder(new Folder {Title = subFolderTitle, ParentFolderID = folderId}); folder = folderDao.GetFolder(folderId); FilesMessageService.Send(folder, HttpContext.Current.Request, MessageAction.FolderCreated, folder.Title); } folderId = folder.ID; relativePath.RemoveAt(0); folderId = GetFolderId(folderId, relativePath); } } } return folderId.ToString(); } #region chunked upload public static File VerifyChunkedUpload(string folderId, string fileName, long fileSize, bool updateIfExists, string relativePath = null) { var maxUploadSize = GetMaxFileSize(folderId, true); if (fileSize > maxUploadSize) throw FileSizeComment.GetFileSizeException(maxUploadSize); var file = VerifyFileUpload(folderId, fileName, updateIfExists, relativePath); file.ContentLength = fileSize; return file; } public static ChunkedUploadSession InitiateUpload(string folderId, string fileId, string fileName, long contentLength, bool encrypted) { if (string.IsNullOrEmpty(folderId)) folderId = null; if (string.IsNullOrEmpty(fileId)) fileId = null; var file = new File { ID = fileId, FolderID = folderId, Title = fileName, ContentLength = contentLength }; using (var dao = Global.DaoFactory.GetFileDao()) { var uploadSession = dao.CreateUploadSession(file, contentLength); uploadSession.Expired = uploadSession.Created + ChunkedUploadSessionHolder.SlidingExpiration; uploadSession.Location = FilesLinkUtility.GetUploadChunkLocationUrl(uploadSession.Id); uploadSession.TenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId; uploadSession.UserId = SecurityContext.CurrentAccount.ID; uploadSession.FolderId = folderId; uploadSession.CultureName = Thread.CurrentThread.CurrentUICulture.Name; uploadSession.Encrypted = encrypted; ChunkedUploadSessionHolder.StoreSession(uploadSession); return uploadSession; } } public static ChunkedUploadSession UploadChunk(string uploadId, Stream stream, long chunkLength) { var uploadSession = ChunkedUploadSessionHolder.GetSession(uploadId); uploadSession.Expired = DateTime.UtcNow + ChunkedUploadSessionHolder.SlidingExpiration; if (chunkLength <= 0) { throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile); } if (chunkLength > SetupInfo.ChunkUploadSize) { throw FileSizeComment.GetFileSizeException(SetupInfo.MaxUploadSize); } var maxUploadSize = GetMaxFileSize(uploadSession.FolderId, uploadSession.BytesTotal > 0); if (uploadSession.BytesUploaded + chunkLength > maxUploadSize) { AbortUpload(uploadSession); throw FileSizeComment.GetFileSizeException(maxUploadSize); } using (var dao = Global.DaoFactory.GetFileDao()) { dao.UploadChunk(uploadSession, stream, chunkLength); } if (uploadSession.BytesUploaded == uploadSession.BytesTotal) { FileMarker.MarkAsNew(uploadSession.File); ChunkedUploadSessionHolder.RemoveSession(uploadSession); } else { ChunkedUploadSessionHolder.StoreSession(uploadSession); } return uploadSession; } public static void AbortUpload(string uploadId) { AbortUpload(ChunkedUploadSessionHolder.GetSession(uploadId)); } private static void AbortUpload(ChunkedUploadSession uploadSession) { using (var dao = Global.DaoFactory.GetFileDao()) { dao.AbortUploadSession(uploadSession); } ChunkedUploadSessionHolder.RemoveSession(uploadSession); } private static long GetMaxFileSize(object folderId, bool chunkedUpload = false) { using (var folderDao = Global.DaoFactory.GetFolderDao()) { return folderDao.GetMaxUploadSize(folderId, chunkedUpload); } } #endregion } }
37.08
151
0.605178
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
web/studio/ASC.Web.Studio/Products/Files/Utils/FileUploader.cs
10,197
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Geek.Server { //摘自微软官网 // Provides a task scheduler that ensures a maximum concurrency level while // running on top of the thread pool. public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler { // Indicates whether the current thread is processing work items. [ThreadStatic] private static bool _currentThreadIsProcessingItems; // The list of tasks to be executed private readonly LinkedList<Task> _tasks = new LinkedList<Task>(); // protected by lock(_tasks) // The maximum concurrency level allowed by this scheduler. private readonly int _maxDegreeOfParallelism; // Indicates whether the scheduler is currently processing work items. private int _delegatesQueuedOrRunning = 0; // Creates a new instance with the specified degree of parallelism. public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism) { if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism"); _maxDegreeOfParallelism = maxDegreeOfParallelism; } // Queues a task to the scheduler. protected sealed override void QueueTask(Task task) { // Add the task to the list of tasks to be processed. If there aren't enough // delegates currently queued or running to process tasks, schedule another. lock (_tasks) { _tasks.AddLast(task); if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism) { ++_delegatesQueuedOrRunning; NotifyThreadPoolOfPendingWork(); } } } // Inform the ThreadPool that there's work to be executed for this scheduler. private void NotifyThreadPoolOfPendingWork() { ThreadPool.UnsafeQueueUserWorkItem(_ => { // Note that the current thread is now processing work items. // This is necessary to enable inlining of tasks into this thread. _currentThreadIsProcessingItems = true; try { // Process all available items in the queue. while (true) { Task item; lock (_tasks) { // When there are no more items to be processed, // note that we're done processing, and get out. if (_tasks.Count == 0) { --_delegatesQueuedOrRunning; break; } // Get the next item from the queue item = _tasks.First.Value; _tasks.RemoveFirst(); } // Execute the task we pulled out of the queue base.TryExecuteTask(item); } } // We're done processing items on the current thread finally { _currentThreadIsProcessingItems = false; } }, null); } // Attempts to execute the specified task on the current thread. protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // If this thread isn't already processing a task, we don't support inlining if (!_currentThreadIsProcessingItems) return false; // If the task was previously queued, remove it from the queue if (taskWasPreviouslyQueued) // Try to run the task. if (TryDequeue(task)) return base.TryExecuteTask(task); else return false; else return base.TryExecuteTask(task); } // Attempt to remove a previously scheduled task from the scheduler. protected sealed override bool TryDequeue(Task task) { lock (_tasks) return _tasks.Remove(task); } // Gets the maximum concurrency level supported by this scheduler. public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } } // Gets an enumerable of the tasks currently scheduled on this scheduler. protected sealed override IEnumerable<Task> GetScheduledTasks() { bool lockTaken = false; try { Monitor.TryEnter(_tasks, ref lockTaken); if (lockTaken) return _tasks; else throw new NotSupportedException(); } finally { if (lockTaken) Monitor.Exit(_tasks); } } } }
38.875969
108
0.561515
[ "MIT" ]
johnson2heng/GeekServer
GeekServer.Core/Actor/LimitedConcurrencyLevelTaskScheduler.cs
5,029
C#
using ControllerApp.ControllerCore; using ControllerApp.Helpers; using Xunit; namespace ControllerApp.Tests { public class HelperTests { [Fact] public void TryGetCoordinates_X_Valid() { // ok coordinates string[] parts = new string[] { "G1", "X22.3", "Y65.3" }; float result = 0F; Assert.True(MathHelper.TryGetCoordinates(parts, Axis.X, out result)); Assert.Equal(22.3F, result); Assert.True(MathHelper.TryGetCoordinates(parts, Axis.Y, out result)); Assert.Equal(65.3F, result); } [Fact] public void TryGetCoordinates_Invalid_X_Valid_Y() { // X missing from parameter string[] parts = new string[] { "G1", "22.3", "Y65.3" }; float result = 0F; Assert.False(MathHelper.TryGetCoordinates(parts, Axis.X, out result)); Assert.Equal(0F, result); Assert.True(MathHelper.TryGetCoordinates(parts, Axis.Y, out result)); Assert.Equal(65.3F, result); } [Fact] public void TryGetCoordinates_Valid_X_Invalid_Y() { // Y missing from parameter string[] parts = new string[] { "G1", "X22.3", "batata" }; float result = 0F; Assert.True(MathHelper.TryGetCoordinates(parts, Axis.X, out result)); Assert.Equal(22.3F, result); Assert.False(MathHelper.TryGetCoordinates(parts, Axis.Y, out result)); Assert.Equal(0F, result); } [Fact] public void TryGetCoordinates_Null_Parts() { // Y missing from parameter string[] parts = new string[] { null, null, null }; float result = 0F; Assert.False(MathHelper.TryGetCoordinates(parts, Axis.X, out result)); Assert.Equal(0F, result); Assert.False(MathHelper.TryGetCoordinates(parts, Axis.Y, out result)); Assert.Equal(0F, result); } [Fact] public void TryGetCoordinates_Empty_Parts() { // Y missing from parameter string[] parts = new string[] { string.Empty, string.Empty, string.Empty }; float result = 0F; Assert.False(MathHelper.TryGetCoordinates(parts, Axis.X, out result)); Assert.Equal(0F, result); Assert.False(MathHelper.TryGetCoordinates(parts, Axis.Y, out result)); Assert.Equal(0F, result); } [Fact] public void TryGetCoordinates_Null_Array_Of_Parts() { // Y missing from parameter string[] parts = null; float result = 0F; Assert.False(MathHelper.TryGetCoordinates(parts, Axis.X, out result)); Assert.Equal(0F, result); Assert.False(MathHelper.TryGetCoordinates(parts, Axis.Y, out result)); Assert.Equal(0F, result); } } }
29.88
87
0.566265
[ "MIT" ]
RafaelEstevamReis/lzak
LZakSuite/ControllerApp.Tests/HelperTests.cs
2,990
C#
using System.Web.Http; using System.Web.Mvc; namespace BiometricAPI.Areas.HelpPage { public class HelpPageAreaRegistration : AreaRegistration { public override string AreaName { get { return "HelpPage"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "HelpPage_Default", "Help/{action}/{apiId}", new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); HelpPageConfig.Register(GlobalConfiguration.Configuration); } } }
25.769231
94
0.564179
[ "MIT" ]
iAvinashVarma/BiometricAPI
BiometricAPI/Areas/HelpPage/HelpPageAreaRegistration.cs
670
C#
using Jeeves.Docs.Models; using Microsoft.AspNetCore.Components; using System.Threading.Tasks; namespace Jeeves.Docs.Pages { /// <summary> /// Program component. /// </summary> /// <seealso cref="Microsoft.AspNetCore.Components.ComponentBase" /> public partial class Program { /// <summary> /// Gets or sets the program identifier. /// </summary> [Parameter] public string ProgramId { get; set; } /// <summary> /// Gets or sets the locale static texts. /// </summary> [Inject] public LocaleStaticTexts LocaleStaticTexts { get; set; } /// <summary> /// Gets or sets the data service. /// </summary> [Inject] public IDataService DataService { get; set; } /// <summary> /// Gets or sets the program contents. /// </summary> public DocsAgent.Models.Program ProgramContents { get; set; } /// <summary> /// Method invoked when the component has received parameters from its parent in /// the render tree, and the incoming values have been assigned to properties. /// </summary> protected override async Task OnParametersSetAsync() { ProgramContents = await DataService.GetProgram(ProgramId); await base.OnParametersSetAsync(); } } }
25.489362
82
0.686978
[ "MIT" ]
rajeshaz09/BlazorAOTDemo
src/Jeeves.Docs/Jeeves.Docs/Pages/Program.razor.cs
1,200
C#
namespace LINGYUN.Abp.WeChat.Features { public static class WeChatFeatures { public const string GroupName = "Abp.WeChat"; } }
18.5
53
0.668919
[ "MIT" ]
FanShiYou/abp-vue-admin-element-typescript
aspnet-core/modules/wechat/LINGYUN.Abp.WeChat/LINGYUN/Abp/WeChat/Features/WeChatFeatures.cs
150
C#
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Core.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Core\Suspend-Job command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class SuspendJob : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public SuspendJob() { this.DisplayName = "Suspend-Job"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Core\\Suspend-Job"; } } // Arguments /// <summary> /// Provides access to the Job parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.Job[]> Job { get; set; } /// <summary> /// Provides access to the Force parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Force { get; set; } /// <summary> /// Provides access to the Wait parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Wait { get; set; } /// <summary> /// Provides access to the Name parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Name { get; set; } /// <summary> /// Provides access to the InstanceId parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Guid[]> InstanceId { get; set; } /// <summary> /// Provides access to the JobId parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32[]> JobId { get; set; } /// <summary> /// Provides access to the State parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.JobState> State { get; set; } /// <summary> /// Provides access to the Filter parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Collections.Hashtable> Filter { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(Job.Expression != null) { targetCommand.AddParameter("Job", Job.Get(context)); } if(Force.Expression != null) { targetCommand.AddParameter("Force", Force.Get(context)); } if(Wait.Expression != null) { targetCommand.AddParameter("Wait", Wait.Get(context)); } if(Name.Expression != null) { targetCommand.AddParameter("Name", Name.Get(context)); } if(InstanceId.Expression != null) { targetCommand.AddParameter("InstanceId", InstanceId.Get(context)); } if(JobId.Expression != null) { targetCommand.AddParameter("Id", JobId.Get(context)); } if(State.Expression != null) { targetCommand.AddParameter("State", State.Get(context)); } if(Filter.Expression != null) { targetCommand.AddParameter("Filter", Filter.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
33.864516
130
0.594589
[ "Apache-2.0", "MIT" ]
adbertram/PowerShell
src/Microsoft.PowerShell.Core.Activities/Generated/SuspendJobActivity.cs
5,249
C#
using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.UI; public class LongClickEvent : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { private bool pointerDown; public UnityEvent onLongClick; [SerializeField] private Image fillImage; public void OnPointerDown(PointerEventData eventData) { pointerDown = true; } public void OnPointerUp(PointerEventData eventData) { pointerDown = false; } private void Update() { if (pointerDown) { if (onLongClick != null) onLongClick.Invoke(); AddEffect(); } else fillImage.fillAmount = 0; } private void AddEffect() { if (fillImage.fillAmount < 1) fillImage.fillAmount += 0.2f; else fillImage.fillAmount = 0; } }
23.421053
84
0.620225
[ "CC0-1.0" ]
JunHong-1998/Unity-MathAdventure-RPG-Game
Scripts/LongClickEvent.cs
892
C#
using Azure.Cosmos; using Foo.Domain.Entities.Repositories; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Threading.Tasks; namespace Foo.Ui.Api.Controllers { [Route("[controller]")] [ApiController] public class FooController : ControllerBase { private readonly IFooRepository _fooRepository; public FooController(IFooRepository fooRepository) { _fooRepository = fooRepository; } [HttpPost("")] public async Task<IActionResult> CreateAsync(Domain.Entities.Foo foo) { await _fooRepository.AddAsync(foo, new PartitionKey(foo.City)); return Ok(); } [HttpGet("")] public async Task<IActionResult> GetAsync() { var result = new List<Domain.Entities.Foo> { }; await foreach (var item in _fooRepository.GetAllAsync()) result.Add(item); return Ok(result); } [HttpGet("{id}/{partitionKey}")] public async Task<IActionResult> GetAsync(string id, string partitionKey) { var foo = await _fooRepository.GetByIdAsync(id, new PartitionKey(partitionKey)); return Ok(foo); } [HttpGet("{neighborhood}")] public async Task<IActionResult> GetAsync(string neighborhood) { var foos = await _fooRepository.GetByNeighborhood(neighborhood); return Ok(foos); } [HttpPut("")] public async Task<IActionResult> UpdateAsync(Domain.Entities.Foo foo) { await _fooRepository.UpdateAsync(foo, new PartitionKey(foo.City)); return Ok(); } [HttpDelete("{id}/{partitionKey}")] public async Task<IActionResult> DeleteAsync(string id, string partitionKey) { await _fooRepository.DeleteAsync(id, new PartitionKey(partitionKey)); return Ok(); } } }
29.102941
92
0.607377
[ "MIT" ]
brunobrandes/cosmos-db-sql-api-repository
example/Ui/Foo.Ui.Api/Controllers/FooController.cs
1,981
C#
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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 Apache.Ignite.Core.Impl.Binary { using System; using System.Collections.Generic; using System.Diagnostics; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Reader extensions. /// </summary> internal static class BinaryReaderExtensions { /// <summary> /// Reads untyped collection as a generic list. /// </summary> /// <typeparam name="T">Type of list element.</typeparam> /// <param name="reader">The reader.</param> /// <returns>Resulting generic list.</returns> public static List<T> ReadCollectionAsList<T>(this IBinaryRawReader reader) { return ((List<T>) reader.ReadCollection(size => new List<T>(size), (col, elem) => ((List<T>) col).Add((T) elem))); } /// <summary> /// Reads untyped dictionary as generic dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="reader">The reader.</param> /// <returns>Resulting dictionary.</returns> public static Dictionary<TKey, TValue> ReadDictionaryAsGeneric<TKey, TValue>(this IBinaryRawReader reader) { return (Dictionary<TKey, TValue>) reader.ReadDictionary(size => new Dictionary<TKey, TValue>(size)); } /// <summary> /// Reads long as timespan with range checks. /// </summary> /// <param name="reader">The reader.</param> /// <returns>TimeSpan.</returns> public static TimeSpan ReadLongAsTimespan(this IBinaryRawReader reader) { return BinaryUtils.LongToTimeSpan(reader.ReadLong()); } /// <summary> /// Reads the nullable TimeSpan. /// </summary> public static TimeSpan? ReadTimeSpanNullable(this IBinaryRawReader reader) { return reader.ReadBoolean() ? reader.ReadLongAsTimespan() : (TimeSpan?) null; } /// <summary> /// Reads the nullable int. /// </summary> public static int? ReadIntNullable(this IBinaryRawReader reader) { return reader.ReadBoolean() ? reader.ReadInt() : (int?) null; } /// <summary> /// Reads the nullable long. /// </summary> public static long? ReadLongNullable(this IBinaryRawReader reader) { return reader.ReadBoolean() ? reader.ReadLong() : (long?) null; } /// <summary> /// Reads the nullable bool. /// </summary> public static bool? ReadBooleanNullable(this IBinaryRawReader reader) { return reader.ReadBoolean() ? reader.ReadBoolean() : (bool?) null; } /// <summary> /// Reads the object either as a normal object or as a [typeName+props] wrapper. /// </summary> public static T ReadObjectEx<T>(this IBinaryRawReader reader) { var obj = reader.ReadObject<object>(); if (obj == null) return default(T); return obj is T ? (T) obj : ((ObjectInfoHolder) obj).CreateInstance<T>(); } /// <summary> /// Reads the collection. The collection could be produced by Java PlatformUtils.writeCollection() /// from org.apache.ignite.internal.processors.platform.utils package /// Note: return null if collection is empty /// </summary> public static ICollection<T> ReadCollectionRaw<T, TReader>(this TReader reader, Func<TReader, T> factory) where TReader : IBinaryRawReader { Debug.Assert(reader != null); Debug.Assert(factory != null); int count = reader.ReadInt(); if (count <= 0) { return null; } var res = new List<T>(count); for (var i = 0; i < count; i++) { res.Add(factory(reader)); } return res; } /// <summary> /// Reads the string collection. /// </summary> public static List<string> ReadStringCollection(this IBinaryRawReader reader) { Debug.Assert(reader != null); var cnt = reader.ReadInt(); var res = new List<string>(cnt); for (var i = 0; i < cnt; i++) { res.Add(reader.ReadString()); } return res; } /// <summary> /// Reads a nullable collection. The collection could be produced by Java /// PlatformUtils.writeNullableCollection() from org.apache.ignite.internal.processors.platform.utils package. /// </summary> public static ICollection<T> ReadNullableCollectionRaw<T, TReader>(this TReader reader, Func<TReader, T> factory) where TReader : IBinaryRawReader { Debug.Assert(reader != null); Debug.Assert(factory != null); var hasVal = reader.ReadBoolean(); if (!hasVal) { return null; } return ReadCollectionRaw(reader, factory); } } }
34.308571
118
0.578947
[ "CC0-1.0" ]
Diffblue-benchmarks/Gridgain-gridgain
modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/BinaryReaderExtensions.cs
6,006
C#
 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DemoZPDK_Xamarin.Helper { public class Util { public static long GetTimeStamp(DateTime date) { return (long)(date.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds; } public static long GetTimeStamp() { return GetTimeStamp(DateTime.Now); } } }
22.4
104
0.620536
[ "Apache-2.0" ]
zpmep/DemoZPDK_Xamarin
DemoZPDK_Xamarin/Helper/Util.cs
450
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UserControls { public partial class PocetniIzbornik : Form { public PocetniIzbornik() { InitializeComponent(); PratiEvente(); } private void PratiEvente() { Eventi.ZaboravljenaLozinka += Eventi_ZaboravljenaLozinka; Eventi.RegistrirajSe += Eventi_RegistrirajSe; Eventi.NatragNaPrijavu += Eventi_NatragNaPrijavu; Eventi.UspjesnaPrijavaStudent += Eventi_UspjesnaPrijavaStudent; Eventi.UspjesnaPrijavaProfesor += Eventi_UspjesnaPrijavaProfesor; Eventi.Izlaz += Eventi_Izlaz; } private void Eventi_ZaboravljenaLozinka(object sender, EventArgs e) { prijava1.Hide(); zaboravljena_lozinka1.Show(); registracija1.Hide(); } private void Eventi_RegistrirajSe(object sender, EventArgs e) { prijava1.Hide(); zaboravljena_lozinka1.Hide(); registracija1.Show(); } private void Eventi_NatragNaPrijavu(object sender, EventArgs e) { zaboravljena_lozinka1.Hide(); registracija1.Hide(); prijava1.Show(); } private void Eventi_UspjesnaPrijavaStudent(object sender, EventArgsKorisnik e) { prijava1.Hide(); zaboravljena_lozinka1.Hide(); registracija1.Hide(); this.Visible = false; GlavniIzbornik_Student stud = new GlavniIzbornik_Student(e.PrijavljeniKorisnik); stud.ShowDialog(); this.Close(); //MessageBox.Show("Ulogiran kao student!"); } private void Eventi_UspjesnaPrijavaProfesor(object sender, EventArgsKorisnik e) { prijava1.Hide(); zaboravljena_lozinka1.Hide(); registracija1.Hide(); this.Visible = false; GlavniIzbornik_Profesor prof = new GlavniIzbornik_Profesor(e.PrijavljeniKorisnik); prof.ShowDialog(); this.Close(); //MessageBox.Show("Ulogiran kao profesor!"); } private void Eventi_Izlaz(object sender, EventArgs e) { this.Close(); } private void StartupForma_Load(object sender, EventArgs e) { prijava1.Visible = true; registracija1.Visible = false; zaboravljena_lozinka1.Visible = false; } } }
28.204301
94
0.61952
[ "MIT" ]
NovakVed/cs-learning
CSeLearning/PocetniIzbornik.cs
2,625
C#
namespace ClassLib057 { public class Class044 { public static string Property => "ClassLib057"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib057/Class044.cs
120
C#
using Microsoft.Extensions.Logging; using Servicebus.JobScheduler.Core.Contracts; using Servicebus.JobScheduler.ExampleApp.Common; using Servicebus.JobScheduler.ExampleApp.Messages; using System; using System.Threading; using System.Threading.Tasks; namespace Servicebus.JobScheduler.ExampleApp.Emulators { public class UpsertsClientSimulator { public static async Task Run(IMessageBus<Topics, Subscriptions> bus, int initialRuleCount, TimeSpan delayBetweenUpserts, int maxConcurrentRules, string runId, IRepository<JobDefinition> repo, ILogger logger, int? maxUpserts, TimeSpan ruleInterval, CancellationToken token) { var totalRulesCount = 0; logger.LogInformation($"Running Tester Client"); while (!token.IsCancellationRequested && (!maxUpserts.HasValue || maxUpserts.Value > totalRulesCount)) { var id = $"{runId}@{(totalRulesCount % maxConcurrentRules)}"; var rule = new JobDefinition { Id = id.ToString(), Name = $"TestRule {id}", //WindowTimeRangeSeconds = (int)ruleInterval.TotalSeconds, //Schedule = new JobSchedule { PeriodicJob = true, RunIntervalSeconds = (int)ruleInterval.TotalSeconds }, //Schedule = new JobSchedule { PeriodicJob = true, CronSchedulingExpression = "*/5 * * * *" }, Schedule = new JobSchedule { PeriodicJob = true, CronSchedulingExpression = "*/5 * * * *", RunIntervalSeconds = 6 * 60 }, RuleId = id.ToString(), RunId = runId, LastRunWindowUpperBound = null,// SkipNextWindowValidation = true, //BehaviorMode = JobDefination.RuleBehaviorMode.DisabledAfterFirstJobOutput, BehaviorMode = JobDefinition.JobBehaviorMode.Simple, Status = JobStatus.Enabled }; logger.LogInformation($"****************************"); logger.LogCritical($"TEST - Upserting Rule {rule.RuleId}"); logger.LogInformation($"****************************"); var savedRule = await repo.Upsert(rule); await bus.PublishAsync(savedRule, Topics.JobDefinitionChange); totalRulesCount++; if (totalRulesCount >= initialRuleCount) { await Task.Delay(delayBetweenUpserts, token); } } logger.LogInformation("Tester Client existed"); } } }
49.54717
280
0.589109
[ "MIT" ]
lilyanc02/Servicebus-JobScheduler
src/Servicebus.JobScheduler.ExampleApp/UpsertsClientSimulator.cs
2,626
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Sixeyed.Caching.Extensions; namespace Sixeyed.Caching.Tests.Extensions { [TestClass] public class StringExtensionsTests { [TestMethod] public void FormatWith() { var format = "{0}_{1}"; var arg1 = Guid.NewGuid(); var arg2 = new Random().Next(); var expected = arg1 + "_" + arg2; Assert.AreEqual(expected, format.FormatWith(arg1, arg2)); format = Guid.NewGuid().ToString(); expected = format; Assert.AreEqual(expected, format.FormatWith(null)); Assert.AreEqual(expected, format.FormatWith(new object[] {})); } [TestMethod] public void IsNullOrEmpty() { var empty = string.Empty; Assert.IsTrue(empty.IsNullOrEmpty()); empty = null; Assert.IsTrue(empty.IsNullOrEmpty()); var notEmpty = Guid.NewGuid().ToString(); Assert.IsFalse(notEmpty.IsNullOrEmpty()); var whitespace = " "; Assert.IsFalse(whitespace.IsNullOrEmpty()); } [TestMethod] public void IsNullOrWhitespace() { var empty = string.Empty; Assert.IsTrue(empty.IsNullOrWhitespace()); empty = null; Assert.IsTrue(empty.IsNullOrEmpty()); var notEmpty = Guid.NewGuid().ToString(); Assert.IsFalse(notEmpty.IsNullOrWhitespace()); var whitespace = " "; Assert.IsTrue(whitespace.IsNullOrWhitespace()); } } }
33.294118
75
0.545347
[ "MIT" ]
YinfengWang/caching
Sixeyed.Caching.Tests/Extensions/StringExtensionsTests.cs
1,700
C#
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Globalization; using System.ComponentModel; using System.Net; namespace TAlex.Testcheck.Core.Questions { /// <summary> /// Provides a base class for different types of questions, /// such as multiple choice, true/false, matching, etc. /// </summary> [Serializable] public abstract class Question : INotifyPropertyChanged, ICloneable, IXmlSerializable { #region Fields private const string TitleElemName = "Title"; private const string DescriptionElemName = "Description"; private const string PointsElemName = "Points"; private string _title = String.Empty; private string _description = String.Empty; private decimal _points = 1; #endregion #region Properties public string Title { get { return _title; } set { _title = value; } } public string Description { get { return _description; } set { _description = value; OnPropertyChanged("Description"); } } public decimal Points { get { return _points; } set { if (value < 0) throw new ArgumentOutOfRangeException("Points"); _points = value; } } public abstract bool CanCheck { get; } [XmlIgnore] public abstract string TypeName { get; } #endregion #region Events [field: NonSerialized] public event EventHandler CanCheckChanged; #endregion #region Constructors public Question() { Description = String.Empty; } protected Question(Question question) { Title = question.Title; Description = question.Description; Points = question.Points; } #endregion #region Methods public abstract decimal Check(); XmlSchema IXmlSerializable.GetSchema() { return null; } public void ReadXml(XmlReader reader) { XmlDocument doc = new XmlDocument() { InnerXml = reader.ReadOuterXml() }; XmlElement element = doc.DocumentElement; ReadXml(element); } protected virtual void ReadXml(XmlElement element) { XmlElement titleElem = element[TitleElemName]; if (titleElem != null) Title = titleElem.InnerText; Description = WebUtility.HtmlDecode(element[DescriptionElemName].InnerXml).Replace("\n", Environment.NewLine); XmlElement pointsElem = element[PointsElemName]; if (pointsElem != null) Points = decimal.Parse(pointsElem.InnerText, CultureInfo.InvariantCulture); } public virtual void WriteXml(XmlWriter writer) { if (!String.IsNullOrEmpty(Title)) { writer.WriteElementString(TitleElemName, Title); } writer.WriteStartElement(DescriptionElemName); writer.WriteString(Description); writer.WriteEndElement(); writer.WriteElementString(PointsElemName, Points.ToString(CultureInfo.InvariantCulture)); } public override int GetHashCode() { int hashCode = 0; if (_title != null) hashCode = _title.GetHashCode(); hashCode ^= _description.GetHashCode(); hashCode ^= _points.GetHashCode(); return hashCode; } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; Question q = (Question)obj; if (_title != q._title) return false; if (_description != q._description) return false; if (_points != q._points) return false; return true; } public abstract Object Clone(); protected virtual void OnCanCheckChanged() { var @event = CanCheckChanged; if (@event != null) { @event(this, new EventArgs()); } } #endregion #region INotifyPropertyChanged Members [field:NonSerialized] public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }
25.238095
123
0.517358
[ "MIT" ]
T-Alex/Testcheck
Testcheck.Core/Questions/Question.cs
5,302
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Vector_; namespace Vectors_CAH { class Program { static void Main(string[] args) { Vector u = new Vector(new List<double> { 1, 5, 3 }); Vector v = new Vector(new List<double> { 4, 6, 9 }); List<Vector> UandV = new List<Vector> { v, u }; Vector result_add = v.add(UandV); Out(result_add); Vector scalar = v.scalar_multiply(5); Out(scalar); Console.WriteLine(v.dot_product(UandV)); Out(v.convex_combination(UandV, 0.5, 0.5)); Console.WriteLine("Geo dot product is: "+v.Geometric_dot_product(v, u,30)); Console.WriteLine(u.find_Angle(v)+" radians"); Console.ReadKey(); } static void Out(Vector v) { Console.WriteLine(string.Join(",", v.v)); } } }
30.71875
87
0.560529
[ "MIT" ]
sps-lco-2020-21/vector-introductions-LimESPS
Vectors_CAH/Vectors_CAH/Program.cs
985
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #pragma warning disable SA1402 // File may only contain a single type #pragma warning disable SA1649 // File name should match first type name using System.Threading; namespace Stride.Engine.Events { /// <summary> /// Used mostly for debug, to identify events /// </summary> internal static class EventKeyCounter { private static long eventKeysCounter; public static ulong New() { return (ulong)Interlocked.Increment(ref eventKeysCounter); } } public sealed class EventKey<T> : EventKeyBase<T> { public EventKey(string category = "General", string eventName = "Event") : base(category, eventName) { } /// <summary> /// Broadcasts the event to all the receivers /// </summary> public void Broadcast(T data) { InternalBroadcast(data); } } /// <summary> /// Creates a new EventKey used to broadcast events. /// </summary> public sealed class EventKey : EventKeyBase<bool> { public EventKey(string category = "General", string eventName = "Event") : base(category, eventName) { } /// <summary> /// Broadcasts the event to all the receivers /// </summary> public void Broadcast() { InternalBroadcast(true); } } }
30.2
163
0.613486
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Engine/Engine/Events/EventKey.cs
1,661
C#
using System.Threading.Tasks; namespace my_robot_zone_robot_server.MessageHandlers { public class DefaultMessageHandler : IMessageHandler { private readonly ILogger _logger; public DefaultMessageHandler(ILogger logger) { _logger = logger; } public Task<bool> StartAsync() { _logger.Log("Default message handler started"); return Task.FromResult(true); } public Task HandleMessageAsync(MRZMessage message) { _logger.Log($"Received FeatureId = '{message.FeatureId}', Payload = '{message.Payload}'"); return Task.FromResult(true); } public Task StopAsync() { _logger.Log("Default message handler stopped"); return Task.FromResult(true); } } }
26.40625
102
0.59645
[ "MIT" ]
myrobotzone/my-robot-zone-owi-arm
my-robot-zone-owi-arm/my-robot-zone-robot-server/MessageHandlers/DefaultMessageHandler.cs
847
C#
using System; using Magellan.Routing; namespace Magellan { /// <summary> /// Represents a route request, which is given to an <see cref="INavigator"/> to execute. /// </summary> public class NavigationRequest { private readonly Uri uri; private readonly RouteValueDictionary routeData; /// <summary> /// Initializes a new instance of the <see cref="NavigationRequest"/> class. /// </summary> /// <param name="routeData">The route data.</param> public NavigationRequest(RouteValueDictionary routeData) : this(null, routeData) { } /// <summary> /// Initializes a new instance of the <see cref="NavigationRequest"/> class. /// </summary> /// <param name="uri">The URI being navigated to. Can be null to resolve a path from route data.</param> public NavigationRequest(Uri uri) : this(uri, null) { } /// <summary> /// Initializes a new instance of the <see cref="NavigationRequest"/> class. /// </summary> /// <param name="uri">The URI being navigated to. Can be null to resolve a path from route data.</param> /// <param name="routeData">The route data.</param> public NavigationRequest(Uri uri, RouteValueDictionary routeData) { this.uri = uri; this.routeData = routeData; } /// <summary> /// Gets the URI. Can be null if the route is meant to be resolved from route data. /// </summary> /// <value>The URI.</value> public Uri Uri { get { return uri; } } /// <summary> /// Gets the route data. /// </summary> /// <value>The route data.</value> public RouteValueDictionary RouteData { get { return routeData; } } } }
32.135593
112
0.565401
[ "MIT" ]
rog1039/magellan-framework
src/Magellan/NavigationRequest.cs
1,898
C#
using FluentAssertions; using Payments.Application.Payments.Commands.UpdatePayment; using System; using System.Net; using System.Threading.Tasks; using Xunit; namespace Payments.API.IntegrationTests.Controllers.Payments { public class Update : IClassFixture<CustomWebApplicationFactory<Startup>> { private readonly CustomWebApplicationFactory<Startup> _factory; private readonly string _paymentBaseUri; public Update(CustomWebApplicationFactory<Startup> factory) { _factory = factory; _paymentBaseUri = $"/api/v1/payments"; } [Fact] public async Task GivenValidUpdatePaymentCommand_ReturnsSuccessCode() { var client = await _factory.GetAuthenticatedClientAsync(); var validId = await new Create(_factory).GivenValidCreatePaymentCommand_ReturnsSuccessCode(); var command = new UpdatePaymentCommand { Id = Convert.ToInt64(validId), Name = $"Do this thing - {DateTime.Now.Ticks}.", IsComplete = true }; var content = IntegrationTestHelper.GetRequestContent(command); var response = await client.PutAsync($"{_paymentBaseUri}/{command.Id}", content); response.EnsureSuccessStatusCode(); } [Fact] public async Task GivenValidUpdatePaymentCommand_ReturnsBadRequest() { var client = await _factory.GetAuthenticatedClientAsync(); var validId = await new Create(_factory).GivenValidCreatePaymentCommand_ReturnsSuccessCode(); var command = new UpdatePaymentCommand { Id = Convert.ToInt64(validId), Name = "Do this thing.", IsComplete = true }; var content = IntegrationTestHelper.GetRequestContent(command); var response = await client.PutAsync($"{_paymentBaseUri}/{command.Id}", content); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); } } }
35.305085
105
0.641383
[ "MIT" ]
vinaykarora/payment-processor
tests/WebUI.IntegrationTests/Payments.API.IntegrationTests/Controllers/Payments/Update.cs
2,085
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Data; using System.Windows.Media; using System.Windows.Threading; using WeUiSharp.DesignTime; namespace WeUiSharp { public class ThemeManager : DependencyObject { internal const string LightKey = "Light"; internal const string DarkKey = "Dark"; private static readonly RoutedEventArgs _actualThemeChangedEventArgs; private static readonly Dictionary<string, ResourceDictionary> _defaultThemeDictionaries = new Dictionary<string, ResourceDictionary>(); private readonly Data _data; private bool _isInitialized; private bool _applicationInitialized; static ThemeManager() { ThemeProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(OnThemeChanged)); _actualThemeChangedEventArgs = new RoutedEventArgs(ActualThemeChangedEvent); //if (DesignMode.DesignModeEnabled) //{ // _ = GetDefaultThemeDictionary(LightKey); // _ = GetDefaultThemeDictionary(DarkKey); //} } private ThemeManager() { _data = new Data(this); } #region ApplicationTheme /// <summary> /// Identifies the ApplicationTheme dependency property. /// </summary> public static readonly DependencyProperty ApplicationThemeProperty = DependencyProperty.Register( nameof(ApplicationTheme), typeof(ApplicationTheme?), typeof(ThemeManager), new PropertyMetadata(OnApplicationThemeChanged)); /// <summary> /// Gets or sets a value that determines the light-dark preference for the overall /// theme of an app. /// </summary> /// <returns> /// A value of the enumeration. The initial value is the default theme set by the /// user in Windows settings. /// </returns> public ApplicationTheme? ApplicationTheme { get => (ApplicationTheme?)GetValue(ApplicationThemeProperty); set => SetValue(ApplicationThemeProperty, value); } private static void OnApplicationThemeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((ThemeManager)d).UpdateActualApplicationTheme(); } #endregion #region ActualApplicationTheme private static readonly DependencyPropertyKey ActualApplicationThemePropertyKey = DependencyProperty.RegisterReadOnly( nameof(ActualApplicationTheme), typeof(ApplicationTheme), typeof(ThemeManager), new PropertyMetadata(WeUiSharp.ApplicationTheme.Light, OnActualApplicationThemeChanged)); public static readonly DependencyProperty ActualApplicationThemeProperty = ActualApplicationThemePropertyKey.DependencyProperty; public ApplicationTheme ActualApplicationTheme { get => (ApplicationTheme)GetValue(ActualApplicationThemeProperty); private set => SetValue(ActualApplicationThemePropertyKey, value); } private static void OnActualApplicationThemeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var tm = (ThemeManager)d; var newValue = (ApplicationTheme)e.NewValue; switch (newValue) { case WeUiSharp.ApplicationTheme.Light: tm._defaultActualTheme = ElementTheme.Light; break; case WeUiSharp.ApplicationTheme.Dark: tm._defaultActualTheme = ElementTheme.Dark; break; } tm._data.ActualApplicationTheme = newValue; tm.ApplyApplicationTheme(); tm.ActualApplicationThemeChanged?.Invoke(tm, null); } private void UpdateActualApplicationTheme() { if (UsingSystemTheme) { ActualApplicationTheme = GetDefaultAppTheme(); } else { ActualApplicationTheme = ApplicationTheme ?? WeUiSharp.ApplicationTheme.Light; } } private void ApplyApplicationTheme() { if (_applicationInitialized) { Debug.Assert(ThemeResources.Current != null); ThemeResources.Current.ApplyApplicationTheme(ActualApplicationTheme); } } #endregion #region RequestedTheme /// <summary> /// Gets the UI theme that is used by the UIElement (and its child elements) /// for resource determination. The UI theme you specify with RequestedTheme can /// override the app-level RequestedTheme. /// </summary> /// <param name="element">The element from which to read the property value.</param> /// <returns>A value of the enumeration, for example **Light**.</returns> public static ElementTheme GetRequestedTheme(FrameworkElement element) { return (ElementTheme)element.GetValue(RequestedThemeProperty); } /// <summary> /// Sets the UI theme that is used by the UIElement (and its child elements) /// for resource determination. The UI theme you specify with RequestedTheme can /// override the app-level RequestedTheme. /// </summary> /// <param name="element">The element on which to set the attached property.</param> /// <param name="value">The property value to set.</param> public static void SetRequestedTheme(FrameworkElement element, ElementTheme value) { element.SetValue(RequestedThemeProperty, value); } /// <summary> /// Identifies the RequestedTheme dependency property. /// </summary> public static readonly DependencyProperty RequestedThemeProperty = DependencyProperty.RegisterAttached( "RequestedTheme", typeof(ElementTheme), typeof(ThemeManager), new PropertyMetadata(ElementTheme.Default, OnRequestedThemeChanged)); private static void OnRequestedThemeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = (FrameworkElement)d; if (element.IsInitialized) { ApplyRequestedTheme(element); } else { SetSubscribedToInitialized(element, true); } } private static void ApplyRequestedTheme(FrameworkElement element) { var resources = element.Resources; var requestedTheme = GetRequestedTheme(element); ThemeResources.Current.ApplyElementTheme(resources, requestedTheme); if (element is Window window) { UpdateWindowTheme(window); } else if (requestedTheme != ElementTheme.Default) { SetTheme(element, requestedTheme); } else { element.ClearValue(ThemeProperty); } } #endregion #region Theme private static readonly DependencyProperty ThemeProperty = DependencyProperty.RegisterAttached( "Theme", typeof(ElementTheme), typeof(ThemeManager), new FrameworkPropertyMetadata( ElementTheme.Default, FrameworkPropertyMetadataOptions.Inherits)); private static void SetTheme(FrameworkElement element, ElementTheme value) { element.SetValue(ThemeProperty, value); } private static void OnThemeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is FrameworkElement fe) { UpdateActualTheme(fe, (ElementTheme)e.NewValue); } } private static void UpdateWindowTheme(Window window) { var requestedTheme = GetRequestedTheme(window); if (requestedTheme != ElementTheme.Default) { SetTheme(window, requestedTheme); } else { SetTheme(window, Current._defaultActualTheme); } } #endregion #region ActualTheme /// <summary> /// Gets the UI theme that is currently used by the element, which might be different /// than the RequestedTheme. /// </summary> /// <param name="element">The element from which to read the property value.</param> /// <returns>A value of the enumeration, for example **Light**.</returns> public static ElementTheme GetActualTheme(FrameworkElement element) { return (ElementTheme)element.GetValue(ActualThemeProperty); } private static readonly DependencyPropertyKey ActualThemePropertyKey = DependencyProperty.RegisterAttachedReadOnly( "ActualTheme", typeof(ElementTheme), typeof(ThemeManager), new FrameworkPropertyMetadata( ElementTheme.Light, OnActualThemeChanged)); /// <summary> /// Identifies the ActualTheme dependency property. /// </summary> public static readonly DependencyProperty ActualThemeProperty = ActualThemePropertyKey.DependencyProperty; private static void OnActualThemeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is FrameworkElement fe) { #if DEBUG if (DependencyPropertyHelper.GetValueSource(d, ThemeProperty).BaseValueSource == BaseValueSource.Default) { Debug.Assert((ElementTheme)e.NewValue == Current._defaultActualTheme); } #endif if (GetHasThemeResources(fe)) { UpdateThemeResourcesForElement(fe); } RaiseActualThemeChanged(fe); } } private static void UpdateActualTheme(FrameworkElement element, ElementTheme theme) { ElementTheme actualTheme; if (theme != ElementTheme.Default) { actualTheme = theme; } else { actualTheme = Current._defaultActualTheme; } element.SetValue(ActualThemePropertyKey, actualTheme); } private ElementTheme _defaultActualTheme = ElementTheme.Light; #endregion #region ActualThemeChanged public static readonly RoutedEvent ActualThemeChangedEvent = EventManager.RegisterRoutedEvent( "ActualThemeChanged", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ThemeManager)); public static void AddActualThemeChangedHandler(FrameworkElement element, RoutedEventHandler handler) { element.AddHandler(ActualThemeChangedEvent, handler); } public static void RemoveActualThemeChangedHandler(FrameworkElement element, RoutedEventHandler handler) { element.RemoveHandler(ActualThemeChangedEvent, handler); } private static void RaiseActualThemeChanged(FrameworkElement element) { element.RaiseEvent(_actualThemeChangedEventArgs); } #endregion #region IsThemeAware public static bool GetIsThemeAware(Window window) { return (bool)window.GetValue(IsThemeAwareProperty); } public static void SetIsThemeAware(Window window, bool value) { window.SetValue(IsThemeAwareProperty, value); } public static readonly DependencyProperty IsThemeAwareProperty = DependencyProperty.RegisterAttached( "IsThemeAware", typeof(bool), typeof(ThemeManager), new PropertyMetadata(OnIsThemeAwareChanged)); private static void OnIsThemeAwareChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Window window) { if ((bool)e.NewValue) { window.SetBinding( InheritedApplicationThemeProperty, new Binding(nameof(ActualApplicationTheme)) { Source = Current._data }); UpdateWindowTheme((Window)d); } else { window.ClearValue(InheritedApplicationThemeProperty); } } } private static readonly DependencyProperty InheritedApplicationThemeProperty = DependencyProperty.RegisterAttached( "InheritedApplicationTheme", typeof(ApplicationTheme), typeof(ThemeManager), new PropertyMetadata(WeUiSharp.ApplicationTheme.Light, OnInheritedApplicationThemeChanged)); private static void OnInheritedApplicationThemeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { UpdateWindowTheme((Window)d); } #endregion #region HasThemeResources public static readonly DependencyProperty HasThemeResourcesProperty = DependencyProperty.RegisterAttached( "HasThemeResources", typeof(bool), typeof(ThemeManager), new PropertyMetadata(OnHasThemeResourcesChanged)); public static bool GetHasThemeResources(FrameworkElement element) { return (bool)element.GetValue(HasThemeResourcesProperty); } public static void SetHasThemeResources(FrameworkElement element, bool value) { element.SetValue(HasThemeResourcesProperty, value); } private static void OnHasThemeResourcesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = (FrameworkElement)d; if ((bool)e.NewValue) { if (element.IsInitialized) { UpdateThemeResourcesForElement(element); } else { SetSubscribedToInitialized(element, true); } } else { UpdateSubscribedToInitialized(element); } } private static void UpdateThemeResourcesForElement(FrameworkElement element) { UpdateElementThemeResources(element.Resources, GetEffectiveThemeKey(element)); } private static void UpdateElementThemeResources(ResourceDictionary resources, string themeKey) { if (resources is ResourceDictionaryEx themeResources) { themeResources.Update(themeKey); } foreach (ResourceDictionary dictionary in resources.MergedDictionaries) { UpdateElementThemeResources(dictionary, themeKey); } } private static string GetEffectiveThemeKey(FrameworkElement element) { switch (GetActualTheme(element)) { case ElementTheme.Light: return LightKey; case ElementTheme.Dark: return DarkKey; } throw new InvalidOperationException(); } #endregion #region SubscribedToInitialized private static readonly DependencyProperty SubscribedToInitializedProperty = DependencyProperty.RegisterAttached( "SubscribedToInitialized", typeof(bool), typeof(ThemeManager), new PropertyMetadata(false, OnSubscribedToInitializedChanged)); private static void SetSubscribedToInitialized(FrameworkElement element, bool value) { element.SetValue(SubscribedToInitializedProperty, value); } private static void OnSubscribedToInitializedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = (FrameworkElement)d; if ((bool)e.NewValue) { element.Initialized += OnElementInitialized; } else { element.Initialized -= OnElementInitialized; } } private static void UpdateSubscribedToInitialized(FrameworkElement element) { if (ShouldSubscribeToInitialized(element)) { SetSubscribedToInitialized(element, true); } else { element.ClearValue(SubscribedToInitializedProperty); } } private static bool ShouldSubscribeToInitialized(FrameworkElement element) { return !element.IsInitialized && (GetRequestedTheme(element) != ElementTheme.Default || GetHasThemeResources(element)); } private static void OnElementInitialized(object sender, EventArgs e) { var element = (FrameworkElement)sender; element.ClearValue(SubscribedToInitializedProperty); if (GetRequestedTheme(element) != ElementTheme.Default) { ApplyRequestedTheme(element); } if (GetHasThemeResources(element)) { UpdateThemeResourcesForElement(element); } } #endregion public static ThemeManager Current { get; } = new ThemeManager(); internal bool UsingSystemTheme => ApplicationTheme == null; public TypedEventHandler<ThemeManager, object> ActualApplicationThemeChanged; internal static void UpdateThemeBrushes(ResourceDictionary colors) { foreach (var themeDictionary in _defaultThemeDictionaries.Values) { ColorsHelper.UpdateBrushes(themeDictionary, colors); } } internal static ResourceDictionary GetDefaultThemeDictionary(string key) { if (!_defaultThemeDictionaries.TryGetValue(key, out ResourceDictionary dictionary)) { dictionary = new ResourceDictionary { Source = GetDefaultSource(key) }; _defaultThemeDictionaries[key] = dictionary; } return dictionary; } internal static void SetDefaultThemeDictionary(string key, ResourceDictionary dictionary) { _defaultThemeDictionaries[key] = dictionary; } private static ApplicationTheme GetDefaultAppTheme() { return ColorsHelper.Current.SystemTheme.GetValueOrDefault(WeUiSharp.ApplicationTheme.Light); } private static Uri GetDefaultSource(string theme) { return PackUriHelper.GetAbsoluteUri($"ThemeResources/{theme}.xaml"); } private static ResourceDictionary FindDictionary(ResourceDictionary parent, Uri source) { if (parent.Source == source) { return parent; } else { foreach (var md in parent.MergedDictionaries) { if (md != null) { if (md.Source == source) { return md; } else { var result = FindDictionary(md, source); if (result != null) { return result; } } } } } return null; } internal void Initialize() { if (_isInitialized) { return; } Debug.Assert(ThemeResources.Current != null); SystemParameters.StaticPropertyChanged += OnSystemParametersChanged; if (Application.Current != null) { var appResources = Application.Current.Resources; appResources.MergedDictionaries.RemoveAll<IntellisenseResourcesBase>(); ColorsHelper.Current.SystemThemeChanged += OnSystemThemeChanged; appResources.MergedDictionaries.Insert(0, ColorsHelper.Current.Colors); UpdateActualApplicationTheme(); _applicationInitialized = true; ApplyApplicationTheme(); } _isInitialized = true; } private void OnSystemThemeChanged(object sender, EventArgs e) { if (UsingSystemTheme) { UpdateActualApplicationTheme(); } } private void OnSystemParametersChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(SystemParameters.HighContrast)) { RunOnMainThread(ApplyApplicationTheme); } } private void RunOnMainThread(Action action) { if (Dispatcher.CheckAccess()) { action(); } else { Dispatcher.BeginInvoke(action); } } private class Data : INotifyPropertyChanged { public Data(ThemeManager owner) { _actualApplicationTheme = owner.ActualApplicationTheme; } public ApplicationTheme ActualApplicationTheme { get => _actualApplicationTheme; set => Set(ref _actualApplicationTheme, value); } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged([CallerMemberName]string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null) { if (!Equals(storage, value)) { storage = value; RaisePropertyChanged(propertyName); } } private ApplicationTheme _actualApplicationTheme; } } /// <summary> /// Declares the theme preference for an app. /// </summary> public enum ApplicationTheme { /// <summary> /// Use the **Light** default theme. /// </summary> Light = 0, /// <summary> /// Use the **Dark** default theme. /// </summary> Dark = 1 } /// <summary> /// Specifies a UI theme that should be used for individual UIElement parts of an app UI. /// </summary> public enum ElementTheme { /// <summary> /// Use the Application.RequestedTheme value for the element. This is the default. /// </summary> Default = 0, /// <summary> /// Use the **Light** default theme. /// </summary> Light = 1, /// <summary> /// Use the **Dark** default theme. /// </summary> Dark = 2 } }
33.211034
144
0.576751
[ "MIT" ]
IUpdatable/WeUiSharp
Src/WeUiSharp/ThemeManager.cs
24,080
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using EOS.Client.Models; using EOS.Client.Utils; using Action = EOS.Client.Models.Action; using Hex = EOS.Client.Cryptography.Hex; namespace EOS.Client { public class EosClient { public EosClient(ISignatureProvider signatureProvider) : this(new Uri("http://localhost:8888"), signatureProvider) { } public EosClient(Uri nodeUri, ISignatureProvider signatureProvider) { this.Api = new EosApi(nodeUri); this.signatureProvider = signatureProvider; this.serializer = new EosBinarySerializer(this.Api); } public IEosApi Api { get; } public async Task<string> PushActionsAsync(IEnumerable<Action> actions) { var chainInfo = await Api.GetInfoAsync(); var blockInfo = await Api.GetBlockAsync(chainInfo.LastIrreversibleBlockId); var transaction = new Transaction { RefBlockNum = chainInfo.LastIrreversibleBlockNum, RefBlockPrefix = blockInfo.RefBlockPrefix, Expiration = chainInfo.HeadBlockTime.AddSeconds(30), Actions = actions }; return await PushTransactionAsync(transaction, chainInfo.ChainId); } public async Task<string> PushTransactionAsync(Transaction transaction) { cachedChainInfo = cachedChainInfo ?? await Api.GetInfoAsync(); return await PushTransactionAsync(transaction, cachedChainInfo.ChainId); } async Task<string> PushTransactionAsync(Transaction transaction, string chainId) { var packedTransaction = await serializer.SerializeAsync(transaction); var signDigest = new[] { Hex.Decode(chainId), packedTransaction, new byte[32] }; var keysInfo = await Api.GetRequiredKeysAsync(transaction, signatureProvider.AvailableKeys); var signatures = await signatureProvider.SignAsync(signDigest.Flattern(), keysInfo.RequiredKeys); var res = await Api.PushTransactionAsync(new SignedTransaction { Transaction = transaction, Signatures = signatures }); return res.TransactionId; } private readonly ISignatureProvider signatureProvider; private readonly EosBinarySerializer serializer; ChainInfo cachedChainInfo; } }
34.116883
109
0.620099
[ "MIT" ]
SNIKO/eosnet
src/EOS.Client/EosClient.cs
2,629
C#
using System; using System.IO; using System.Net; using System.Threading.Tasks; using Kudu.Contracts.SiteExtensions; using Kudu.Contracts.Tracing; using Kudu.Core.Infrastructure; using Kudu.Core.Settings; using Kudu.Core.Tracing; using Newtonsoft.Json.Linq; namespace Kudu.Core.SiteExtensions { public class SiteExtensionStatus { private const string _statusSettingsFileName = "SiteExtensionStatus.json"; private const string _provisioningStateSetting = "provisioningState"; private const string _commentMessageSetting = "comment"; private const string _statusSetting = "status"; private const string _operationSetting = "operation"; private const string _siteExtensionType = "siteExtensionType"; private string _filePath; private JsonSettings _jsonSettings; private ITracer _tracer; public string ProvisioningState { get { return SafeRead(_provisioningStateSetting); } set { SafeWrite(_provisioningStateSetting, value); } } public string Comment { get { return SafeRead(_commentMessageSetting); } set { SafeWrite(_commentMessageSetting, value); } } public HttpStatusCode Status { get { string statusStr = SafeRead(_statusSetting); HttpStatusCode statusCode = HttpStatusCode.OK; Enum.TryParse<HttpStatusCode>(statusStr, out statusCode); return statusCode; } set { SafeWrite(_statusSetting, Enum.GetName(typeof(HttpStatusCode), value)); } } public SiteExtensionInfo.SiteExtensionType Type { get { string typeStr = SafeRead(_siteExtensionType); SiteExtensionInfo.SiteExtensionType type = SiteExtensionInfo.SiteExtensionType.Gallery; Enum.TryParse<SiteExtensionInfo.SiteExtensionType>(typeStr, out type); return type; } set { SafeWrite(_siteExtensionType, Enum.GetName(typeof(SiteExtensionInfo.SiteExtensionType), value)); } } /// <summary> /// <para>Property to indicate current operation</para> /// <para>Empty/null means there is no recent operation</para> /// </summary> public string Operation { get { return _jsonSettings.GetValue(_operationSetting); } set { SafeWrite(_operationSetting, value); } } public SiteExtensionStatus(string rootPath, string id, ITracer tracer) { _filePath = GetFilePath(rootPath, id); _jsonSettings = new JsonSettings(_filePath); _tracer = tracer; } public void FillSiteExtensionInfo(SiteExtensionInfo info, string defaultProvisionState = null) { info.ProvisioningState = ProvisioningState ?? defaultProvisionState; info.Comment = Comment; } public void ReadSiteExtensionInfo(SiteExtensionInfo info) { ProvisioningState = info.ProvisioningState; Comment = info.Comment; } public async Task RemoveStatus() { try { string dirName = Path.GetDirectoryName(_filePath); if (FileSystemHelpers.DirectoryExists(dirName)) { FileSystemHelpers.DeleteDirectoryContentsSafe(dirName); // call DeleteDirectorySafe directly would sometime causing "Access denied" on folder // work-around: remove content and wait briefly before delete folder await Task.Delay(300); FileSystemHelpers.DeleteDirectorySafe(dirName); } } catch (Exception ex) { // no-op _tracer.TraceError(ex); } } public bool IsTerminalStatus() { return string.Equals(Constants.SiteExtensionProvisioningStateSucceeded, ProvisioningState, StringComparison.OrdinalIgnoreCase) || string.Equals(Constants.SiteExtensionProvisioningStateFailed, ProvisioningState, StringComparison.OrdinalIgnoreCase) || string.Equals(Constants.SiteExtensionProvisioningStateCanceled, ProvisioningState, StringComparison.OrdinalIgnoreCase); } /// <param name="siteExtensionRoot">should be $ROOT\SiteExtensions</param> public bool IsRestartRequired(string siteExtensionRoot) { return this.IsSiteExtensionRequireRestart(siteExtensionRoot); } /// <summary> /// <para>Loop thru all site extension settings files under 'siteExtensionStatusRoot', check if there is any successful installation</para> /// <para>if not install to webroot, will trigger restart; if install to webroot and with applicationHost.xdt file, trigger restart.</para> /// </summary> /// <param name="siteExtensionStatusRoot">should be $ROOT\site\siteextensions</param> /// <param name="siteExtensionRoot">should be $ROOT\SiteExtensions</param> public static bool IsAnyInstallationRequireRestart(string siteExtensionStatusRoot, string siteExtensionRoot, ITracer tracer, IAnalytics analytics) { try { using (tracer.Step("Checking if there is any installation require site restart ...")) { string[] packageDirs = FileSystemHelpers.GetDirectories(siteExtensionStatusRoot); foreach (var dir in packageDirs) { try { DirectoryInfo dirInfo = new DirectoryInfo(dir); string[] settingFile = FileSystemHelpers.GetFiles(dir, _statusSettingsFileName); foreach (var file in settingFile) { var statusSettings = new SiteExtensionStatus(siteExtensionStatusRoot, dirInfo.Name, tracer); if (statusSettings.IsSiteExtensionRequireRestart(siteExtensionRoot)) { return true; } } } catch (Exception ex) { analytics.UnexpectedException(ex, trace: false); tracer.TraceError(ex, "Failed to query {0} under {1}, continus to check others ...", _statusSettingsFileName, dir); } } } } catch (Exception ex) { analytics.UnexpectedException(ex, trace: false); tracer.TraceError(ex, "Not able to query directory under {0}", siteExtensionStatusRoot); } return false; } private bool IsSiteExtensionRequireRestart(string siteExtensionRoot) { if (Operation == Constants.SiteExtensionOperationInstall && ProvisioningState == Constants.SiteExtensionProvisioningStateSucceeded) { if (Type != SiteExtensionInfo.SiteExtensionType.WebRoot) { // normal path // if it is not installed to webroot and installation finish successfully, we should restart site return true; } else { // if it is intalled to webroot, restart site ONLY if there is an applicationHost.xdt file under site extension folder DirectoryInfo dirInfo = new DirectoryInfo(Path.GetDirectoryName(_filePath)); // folder name is the id of the package string xdtFilePath = Path.Combine(siteExtensionRoot, dirInfo.Name, Constants.ApplicationHostXdtFileName); return File.Exists(xdtFilePath); } } return false; } private string SafeRead(string key) { try { return _jsonSettings.GetValue(key); } catch (Exception ex) { _tracer.TraceError(ex); // if setting file happen to be invalid, e.g w3wp.exe was kill while writting // treat it as failed, and suggest user to re-install or un-install JObject newSettings = new JObject(); newSettings[_provisioningStateSetting] = Constants.SiteExtensionProvisioningStateFailed; newSettings[_commentMessageSetting] = "Corrupted site extension, please re-install or uninstall extension."; newSettings[_statusSetting] = Enum.GetName(typeof(HttpStatusCode), HttpStatusCode.BadRequest); _jsonSettings.Save(newSettings); } return _jsonSettings.GetValue(key); } private void SafeWrite(string key, JToken value) { try { _jsonSettings.SetValue(key, value); } catch (Exception ex) { _tracer.TraceError(ex); // if setting file happen to be invalid, e.g w3wp.exe was kill while writting // clear all content, start from blank JObject newSettings = new JObject(); newSettings[key] = value; _jsonSettings.Save(newSettings); } } private static string GetFilePath(string rootPath, string id) { return Path.Combine(rootPath, id, _statusSettingsFileName); } } }
41.364017
154
0.578596
[ "Apache-2.0" ]
RajkumarTCS/kudu
Kudu.Core/SiteExtensions/SiteExtensionStatus.cs
9,888
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Digits { class Digits { static void Main(string[] args) { var num = int.Parse(Console.ReadLine()); var thirdDigit = num % 10; var secondDigit = (num / 10) % 10; var firstDigit = num / 100; var rows = firstDigit + secondDigit; var cols = firstDigit + thirdDigit; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (num % 5 == 0) { num -= firstDigit; Console.Write(num + " "); } else if (num % 3 == 0) { num -= secondDigit; Console.Write(num + " "); } else { num += thirdDigit; Console.Write(num + " "); } } Console.WriteLine(); } } } }
26.977778
52
0.360791
[ "MIT" ]
AlexanderPetrovv/Programming-Basics-December-2016
ProgrammingBasicsExam28Aug2016/Digits/Digits.cs
1,216
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using Microsoft.CodeAnalysis.Text; using Roslynator.Text; namespace Roslynator.Testing.Text { internal abstract class TextParser { public static TextParser Default { get; } = new DefaultTextParser(); public abstract TextParserResult GetSpans(string s, IComparer<LinePositionSpanInfo> comparer = null); public abstract (TextSpan span, string text) ReplaceEmptySpan(string s, string replacement); public abstract (TextSpan span, string text1, string text2) ReplaceEmptySpan(string s, string replacement1, string replacement2); private class DefaultTextParser : TextParser { private const string OpenToken = "[|"; private const string CloseToken = "|]"; private const string OpenCloseTokens = OpenToken + CloseToken; private const int TokensLength = 4; public override TextParserResult GetSpans(string s, IComparer<LinePositionSpanInfo> comparer = null) { StringBuilder sb = StringBuilderCache.GetInstance(s.Length - TokensLength); var startPending = false; LinePositionInfo start = default; Stack<LinePositionInfo> stack = null; List<LinePositionSpanInfo> spans = null; int lastPos = 0; int line = 0; int column = 0; int length = s.Length; int i = 0; while (i < length) { switch (s[i]) { case '\r': { if (PeekNextChar() == '\n') { i++; } line++; column = 0; i++; continue; } case '\n': { line++; column = 0; i++; continue; } case '[': { char nextChar = PeekNextChar(); if (nextChar == '|') { sb.Append(s, lastPos, i - lastPos); var start2 = new LinePositionInfo(sb.Length, line, column); if (stack != null) { stack.Push(start2); } else if (!startPending) { start = start2; startPending = true; } else { stack = new Stack<LinePositionInfo>(); stack.Push(start); stack.Push(start2); startPending = false; } i += 2; lastPos = i; continue; } else if (nextChar == '[' && PeekChar(2) == '|' && PeekChar(3) == ']') { i++; column++; CloseSpan(); i += 3; lastPos = i; continue; } break; } case '|': { if (PeekNextChar() == ']') { CloseSpan(); i += 2; lastPos = i; continue; } break; } } column++; i++; } if (startPending || stack?.Count > 0) { throw new InvalidOperationException(); } sb.Append(s, lastPos, s.Length - lastPos); spans?.Sort(comparer ?? LinePositionSpanInfoComparer.Index); return new TextParserResult( StringBuilderCache.GetStringAndFree(sb), spans?.ToImmutableArray() ?? ImmutableArray<LinePositionSpanInfo>.Empty); char PeekNextChar() { return PeekChar(1); } char PeekChar(int offset) { return (i + offset >= s.Length) ? '\0' : s[i + offset]; } void CloseSpan() { if (stack != null) { start = stack.Pop(); } else if (startPending) { startPending = false; } else { throw new InvalidOperationException(); } var end = new LinePositionInfo(sb.Length + i - lastPos, line, column); var span = new LinePositionSpanInfo(start, end); (spans ??= new List<LinePositionSpanInfo>()).Add(span); sb.Append(s, lastPos, i - lastPos); } } public override (TextSpan span, string text) ReplaceEmptySpan(string s, string replacement) { int index = s.IndexOf(OpenCloseTokens, StringComparison.Ordinal); if (index == -1) throw new ArgumentException("Empty span not found.", nameof(s)); var span = new TextSpan(index, replacement.Length); string result = Replace(s, index, replacement); return (span, result); } public override (TextSpan span, string text1, string text2) ReplaceEmptySpan(string s, string replacement1, string replacement2) { int index = s.IndexOf(OpenCloseTokens, StringComparison.Ordinal); if (index == -1) throw new ArgumentException("Empty span not found.", nameof(s)); var span = new TextSpan(index, replacement1.Length); string result1 = Replace(s, index, replacement1); string result2 = Replace(s, index, replacement2); return (span, result1, result2); } private static string Replace(string s, int index, string replacement) { StringBuilder sb = StringBuilderCache.GetInstance(s.Length - TokensLength + replacement.Length) .Append(s, 0, index) .Append(replacement) .Append(s, index + TokensLength, s.Length - index - TokensLength); return StringBuilderCache.GetStringAndFree(sb); } } } }
37.004525
160
0.380655
[ "Apache-2.0" ]
RickeyEstes/Roslynator
src/Tests/Testing.Common/Testing/Text/TextParser.cs
8,180
C#
// <auto-generated> // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. // // For documentation on code generator please visit // https://aka.ms/nrp-code-generation // Please contact wanrpdev@microsoft.com if you need to make changes to this file. // </auto-generated> using System; using Microsoft.Azure.ServiceManagemenet.Common.Models; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Xunit; using Xunit.Abstractions; namespace Commands.Network.Test.ScenarioTests { public class LoadBalancerTestsGenerated : RMTestBase { public XunitTracingInterceptor _logger; public LoadBalancerTestsGenerated(Xunit.Abstractions.ITestOutputHelper output) { _logger = new XunitTracingInterceptor(output); XunitTracingInterceptor.AddToContext(_logger); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestLoadBalancerCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-LoadBalancerCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestLoadBalancerCRUDAllParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-LoadBalancerCRUDAllParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestFrontendIPConfigurationCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-FrontendIPConfigurationCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestFrontendIPConfigurationCRUDAllParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-FrontendIPConfigurationCRUDAllParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestBackendAddressPoolCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-BackendAddressPoolCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestLoadBalancingRuleCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-LoadBalancingRuleCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestLoadBalancingRuleCRUDAllParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-LoadBalancingRuleCRUDAllParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestProbeCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-ProbeCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestProbeCRUDAllParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-ProbeCRUDAllParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestInboundNatRuleCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-InboundNatRuleCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestInboundNatRuleCRUDAllParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-InboundNatRuleCRUDAllParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestInboundNatPoolCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-InboundNatPoolCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestInboundNatPoolCRUDAllParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-InboundNatPoolCRUDAllParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestOutboundRuleCRUDMinimalParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-OutboundRuleCRUDMinimalParameters"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] [Trait(Category.Owner, NrpTeamAlias.slbdev)] public void TestOutboundRuleCRUDAllParameters() { NetworkResourcesController.NewInstance.RunPsTest(_logger, "Test-OutboundRuleCRUDAllParameters"); } } }
39.598802
124
0.680327
[ "MIT" ]
DexterPOSH/azure-powershell
src/ResourceManager/Network/Commands.Network.Test/ScenarioTests/Generated/LoadBalancerTestsGenerated.cs
6,449
C#
// ---------------------------------------------------------------------------------------------------------- // Copyright 2018 - RoboDK Inc. - https://robodk.com/ // 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. // ---------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------- // This file (RoboDK.cs) implements the RoboDK API for C# // This file defines the following classes: // Mat: Matrix class, useful pose operations // RoboDK: API to interact with RoboDK // RoboDK.Item: Any item in the RoboDK station tree // // These classes are the objects used to interact with RoboDK and create macros. // An item is an object in the RoboDK tree (it can be either a robot, an object, a tool, a frame, a program, ...). // Items can be retrieved from the RoboDK station using the RoboDK() object (such as RoboDK.GetItem() method) // // In this document: pose = transformation matrix = homogeneous matrix = 4x4 matrix // // More information about the RoboDK API for Python here: // https://robodk.com/doc/en/CsAPI/index.html // https://robodk.com/doc/en/RoboDK-API.html // https://robodk.com/doc/en/PythonAPI/index.html // // More information about RoboDK post processors here: // https://robodk.com/help#PostProcessor // // Visit the Matrix and Quaternions FAQ for more information about pose/homogeneous transformations // http://www.j3d.org/matrix_faq/matrfaq_latest.html // // This library includes the mathematics to operate with homogeneous matrices for robotics. // ---------------------------------------------------------------------------------------------------------- #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Media; using RoboDk.API.Exceptions; using RoboDk.API.Model; #endregion namespace RoboDk.API { /// <summary> /// The Item class represents an item in RoboDK station. An item can be a robot, a frame, a tool, an object, a target, /// ... any item visible in the station tree. /// An item can also be seen as a node where other items can be attached to (child items). /// Every item has one parent item/node and can have one or more child items/nodes /// RoboLinkItem is a "friend" class of RoboLink. /// </summary> internal class Item : IItem { #region Fields private readonly ItemType _type; private string _name; #endregion #region Constructors /// <summary> /// Constructor /// </summary> public Item(RoboDK connectionLink, long itemId = 0, ItemType itemType = ItemType.Any) { ItemId = itemId; Link = connectionLink; _type = itemType; _name = ""; } #endregion #region Properties internal RoboDK Link { get; private set; } public long ItemId { get; private set; } #endregion #region Public Methods public IItem Clone(IRoboDK connectionLink) { var item = new Item((RoboDK)connectionLink, this.ItemId, this._type); var itemProxy = connectionLink.ItemInterceptFunction(item); return itemProxy; } public override string ToString() { if (Valid()) { return $"RoboDK item(name:{_name}, id:{ItemId}, type:{_type})"; } return "RoboDK item (INVALID)"; } /// <inheritdoc /> public void SetItemFlags(ItemFlags itemFlags = ItemFlags.All) { int flags = (int) itemFlags; Link.check_connection(); string command = "S_Item_Rights"; Link.send_line(command); Link.send_item(this); Link.send_int(flags); Link.check_status(); } /// <inheritdoc /> public ItemFlags GetItemFlags() { Link.check_connection(); string command = "S_Item_Rights"; Link.send_line(command); Link.send_item(this); int flags = Link.rec_int(); ItemFlags itemFlags = (ItemFlags) flags; Link.check_status(); return itemFlags; } /// <inheritdoc /> public bool Equals(IItem otherItem) { return ItemId == otherItem.ItemId; } /// <inheritdoc /> public RoboDK RL() { return Link; } /// <inheritdoc /> public RoboDK RDK() { return Link; } /// <inheritdoc /> public void NewLink() { Link = new RoboDK(); Link.Connect(); } //////// GENERIC ITEM CALLS /// <inheritdoc /> public ItemType GetItemType() { /*Link.check_connection(); var command = "G_Item_Type"; Link.send_line(command); Link.send_item(this); var type = Link.rec_int(); ItemType itemType = (ItemType) type; Link.check_status(); return itemType;*/ return _type; } ////// add more methods /// <inheritdoc /> public void Save(string filename) { Link.Save(filename, this); } /// <inheritdoc /> public void Delete() { if (ItemId == 0) { throw new RdkException("Item does not exist"); } Link.check_connection(); var command = "Remove"; Link.send_line(command); Link.send_item(this); Link.check_status(); ItemId = 0; } /// <inheritdoc /> public bool Valid() { if (ItemId == 0) { return false; } return true; } /// <inheritdoc /> public void SetParent(IItem parent) { Link.check_connection(); Link.send_line("S_Parent"); Link.send_item(this); Link.send_item(parent); Link.check_status(); } /// <inheritdoc /> public void SetParentStatic(IItem parent) { Link.check_connection(); Link.send_line("S_Parent_Static"); Link.send_item(this); Link.send_item(parent); Link.check_status(); } /// <inheritdoc /> public IItem AttachClosest() { Link.check_connection(); Link.send_line("Attach_Closest"); Link.send_item(this); IItem item_attached = Link.rec_item(); Link.check_status(); return item_attached; } /// <inheritdoc /> public IItem DetachClosest(IItem parent = null) { Link.check_connection(); Link.send_line("Detach_Closest"); Link.send_item(this); Link.send_item(parent); IItem item_detached = Link.rec_item(); Link.check_status(); return item_detached; } /// <inheritdoc /> public void DetachAll(IItem parent = null) { Link.check_connection(); Link.send_line("Detach_All"); Link.send_item(this); Link.send_item(parent); Link.check_status(); } /// <inheritdoc /> public List<IItem> Childs() { Link.check_connection(); var command = "G_Childs"; Link.send_line(command); Link.send_item(this); var nitems = Link.rec_int(); var itemlist = new List<IItem>(nitems); for (var i = 0; i < nitems; i++) { itemlist.Add(Link.rec_item()); } Link.check_status(); return itemlist; } /// <inheritdoc /> public IItem Parent() { Link.check_connection(); var command = "G_Parent"; Link.send_line(command); Link.send_item(this); var parent = Link.rec_item(); Link.check_status(); return parent; } /// <inheritdoc /> public bool Visible() { Link.check_connection(); var command = "G_Visible"; Link.send_line(command); Link.send_item(this); var visible = Link.rec_int(); Link.check_status(); return visible != 0; } /// <inheritdoc /> public void SetVisible(bool visible, VisibleRefType visible_reference = VisibleRefType.Default) { if (visible_reference == VisibleRefType.Default) { visible_reference = visible ? VisibleRefType.On : VisibleRefType.Off; } Link.check_connection(); var command = "S_Visible"; Link.send_line(command); Link.send_item(this); Link.send_int(visible ? 1 : 0); Link.send_int((int)visible_reference); Link.check_status(); } /// <inheritdoc /> public void ShowAsCollided(bool collided, int robotLinkId = 0) { Link.RequireBuild(5449); Link.check_connection(); Link.send_line("ShowAsCollided"); Link.send_item(this); Link.send_int(robotLinkId); Link.send_int(collided ? 1 : 0); Link.check_status(); } /// <inheritdoc /> public string Name() { Link.check_connection(); var command = "G_Name"; Link.send_line(command); Link.send_item(this); _name = Link.rec_line(); Link.check_status(); return _name; } /// <inheritdoc /> public void SetName(string name) { Link.check_connection(); var command = "S_Name"; Link.send_line(command); Link.send_item(this); Link.send_line(name); Link.check_status(); } /// <inheritdoc /> public void setParamRobotTool(double toolMass = 5, double[] toolCOG = null) { Link.check_connection(); var command = "S_ParamCalibTool"; Link.send_line(command); Link.send_item(this); Link.send_double(toolMass); if (toolCOG != null) { Link.send_array(toolCOG); } Link.check_status(); } /// <inheritdoc /> public string SetParam(string param, string value = "") { Link.RequireBuild(7129); Link.check_connection(); Link.send_line("ICMD"); Link.send_item(this); Link.send_line(param); Link.send_line(value); var response = Link.rec_line(); Link.check_status(); return response; } /// <inheritdoc /> public void SetPose(Mat pose) { Link.check_connection(); var command = "S_Hlocal"; Link.send_line(command); Link.send_item(this); Link.send_pose(pose); Link.check_status(); } /// <inheritdoc /> public Mat Pose() { Link.check_connection(); var command = "G_Hlocal"; Link.send_line(command); Link.send_item(this); var pose = Link.rec_pose(); Link.check_status(); return pose; } /// <inheritdoc /> public void SetGeometryPose(Mat pose) { Link.check_connection(); var command = "S_Hgeom"; Link.send_line(command); Link.send_item(this); Link.send_pose(pose); Link.check_status(); } /// <inheritdoc /> public Mat GeometryPose() { Link.check_connection(); var command = "G_Hgeom"; Link.send_line(command); Link.send_item(this); var pose = Link.rec_pose(); Link.check_status(); return pose; } /// <inheritdoc /> public void SetHtool(Mat pose) { Link.check_connection(); var command = "S_Htool"; Link.send_line(command); Link.send_item(this); Link.send_pose(pose); Link.check_status(); } /// <inheritdoc /> public Mat Htool() { Link.check_connection(); var command = "G_Htool"; Link.send_line(command); Link.send_item(this); var pose = Link.rec_pose(); Link.check_status(); return pose; } /// <inheritdoc /> public Mat PoseTool() { Link.check_connection(); var command = "G_Tool"; Link.send_line(command); Link.send_item(this); var pose = Link.rec_pose(); Link.check_status(); return pose; } /// <inheritdoc /> public Mat PoseFrame() { Link.check_connection(); var command = "G_Frame"; Link.send_line(command); Link.send_item(this); var pose = Link.rec_pose(); Link.check_status(); return pose; } /// <inheritdoc /> public void SetPoseFrame(Mat framePose) { Link.check_connection(); var command = "S_Frame"; Link.send_line(command); Link.send_pose(framePose); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void SetPoseFrame(IItem frameItem) { Link.check_connection(); var command = "S_Frame_ptr"; Link.send_line(command); Link.send_item(frameItem); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void SetPoseTool(Mat toolPose) { Link.check_connection(); var command = "S_Tool"; Link.send_line(command); Link.send_pose(toolPose); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void SetPoseTool(IItem toolItem) { Link.check_connection(); var command = "S_Tool_ptr"; Link.send_line(command); Link.send_item(toolItem); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void SetPoseAbs(Mat pose) { Link.check_connection(); var command = "S_Hlocal_Abs"; Link.send_line(command); Link.send_item(this); Link.send_pose(pose); Link.check_status(); } /// <inheritdoc /> public Mat PoseAbs() { Link.check_connection(); var command = "G_Hlocal_Abs"; Link.send_line(command); Link.send_item(this); var pose = Link.rec_pose(); Link.check_status(); return pose; } /// <inheritdoc /> [Obsolete("Deprecated, please use new Recolor mehod which uses the new RoboDK Color class.")] public void Recolor(double[] tocolor, double[] fromcolor = null, double tolerance = 0.1) { Link.check_connection(); if (fromcolor == null) { fromcolor = new double[] {0, 0, 0, 0}; tolerance = 2; } Link.check_color(tocolor); Link.check_color(fromcolor); var command = "Recolor"; Link.send_line(command); Link.send_item(this); var combined = new double[9]; combined[0] = tolerance; Array.Copy(fromcolor, 0, combined, 1, 4); Array.Copy(tocolor, 0, combined, 5, 4); Link.send_array(combined); Link.check_status(); } /// <inheritdoc /> public void Recolor(Color tocolor, Color? fromcolor = null, double tolerance = 0.1) { double[] tocolorArray = tocolor.ToRoboDKColorArray(); Link.check_connection(); if (fromcolor.HasValue == false) { fromcolor = new Color {A = 0, R = 0, G = 0, B = 0}; tolerance = 2; } double[] fromcolorArray = fromcolor.Value.ToRoboDKColorArray(); Link.check_color(tocolorArray); Link.check_color(fromcolorArray); var command = "Recolor"; Link.send_line(command); Link.send_item(this); var combined = new double[9]; combined[0] = tolerance; Array.Copy(fromcolorArray, 0, combined, 1, 4); Array.Copy(tocolorArray, 0, combined, 5, 4); Link.send_array(combined); Link.check_status(); } /// <inheritdoc /> public void SetColor(Color tocolor) { double[] tocolorArray = tocolor.ToRoboDKColorArray(); Link.check_connection(); Link.check_color(tocolorArray); Link.send_line("S_Color"); Link.send_item(this); Link.send_array(tocolorArray); Link.check_status(); } /// <inheritdoc /> public void SetColor(int shapeId, Color tocolor) { double[] tocolorArray = tocolor.ToRoboDKColorArray(); Link.check_color(tocolorArray); Link.check_connection(); Link.send_line("S_ShapeColor"); Link.send_item(this); Link.send_int(shapeId); Link.send_array(tocolorArray); Link.check_status(); } /// <inheritdoc /> public void SetTransparency(double alpha) { // saturate the alpha channel so it remains between 0 and 1. alpha = Math.Min(1, Math.Max(0, alpha)); Link.check_connection(); double[] tocolorArray = {-1, -1, -1, alpha}; Link.send_line("S_Color"); Link.send_item(this); Link.send_array(tocolorArray); Link.check_status(); } /// <inheritdoc /> public Color GetColor() { Link.check_connection(); Link.send_line("G_Color"); Link.send_item(this); var colorArray = Link.rec_array(); Link.check_status(); Color c = colorArray.FromRoboDKColorArray(); return c; } /// <inheritdoc /> public void Scale(double[] scale) { Link.check_connection(); if (scale.Length != 3) { throw new RdkException("scale must be a single value or a 3-vector value"); } var command = "Scale"; Link.send_line(command); Link.send_item(this); Link.send_array(scale); Link.check_status(); } /// <inheritdoc /> public IItem AddCurve(Mat curvePoints, bool addToRef = false, ProjectionType projectionType = ProjectionType.AlongNormalRecalc) { return Link.AddCurve(curvePoints, this, addToRef, projectionType); } /// <inheritdoc /> public Mat ProjectPoints(Mat points, ProjectionType projectionType = ProjectionType.AlongNormalRecalc) { return Link.ProjectPoints(points, this, projectionType); } /// <inheritdoc /> public bool SelectedFeature(out ObjectSelectionType featureType, out int featureId) { Link.check_connection(); Link.send_line("G_ObjSelection"); Link.send_item(this); int isSelected = Link.rec_int(); featureType = (ObjectSelectionType)Link.rec_int(); featureId = Link.rec_int(); Link.check_status(); return isSelected > 0; } /// <inheritdoc /> public string GetPoints(ObjectSelectionType featureType, int featureId, out Mat pointList) { Link.check_connection(); Link.send_line("G_ObjPoint"); Link.send_item(this); Link.send_int((int)featureType); Link.send_int(featureId); pointList = Link.rec_matrix(); string name = Link.rec_line(); Link.check_status(); return name; } /// <inheritdoc /> public IItem SetMachiningParameters(string ncfile = "", IItem partObj = null, string options = "") { Link.check_connection(); Link.send_line("S_MachiningParams"); Link.send_item(this); Link.send_line(ncfile); Link.send_item(partObj); Link.send_line("NO_UPDATE " + options); Link.ReceiveTimeout = 3600 * 1000; IItem program = Link.rec_item(); Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; double status = Link.rec_int() / 1000.0; Link.check_status(); return program; } //"""Target item calls""" /// <inheritdoc /> public void SetAsCartesianTarget() { Link.check_connection(); var command = "S_Target_As_RT"; Link.send_line(command); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void SetAsJointTarget() { Link.check_connection(); var command = "S_Target_As_JT"; Link.send_line(command); Link.send_item(this); Link.check_status(); } //#####Robot item calls#### /// <inheritdoc /> public double[] Joints() { Link.check_connection(); var command = "G_Thetas"; Link.send_line(command); Link.send_item(this); var joints = Link.rec_array(); Link.check_status(); return joints; } // add more methods /// <inheritdoc /> public double[] JointsHome() { Link.check_connection(); var command = "G_Home"; Link.send_line(command); Link.send_item(this); var joints = Link.rec_array(); Link.check_status(); return joints; } /// <inheritdoc /> /// <returns></returns> public IItem ObjectLink(int linkId = 0) { Link.check_connection(); Link.send_line("G_LinkObjId"); Link.send_item(this); Link.send_int(linkId); IItem item = Link.rec_item(); Link.check_status(); return item; } /// <inheritdoc /> public IItem GetLink(ItemType typeLinked = ItemType.Robot) { Link.check_connection(); Link.send_line("G_LinkType"); Link.send_item(this); Link.send_int((int) typeLinked); IItem item = Link.rec_item(); Link.check_status(); return item; } /// <inheritdoc /> public void SetJoints(double[] joints) { Link.check_connection(); var command = "S_Thetas"; Link.send_line(command); Link.send_array(joints); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void JointLimits(out double[] lowerLlimits, out double[] upperLimits) { Link.check_connection(); var command = "G_RobLimits"; Link.send_line(command); Link.send_item(this); lowerLlimits = Link.rec_array(); upperLimits = Link.rec_array(); var jointsType = Link.rec_int() / 1000.0; Link.check_status(); } /// <inheritdoc /> public void SetRobot(IItem robot = null) { Link.check_connection(); var command = "S_Robot"; Link.send_line(command); Link.send_item(this); Link.send_item(robot); Link.check_status(); } /// <inheritdoc /> public void SetFrame(IItem frame) { SetPoseFrame(frame); } /// <inheritdoc /> public void SetFrame(Mat frame) { SetPoseFrame(frame); } /// <inheritdoc /> public void SetTool(IItem tool) { SetPoseTool(tool); } /// <inheritdoc /> public void SetTool(Mat tool) { SetPoseTool(tool); } /// <inheritdoc /> public IItem AddTool(Mat toolPose, string toolName = "New TCP") { Link.check_connection(); var command = "AddToolEmpty"; Link.send_line(command); Link.send_item(this); Link.send_pose(toolPose); Link.send_line(toolName); var newtool = Link.rec_item(); Link.check_status(); return newtool; } /// <inheritdoc /> public Mat SolveFK(double[] joints) { Link.check_connection(); var command = "G_FK"; Link.send_line(command); Link.send_array(joints); Link.send_item(this); var pose = Link.rec_pose(); Link.check_status(); return pose; } /// <inheritdoc /> public double[] JointsConfig(double[] joints) { Link.check_connection(); var command = "G_Thetas_Config"; Link.send_line(command); Link.send_array(joints); Link.send_item(this); var config = Link.rec_array(); Link.check_status(); return config; } /// <inheritdoc /> /// <returns>array of joints</returns> public double[] SolveIK(Mat pose, double[] jointsApprox = null, Mat tool = null, Mat reference = null) { if (tool != null) { pose = pose * tool.inv(); } if (reference != null) { pose = reference * pose; } Link.check_connection(); if (jointsApprox == null) { Link.send_line("G_IK"); Link.send_pose(pose); } else { Link.send_line("G_IK_jnts"); Link.send_pose(pose); Link.send_array(jointsApprox); } Link.send_item(this); var jointsok = Link.rec_array(); Link.check_status(); return jointsok; } /// <inheritdoc /> public Mat SolveIK_All(Mat pose, Mat tool = null, Mat reference = null) { if (tool != null) { pose = pose * tool.inv(); } if (reference != null) { pose = reference * pose; } Link.check_connection(); var command = "G_IK_cmpl"; Link.send_line(command); Link.send_pose(pose); Link.send_item(this); var jointsList = Link.rec_matrix(); Link.check_status(); return jointsList; } /// <inheritdoc /> public bool Connect(string robotIp = "") { Link.check_connection(); var command = "Connect"; Link.send_line(command); Link.send_item(this); Link.send_line(robotIp); var status = Link.rec_int(); Link.check_status(); return status != 0; } /// <inheritdoc /> public bool ConnectSafe(string robotIp = "", int maxAttempts = 5, int waitConnection = 4) { int tryCount = 0; int refreshRate = 500; // [ms] var waitSpan = new TimeSpan(0, 0, waitConnection); RobotConnectionType connectionStatus; Connect(robotIp); var timer = new Stopwatch(); timer.Start(); var attemptStart = timer.Elapsed; System.Threading.Thread.Sleep(refreshRate); while (true) { connectionStatus = ConnectedState(); Console.WriteLine(connectionStatus); //.Message); if (connectionStatus == RobotConnectionType.Ready) { break; } else if (connectionStatus == RobotConnectionType.Disconnected) { Console.WriteLine("Trying to reconnect..."); Connect(robotIp); } if (timer.Elapsed - attemptStart > waitSpan) { attemptStart = timer.Elapsed; Disconnect(); tryCount++; if (tryCount >= maxAttempts) { Console.WriteLine("Failed to connect: Timed out"); break; } Console.WriteLine("Retrying connection, attempt #" + (tryCount + 1)); } System.Threading.Thread.Sleep(refreshRate); } return connectionStatus == RobotConnectionType.Ready; } /// <inheritdoc /> public (string RobotIP, int Port, string RemotePath, string FTPUser, string FTPPass) ConnectionParams() { Link.check_connection(); var command = "ConnectParams"; Link.send_line(command); Link.send_item(this); var robotIP = Link.rec_line(); var port = Link.rec_int(); var remotePath = Link.rec_line(); var ftpUser = Link.rec_line(); var ftpPass = Link.rec_line(); Link.check_status(); return (robotIP, port, remotePath, ftpUser, ftpPass); } /// <inheritdoc /> public void setConnectionParams(string robotIP, int port, string remotePath, string ftpUser, string ftpPass) { Link.check_connection(); var command = "setConnectParams"; Link.send_line(command); Link.send_item(this); Link.send_line(robotIP); Link.send_int(port); Link.send_line(remotePath); Link.send_line(ftpUser); Link.send_line(ftpPass); Link.check_status(); } /// <inheritdoc /> public RobotConnectionType ConnectedState() { Link.check_connection(); var command = "ConnectedState"; Link.send_line(command); Link.send_item(this); RobotConnectionType status = (RobotConnectionType) Link.rec_int(); var message = Link.rec_line(); Link.check_status(); return status;//((RobotConnectionStatus)status, message); } /// <inheritdoc /> public bool Disconnect() { Link.check_connection(); var command = "Disconnect"; Link.send_line(command); Link.send_item(this); var status = Link.rec_int(); Link.check_status(); return status != 0; } /// <inheritdoc /> public void MoveJ(IItem itemtarget, bool blocking = true) { if (this.GetItemType() == ItemType.Program) { AddMoveJ(itemtarget); } else { Link.MoveX(itemtarget, null, null, this, 1, blocking); } } /// <inheritdoc /> public void MoveJ(double[] joints, bool blocking = true) { Link.MoveX(null, joints, null, this, 1, blocking); } /// <inheritdoc /> public void MoveJ(Mat target, bool blocking = true) { Link.MoveX(null, null, target, this, 1, blocking); } /// <inheritdoc /> public void MoveL(IItem itemtarget, bool blocking = true) { if (this.GetItemType() == ItemType.Program) { AddMoveL(itemtarget); } else { Link.MoveX(itemtarget, null, null, this, 2, blocking); } } /// <inheritdoc /> public void MoveL(double[] joints, bool blocking = true) { Link.MoveX(null, joints, null, this, 2, blocking); } /// <inheritdoc /> public void MoveL(Mat target, bool blocking = true) { Link.MoveX(null, null, target, this, 2, blocking); } /// <inheritdoc /> public void MoveC(IItem itemtarget1, IItem itemtarget2, bool blocking = true) { Link.moveC_private(itemtarget1, null, null, itemtarget2, null, null, this, blocking); } /// <inheritdoc /> public void MoveC(double[] joints1, double[] joints2, bool blocking = true) { Link.moveC_private(null, joints1, null, null, joints2, null, this, blocking); } /// <inheritdoc /> public void MoveC(Mat target1, Mat target2, bool blocking = true) { Link.moveC_private(null, null, target1, null, null, target2, this, blocking); } /// <inheritdoc /> public int MoveJ_Test(double[] j1, double[] j2, double minstepDeg = -1) { Link.check_connection(); Link.send_line("CollisionMove"); Link.send_item(this); Link.send_array(j1); Link.send_array(j2); Link.send_int((int) (minstepDeg * 1000.0)); Link.ReceiveTimeout = 3600 * 1000; var collision = Link.rec_int(); Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; Link.check_status(); return collision; } /// <inheritdoc /> public bool MoveJ_Test_Blend(double[] j1, double[] j2, double[] j3, double blendDeg = 5, double minstepDeg = -1) { Link.RequireBuild(7206); Link.check_connection(); Link.send_line("CollisionMoveBlend"); Link.send_item(this); Link.send_array(j1); Link.send_array(j2); Link.send_array(j3); Link.send_int((int)(minstepDeg * 1000.0)); Link.send_int((int)(blendDeg * 1000.0)); Link.ReceiveTimeout = 3600 * 1000; var collision = Link.rec_int(); Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; Link.check_status(); return collision != 0; } /// <inheritdoc /> public int MoveL_Test(double[] j1, double[] j2, double minstepDeg = -1) { Link.check_connection(); var command = "CollisionMoveL"; Link.send_line(command); Link.send_item(this); Link.send_array(j1); Link.send_array(j2); Link.send_int((int) (minstepDeg * 1000.0)); Link.ReceiveTimeout = 3600 * 1000; var collision = Link.rec_int(); Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; Link.check_status(); return collision; } /// <inheritdoc /> public void SetSpeed(double speedLinear, double accelLinear = -1, double speedJoints = -1, double accelJoints = -1) { Link.check_connection(); var command = "S_Speed4"; Link.send_line(command); Link.send_item(this); var speedAccel = new double[4]; speedAccel[0] = speedLinear; speedAccel[1] = speedJoints; speedAccel[2] = accelLinear; speedAccel[3] = accelJoints; Link.send_array(speedAccel); Link.check_status(); } /// <inheritdoc /> public void SetZoneData(double zonedata) { Link.check_connection(); var command = "S_ZoneData"; Link.send_line(command); Link.send_int((int) (zonedata * 1000.0)); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void SetRounding(double rounding) { Link.check_connection(); var command = "S_ZoneData"; Link.send_line(command); Link.send_int((int) rounding * 1000); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void ShowSequence(Mat sequence) { Link.check_connection(); var command = "Show_Seq"; Link.send_line(command); Link.send_matrix(sequence); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public bool Busy() { Link.check_connection(); var command = "IsBusy"; Link.send_line(command); Link.send_item(this); var busy = Link.rec_int(); Link.check_status(); return busy > 0; } /// <inheritdoc /> public void Stop() { Link.check_connection(); var command = "Stop"; Link.send_line(command); Link.send_item(this); Link.check_status(); } /// <inheritdoc /> public void WaitMove(double timeoutSec = 300) { Link.check_connection(); var command = "WaitMove"; Link.send_line(command); Link.send_item(this); Link.check_status(); Link.ReceiveTimeout = (int) (timeoutSec * 1000.0); Link.check_status(); //will wait here; Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; //int isbusy = link.Busy(this); //while (isbusy) //{ // busy = link.Busy(item); //} } ///////// ADD MORE METHODS // ---- Program item calls ----- /// <inheritdoc /> public bool MakeProgram(string filename = "", RunMode runMode = RunMode.MakeRobotProgram) { Link.check_connection(); Link.send_line("MakeProg2"); Link.send_item(this); Link.send_line(filename); Link.send_int((int) runMode); Link.ReceiveTimeout = 3600 * 1000; int progStatus = Link.rec_int(); Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; string progLogStr = Link.rec_line(); int transferStatus = Link.rec_int(); Link.check_status(); Link.LastStatusMessage = progLogStr; bool success = progStatus > 0; bool transferOk = transferStatus > 0; return success && transferOk; // prog_log_str //return success, prog_log_str, transfer_ok } /// <inheritdoc /> public void SetRunType(ProgramExecutionType programExecutionType) { Link.check_connection(); var command = "S_ProgRunType"; Link.send_line(command); Link.send_item(this); Link.send_int((int) programExecutionType); Link.check_status(); } /// <inheritdoc /> public int RunProgram() { Link.check_connection(); var command = "RunProg"; Link.send_line(command); Link.send_item(this); var progStatus = Link.rec_int(); Link.check_status(); return progStatus; } /// <inheritdoc /> public int RunCode(string parameters = null) { Link.check_connection(); if (parameters == null) { var command = "RunProg"; Link.send_line(command); Link.send_item(this); } else { var command = "RunProgParam"; Link.send_line(command); Link.send_item(this); Link.send_line(parameters); } var progstatus = Link.rec_int(); Link.check_status(); return progstatus; } /// <inheritdoc /> public bool RunCodeCustom(string code, ProgramRunType runType = ProgramRunType.CallProgram) { Link.check_connection(); var command = "RunCode2"; Link.send_line(command); Link.send_item(this); Link.send_line(code.Replace("\n\n", "<br>").Replace("\n", "<br>")); Link.send_int((int) runType); var progstatus = Link.rec_int(); Link.check_status(); return progstatus == 0; } /// <inheritdoc /> public void Pause(double timeMs = -1) { Link.check_connection(); var command = "RunPause"; Link.send_line(command); Link.send_item(this); Link.send_int((int) (timeMs * 1000.0)); Link.check_status(); } /// <inheritdoc /> public void setDO(string ioVar, string ioValue) { Link.check_connection(); var command = "setDO"; Link.send_line(command); Link.send_item(this); Link.send_line(ioVar); Link.send_line(ioValue); Link.check_status(); } /// <inheritdoc /> public void waitDI(string ioVar, string ioValue, double timeoutMs = -1) { Link.check_connection(); var command = "waitDI"; Link.send_line(command); Link.send_item(this); Link.send_line(ioVar); Link.send_line(ioValue); Link.send_int((int) (timeoutMs * 1000.0)); Link.check_status(); } /// <inheritdoc /> public void AddCustomInstruction(string name, string pathRun, string pathIcon = "", bool blocking = true, string cmdRunOnRobot = "") { Link.check_connection(); var command = "InsCustom2"; Link.send_line(command); Link.send_item(this); Link.send_line(name); Link.send_line(pathRun); Link.send_line(pathIcon); Link.send_line(cmdRunOnRobot); Link.send_int(blocking ? 1 : 0); Link.check_status(); } /// <inheritdoc /> public void AddMoveJ(IItem itemtarget) { Link.check_connection(); var command = "Add_INSMOVE"; Link.send_line(command); Link.send_item(itemtarget); Link.send_item(this); Link.send_int(1); Link.check_status(); } /// <inheritdoc /> public void AddMoveL(IItem itemtarget) { Link.check_connection(); var command = "Add_INSMOVE"; Link.send_line(command); Link.send_item(itemtarget); Link.send_item(this); Link.send_int(2); Link.check_status(); } /// <inheritdoc /> public void ShowInstructions(bool show = true) { Link.check_connection(); Link.send_line("Prog_ShowIns"); Link.send_item(this); Link.send_int(show ? 1 : 0); Link.check_status(); } /// <inheritdoc /> public void ShowTargets(bool show = true) { Link.check_connection(); Link.send_line("Prog_ShowTargets"); Link.send_item(this); Link.send_int(show ? 1 : 0); Link.check_status(); } ////////// ADD MORE METHODS /// <inheritdoc /> public int InstructionCount() { Link.check_connection(); var command = "Prog_Nins"; Link.send_line(command); Link.send_item(this); var nins = Link.rec_int(); Link.check_status(); return nins; } /// <inheritdoc /> public ProgramInstruction GetInstruction(int instructionId) { ProgramInstruction programInstruction = new ProgramInstruction(); Link.check_connection(); var command = "Prog_GIns"; Link.send_line(command); Link.send_item(this); Link.send_int(instructionId); programInstruction.Name = Link.rec_line(); programInstruction.InstructionType = (InstructionType) Link.rec_int(); programInstruction.MoveType = MoveType.Invalid; programInstruction.IsJointTarget = false; programInstruction.Target = null; programInstruction.Joints = null; if (programInstruction.InstructionType == InstructionType.Move) { programInstruction.MoveType = (MoveType) Link.rec_int(); programInstruction.IsJointTarget = Link.rec_int() > 0 ? true : false; programInstruction.Target = Link.rec_pose(); programInstruction.Joints = Link.rec_array(); } Link.check_status(); return programInstruction; } /// <inheritdoc /> public void SetInstruction(int instructionId, ProgramInstruction instruction) { Link.check_connection(); var command = "Prog_SIns"; Link.send_line(command); Link.send_item(this); Link.send_int(instructionId); Link.send_line(instruction.Name); Link.send_int((int) instruction.InstructionType); if (instruction.InstructionType == InstructionType.Move) { Link.send_int((int) instruction.MoveType); Link.send_int(instruction.IsJointTarget ? 1 : 0); Link.send_pose(instruction.Target); Link.send_array(instruction.Joints); } Link.check_status(); } /// <inheritdoc /> public UpdateResult Update() { /*Updates a program and returns the estimated time and the number of valid instructions. :return: [valid_instructions, program_time, program_distance, valid_program] valid_instructions: The number of valid instructions program_time: Estimated cycle time(in seconds) program_distance: Estimated distance that the robot TCP will travel(in mm) valid_program: It is 1 if the program has no issues, 0 otherwise. ..seealso:: :func:`~robolink.Robolink.AddProgram` */ Link.check_connection(); var command = "Update"; Link.send_line(command); Link.send_item(this); var values = Link.rec_array(); if (values == null) { throw new Exception("Item Update failed."); } Link.check_status(); //var validInstructions = values[0]; //var program_time = values[1] //var program_distance = values[2] //var valid_program = values[3] UpdateResult updateResult = new UpdateResult( values[0], values[1], values[2], values[3]); return updateResult; } /// <inheritdoc /> public UpdateResult Update( CollisionCheckOptions collisionCheck, /* = CollisionCheckOptions.CollisionCheckOff, */ int timeoutSec = 3600, double linStepMm = -1, double jointStepDeg = -1) { Link.check_connection(); Link.send_line("Update2"); Link.send_item(this); double[] values = {(double) collisionCheck, linStepMm, jointStepDeg}; Link.send_array(values); Link.ReceiveTimeout = timeoutSec * 1000; double[] result = Link.rec_array(); Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; string readableMsg = Link.rec_line(); Link.check_status(); Link.LastStatusMessage = readableMsg; UpdateResult updateResult = new UpdateResult( result[0], result[1], result[2], result[3], readableMsg); return updateResult; } //// <inheritdoc /> public int InstructionList(out Mat instructions) { Link.check_connection(); var command = "G_ProgInsList"; Link.send_line(command); Link.send_item(this); instructions = Link.rec_matrix(); var errors = Link.rec_int(); Link.check_status(); return errors; } /// <inheritdoc /> public InstructionListJointsResult GetInstructionListJoints( double mmStep = 10.0, double degStep = 5.0, string saveToFile = "", CollisionCheckOptions collisionCheck = CollisionCheckOptions.CollisionCheckOff, ListJointsType flags = 0, int timeoutSec = 3600, double time_step = 0.2) { var result = new InstructionListJointsResult {JointList = new List<InstructionListJointsResult.JointsResult>()}; string errorMessage; Mat jointList; result.ErrorCode = InstructionListJoints(out errorMessage, out jointList, mmStep, degStep, saveToFile, collisionCheck, flags, timeoutSec, time_step); result.ErrorMessage = errorMessage; var numberOfJoints = GetLink(ItemType.Robot).Joints().Length; for (var colId = 0; colId < jointList.Cols; colId++) { var joints = new double[numberOfJoints]; for (var rowId = 0; rowId < numberOfJoints; rowId++) { joints[rowId] = jointList[rowId, colId]; } var jointError = (int) jointList[numberOfJoints, colId]; var errorType = JointErrorTypeHelper.ConvertErrorCodeToJointErrorType(jointError); var linearStep = jointList[numberOfJoints + 1, colId]; var jointStep = jointList[numberOfJoints + 2, colId]; var moveId = (int) jointList[numberOfJoints + 3, colId]; var timeStep = 0.0; var speeds = new double[0]; var accelerations = new double[0]; if ((int)flags >= 2) { timeStep = jointList[numberOfJoints + 4, colId]; speeds = new double[numberOfJoints]; var speedRowId = numberOfJoints + 8; var i = 0; for (var rowId = speedRowId; rowId < speedRowId + numberOfJoints; rowId++, i++) { speeds[i] = jointList[rowId, colId]; } } if ((int)flags >= 3) { accelerations = new double[numberOfJoints]; var accelerationRowId = numberOfJoints + 8 + numberOfJoints; var i = 0; for (var rowId = accelerationRowId; rowId < accelerationRowId + numberOfJoints; rowId++, i++) { accelerations[i] = jointList[rowId, colId]; } } result.JointList.Add( new InstructionListJointsResult.JointsResult ( moveId, joints, speeds, accelerations, errorType, linearStep, jointStep, timeStep ) ); } return result; } /// <inheritdoc /> public int InstructionListJoints(out string errorMsg, out Mat jointList, double mmStep = 10.0, double degStep = 5.0, string saveToFile = "", CollisionCheckOptions collisionCheck = CollisionCheckOptions.CollisionCheckOff, ListJointsType flags = 0, int timeoutSec = 3600, double time_step = 0.2) { Link.check_connection(); Link.send_line("G_ProgJointList"); Link.send_item(this); double[] parameter = {mmStep, degStep, (double) collisionCheck, (double)flags, time_step}; Link.send_array(parameter); //joint_list = save_to_file; Link.ReceiveTimeout = timeoutSec * 1000; if (string.IsNullOrEmpty(saveToFile)) { Link.send_line(""); jointList = Link.rec_matrix(); } else { Link.send_line(saveToFile); jointList = null; } int errorCode = Link.rec_int(); Link.ReceiveTimeout = Link.DefaultSocketTimeoutMilliseconds; errorMsg = Link.rec_line(); Link.check_status(); return errorCode; } /// <summary> /// Disconnect from the RoboDK API. This flushes any pending program generation. /// </summary> public void Finish() { Link.Finish(); } #endregion } }
31.43287
126
0.517693
[ "MIT" ]
kellyprankin/RoboDK-API
C#/API/Item.cs
54,318
C#
using UnityEngine; using qASIC; using qASIC.InputManagement; namespace Player { public class PlayerMovementController : MonoBehaviour { CharacterController controller; [SerializeField] float speed; [SerializeField] float runSpeed; [SerializeField] float gravity; [SerializeField] float jumpHeight; [SerializeField] float groundVelocity = 3f; [SerializeField] Vector3 GroundPointOffset; [SerializeField] float GroundPointRadius = 0.55f; [SerializeField] LayerMask GroundLayer; float velocity; bool isGrounded; public static bool Noclip { get; set; } private void Awake() { controller = GetComponent<CharacterController>(); if (controller == null) qDebug.LogError("Character controller has not been added!"); } private void Start() { CursorManager.ChangeLookState("interact", true); CursorManager.ChangeMovementState("interact", true); } private void Update() { Vector3 path = GetPath(); path.y += CalculateGravity(); qDebug.DisplayValue("pos", VectorText.ToText(transform.position)); qDebug.DisplayValue("path", VectorText.ToText(path)); qDebug.DisplayValue("velocity", velocity); controller.Move(path * Time.deltaTime); } Vector3 GetPath() { if (!CursorManager.CanMove()) return new Vector3(); float y = InputManager.GetAxis("Up", "Down"); float x = InputManager.GetAxis("Right", "Left"); return (transform.right * x + transform.forward * y) * (InputManager.GetInput("Sprint") ? runSpeed : speed); } private void OnDrawGizmosSelected() { Color color = Gizmos.color; Gizmos.color = Color.green; Gizmos.DrawWireSphere(transform.position + GroundPointOffset, GroundPointRadius); Gizmos.color = color; } float CalculateGravity() { isGrounded = Physics.CheckSphere(transform.position + GroundPointOffset, GroundPointRadius, GroundLayer); switch (Noclip) { case true: velocity = InputManager.GetAxis("Jump", "Crouch") * (InputManager.GetInput("Sprint") ? runSpeed : speed); break; default: if (!isGrounded) return velocity -= gravity * Time.deltaTime; velocity = -groundVelocity; if (InputManager.GetInput("Jump") && CursorManager.CanMove()) velocity = Mathf.Sqrt(jumpHeight * 2f * gravity); break; } return velocity; } } }
32.954023
125
0.568887
[ "MIT" ]
Outgrass-Studios/LudumDare49
Assets/Scripts/Player/PlayerMovementController.cs
2,867
C#
using System.Reflection; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 特性集控制。更改这些特性值可修改 与程序集关联的信息。 [assembly: AssemblyTitle("Lenic.Framework.Common")] [assembly: AssemblyDescription("基础程序集。")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lenic.Framework.Common")] [assembly: AssemblyCopyright("Copyright © Lenic 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("12777563-9790-46ad-8d3b-3ebcb41d5ce5")] // 程序集的版本信息由下面四个值组成: // // 主版本 次版本 生成号 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 方法是按如下所示使用“*”: //[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.4")] [assembly: AssemblyFileVersion("1.1.0.4")]
34.074074
101
0.729348
[ "MIT" ]
Lenic/Lenic.Web
WebApi/Lenic.Framework.Common/Properties/AssemblyInfo.cs
1,291
C#
namespace MilanWebStore.Services.Messaging { using System.Collections.Generic; using System.Threading.Tasks; public class NullMessageSender : IEmailSender { public Task SendEmailAsync( string from, string fromName, string to, string subject, string htmlContent, IEnumerable<EmailAttachment> attachments = null) { return Task.CompletedTask; } } }
23.8
60
0.594538
[ "MIT" ]
MihailKarabashev/MilanWebStore
Services/MilanWebStore.Services.Messaging/NullMessageSender.cs
478
C#