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 Microsoft.VisualStudio.TestTools.UnitTesting; using Linehaul_Helper.ViewModels; using Linehaul_Helper.Models; using Linehaul_Helper.Exceptions; using System.Threading.Tasks; using System.Diagnostics; namespace Linehaul_Helper.UnitTest.Tests { [TestClass] public class PlateNumberPageViewModelUnitTest { [TestMethod] [ExpectedException(typeof(LayoutException))] public void DoneCommandShouldExitCurrentScreen() { var pnpvm = new PlateNumberPageViewModel(new UnitInfo()); if (pnpvm.DoneCommand.CanExecute(null)) pnpvm.DoneCommand.Execute(null); } } }
27.791667
69
0.713643
[ "MIT" ]
RodgerLeblanc/Linehaul-Helper
Linehaul_Helper.UnitTest/Tests/PlateNumberPageViewModelUnitTest.cs
669
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HXD.BookLibrary.Models { public class PageHelper { public int TotalCount { get; set; } public int CurrentPage { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public int RecordCount { get; set; } } }
23.875
44
0.636126
[ "Apache-2.0" ]
hxd1230/BookLibrary
HXD.BookLibrary/Models/PageHelper.cs
384
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Robotis { class Com { /// <summary> /// Sucsessfull transmition. /// </summary> public const int TXSUCCESS = 0; /// <summary> /// Sucsessfull reception. /// </summary> public const int RXSUCCESS = 1; /// <summary> /// Unsuxsefull transmition. /// </summary> public const int TXFAIL = 2; /// <summary> /// Unsucefull reception. /// </summary> public const int RXFAIL = 3; /// <summary> /// Transmition error. /// </summary> public const int TXERROR = 4; /// <summary> /// Transmition waiting. /// </summary> public const int RXWAITING = 5; /// <summary> /// Reception timeout. /// </summary> public const int RXTIMEOUT = 6; /// <summary> /// Corupted reception. /// </summary> public const int RXCORRUPT = 7; } }
21.27451
39
0.497696
[ "BSD-3-Clause" ]
orlin369/NineManMorris
Robotis/Com.cs
1,087
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MVC_Core_Entity_ToDoList_01.Models; namespace MVC_Core_Entity_ToDoList_01.Controllers { public class TestController : Controller { public IActionResult Index() { var instance = new Lists(); instance.stringList = new List<string>() { "one", "two", "three" }; instance.publicCelebrityWhoWeWontActuallyName = "Un-named Celebrity"; instance.publicCelebrityHasNoAge = 55; return View(instance); } } }
27.73913
81
0.663009
[ "MIT" ]
philanderson888/2019-06-c-sharp-labs
labs/StandaloneProjects/MVC_Core_Entity_ToDoList_01/Controllers/TestController.cs
640
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Scruffy.Data.Entity; namespace Scruffy.Data.Entity.Migrations { [DbContext(typeof(ScruffyDbContext))] [Migration("20210612150000_Update8")] partial class Update8 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.5") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Scruffy.Data.Entity.Tables.CoreData.ServerConfigurationEntity", b => { b.Property<decimal>("ServerId") .ValueGeneratedOnAdd() .HasColumnType("decimal(20,0)") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.None); b.Property<string>("Prefix") .HasColumnType("nvarchar(max)"); b.HasKey("ServerId"); b.ToTable("ServerConfigurationEntity"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.CoreData.UserEntity", b => { b.Property<decimal>("Id") .ValueGeneratedOnAdd() .HasColumnType("decimal(20,0)") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.None); b.Property<DateTime>("CreationTimeStamp") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Users"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Fractals.FractalAppointmentEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("AppointmentTimeStamp") .HasColumnType("datetime2"); b.Property<long>("ConfigurationId") .HasColumnType("bigint"); b.Property<decimal>("MessageId") .HasColumnType("decimal(20,0)"); b.HasKey("Id"); b.HasIndex("ConfigurationId"); b.ToTable("FractalAppointments"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Fractals.FractalLfgConfigurationEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AliasName") .HasMaxLength(20) .HasColumnType("nvarchar(20)"); b.Property<decimal>("ChannelId") .HasColumnType("decimal(20,0)"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<decimal>("MessageId") .HasColumnType("decimal(20,0)"); b.Property<string>("Title") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("FractalLfgConfigurations"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Fractals.FractalRegistrationEntity", b => { b.Property<long>("ConfigurationId") .HasColumnType("bigint"); b.Property<DateTime>("AppointmentTimeStamp") .HasColumnType("datetime2"); b.Property<decimal>("UserId") .HasColumnType("decimal(20,0)"); b.Property<long?>("AppointmentId") .HasColumnType("bigint"); b.Property<DateTime>("RegistrationTimeStamp") .HasColumnType("datetime2"); b.HasKey("ConfigurationId", "AppointmentTimeStamp", "UserId"); b.HasIndex("AppointmentId"); b.ToTable("FractalRegistrations"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidAppointmentEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("ConfigurationId") .HasColumnType("bigint"); b.Property<DateTime>("TimeStamp") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("ConfigurationId"); b.ToTable("RaidAppointments"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidDayConfigurationEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal?>("AdministrationRoleId") .HasColumnType("decimal(20,0)"); b.Property<decimal>("ChannelId") .HasColumnType("decimal(20,0)"); b.Property<int>("Day") .HasColumnType("int"); b.Property<decimal>("MessageId") .HasColumnType("decimal(20,0)"); b.Property<TimeSpan>("RegistrationDeadline") .HasColumnType("time"); b.Property<decimal?>("ReminderChannelId") .HasColumnType("decimal(20,0)"); b.Property<TimeSpan?>("ReminderTime") .HasColumnType("time"); b.Property<TimeSpan>("ResetTime") .HasColumnType("time"); b.Property<TimeSpan>("StartTime") .HasColumnType("time"); b.HasKey("Id"); b.ToTable("RaidDayConfigurations"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidDayTemplateEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AliasName") .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Thumbnail") .HasColumnType("nvarchar(max)"); b.Property<string>("Title") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("RaidDayTemplates"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidExperienceAssignmentEntity", b => { b.Property<long>("ConfigurationId") .HasColumnType("bigint"); b.Property<long>("ExperienceLevelId") .HasColumnType("bigint"); b.Property<long>("Count") .HasColumnType("bigint"); b.HasKey("ConfigurationId", "ExperienceLevelId"); b.HasIndex("ExperienceLevelId"); b.ToTable("RaidExperienceAssignments"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidExperienceLevelEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal?>("DiscordRoleId") .HasColumnType("decimal(20,0)"); b.Property<long?>("SuperiorExperienceLevelId") .IsRequired() .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("SuperiorExperienceLevelId"); b.ToTable("RaidExperienceLevels"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRegistrationEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("AppointmentId") .HasColumnType("bigint"); b.Property<long?>("Points") .HasColumnType("bigint"); b.Property<DateTime>("RegistrationTimeStamp") .HasColumnType("datetime2"); b.Property<decimal>("UserId") .HasColumnType("decimal(20,0)"); b.HasKey("Id"); b.HasIndex("AppointmentId"); b.HasIndex("UserId"); b.ToTable("RaidRegistrations"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRegistrationRoleAssignmentEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long?>("MainRoleId") .HasColumnType("bigint"); b.Property<long>("RegistrationId") .HasColumnType("bigint"); b.Property<long?>("SubRoleId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("MainRoleId"); b.HasIndex("RegistrationId"); b.HasIndex("SubRoleId"); b.ToTable("RaidRegistrationRoleAssignments"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRequiredRoleEntity", b => { b.Property<long>("ConfigurationId") .HasColumnType("bigint"); b.Property<long>("Index") .HasColumnType("bigint"); b.Property<long>("MainRoleId") .HasColumnType("bigint"); b.Property<long?>("SubRoleId") .HasColumnType("bigint"); b.HasKey("ConfigurationId", "Index"); b.HasIndex("MainRoleId"); b.HasIndex("SubRoleId"); b.ToTable("RaidRequiredRoles"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRoleAliasNameEntity", b => { b.Property<string>("AliasName") .HasMaxLength(20) .HasColumnType("nvarchar(20)"); b.Property<long>("MainRoleId") .HasColumnType("bigint"); b.Property<long?>("SubRoleId") .HasColumnType("bigint"); b.HasKey("AliasName"); b.HasIndex("MainRoleId"); b.HasIndex("SubRoleId"); b.ToTable("RaidRoleAliasNames"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<decimal>("DiscordEmojiId") .HasColumnType("decimal(20,0)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<long?>("MainRoleId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("MainRoleId"); b.ToTable("RaidRoles"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidUserRoleEntity", b => { b.Property<decimal>("UserId") .HasColumnType("decimal(20,0)"); b.Property<long>("MainRoleId") .HasColumnType("bigint"); b.Property<long>("SubRoleId") .HasColumnType("bigint"); b.HasKey("UserId", "MainRoleId", "SubRoleId"); b.HasIndex("MainRoleId"); b.HasIndex("SubRoleId"); b.ToTable("RaidUserRoles"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Reminder.OneTimeReminderEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal>("ChannelId") .HasColumnType("decimal(20,0)"); b.Property<bool>("IsExecuted") .HasColumnType("bit"); b.Property<string>("Message") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("TimeStamp") .HasColumnType("datetime2"); b.Property<decimal>("UserId") .HasColumnType("decimal(20,0)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("OneTimeReminders"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Reminder.WeeklyReminderEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal>("ChannelId") .HasColumnType("decimal(20,0)"); b.Property<int>("DayOfWeek") .HasColumnType("int"); b.Property<TimeSpan>("DeletionTime") .HasColumnType("time"); b.Property<string>("Message") .HasColumnType("nvarchar(max)"); b.Property<decimal?>("MessageId") .HasColumnType("decimal(20,0)"); b.Property<TimeSpan>("PostTime") .HasColumnType("time"); b.HasKey("Id"); b.ToTable("WeeklyReminders"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Fractals.FractalAppointmentEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Fractals.FractalLfgConfigurationEntity", "FractalLfgConfiguration") .WithMany() .HasForeignKey("ConfigurationId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("FractalLfgConfiguration"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Fractals.FractalRegistrationEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Fractals.FractalAppointmentEntity", "FractalAppointmentEntity") .WithMany() .HasForeignKey("AppointmentId"); b.HasOne("Scruffy.Data.Entity.Tables.Fractals.FractalLfgConfigurationEntity", "FractalLfgConfiguration") .WithMany("FractalRegistrations") .HasForeignKey("ConfigurationId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("FractalAppointmentEntity"); b.Navigation("FractalLfgConfiguration"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidAppointmentEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidDayConfigurationEntity", "RaidDayConfiguration") .WithMany("RaidAppointments") .HasForeignKey("ConfigurationId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("RaidDayConfiguration"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidExperienceAssignmentEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidDayConfigurationEntity", "RaidDayConfiguration") .WithMany("RaidExperienceAssignments") .HasForeignKey("ConfigurationId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidExperienceLevelEntity", "RaidExperienceLevel") .WithMany("RaidExperienceAssignments") .HasForeignKey("ExperienceLevelId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("RaidDayConfiguration"); b.Navigation("RaidExperienceLevel"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidExperienceLevelEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidExperienceLevelEntity", "SuperiorRaidExperienceLevel") .WithMany("InferiorRaidExperienceLevels") .HasForeignKey("SuperiorExperienceLevelId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("SuperiorRaidExperienceLevel"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRegistrationEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidAppointmentEntity", "RaidAppointment") .WithMany("RaidRegistrations") .HasForeignKey("AppointmentId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.CoreData.UserEntity", "User") .WithMany("RaidRegistrations") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("RaidAppointment"); b.Navigation("User"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRegistrationRoleAssignmentEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "MainRaidRole") .WithMany() .HasForeignKey("MainRoleId"); b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRegistrationEntity", "RaidRegistration") .WithMany("RaidRegistrationRoleAssignments") .HasForeignKey("RegistrationId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "SubRaidRole") .WithMany() .HasForeignKey("SubRoleId"); b.Navigation("MainRaidRole"); b.Navigation("RaidRegistration"); b.Navigation("SubRaidRole"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRequiredRoleEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidDayConfigurationEntity", "RaidDayConfiguration") .WithMany("RaidRequiredRoles") .HasForeignKey("ConfigurationId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "MainRaidRole") .WithMany() .HasForeignKey("MainRoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "SubRaidRole") .WithMany() .HasForeignKey("SubRoleId"); b.Navigation("MainRaidRole"); b.Navigation("RaidDayConfiguration"); b.Navigation("SubRaidRole"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRoleAliasNameEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "MainRaidRole") .WithMany() .HasForeignKey("MainRoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "SubRaidRole") .WithMany() .HasForeignKey("SubRoleId"); b.Navigation("MainRaidRole"); b.Navigation("SubRaidRole"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "MainRaidRole") .WithMany("SubRaidRoles") .HasForeignKey("MainRoleId"); b.Navigation("MainRaidRole"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidUserRoleEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "MainRaidRole") .WithMany() .HasForeignKey("MainRoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", "SubRaidRole") .WithMany() .HasForeignKey("SubRoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Scruffy.Data.Entity.Tables.CoreData.UserEntity", "User") .WithMany("RaidUserRoles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("MainRaidRole"); b.Navigation("SubRaidRole"); b.Navigation("User"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Reminder.OneTimeReminderEntity", b => { b.HasOne("Scruffy.Data.Entity.Tables.CoreData.UserEntity", "User") .WithMany("OneTimeReminders") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.CoreData.UserEntity", b => { b.Navigation("OneTimeReminders"); b.Navigation("RaidRegistrations"); b.Navigation("RaidUserRoles"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Fractals.FractalLfgConfigurationEntity", b => { b.Navigation("FractalRegistrations"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidAppointmentEntity", b => { b.Navigation("RaidRegistrations"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidDayConfigurationEntity", b => { b.Navigation("RaidAppointments"); b.Navigation("RaidExperienceAssignments"); b.Navigation("RaidRequiredRoles"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidExperienceLevelEntity", b => { b.Navigation("InferiorRaidExperienceLevels"); b.Navigation("RaidExperienceAssignments"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRegistrationEntity", b => { b.Navigation("RaidRegistrationRoleAssignments"); }); modelBuilder.Entity("Scruffy.Data.Entity.Tables.Raid.RaidRoleEntity", b => { b.Navigation("SubRaidRoles"); }); #pragma warning restore 612, 618 } } }
38.937677
125
0.490869
[ "MIT" ]
thoenissen/Scruffy
Scruffy.Data/Entity/Migrations/20210612150000_Update8.Designer.cs
27,492
C#
// *********************************************************************** // Assembly : TessellationAndVoxelizationGeometryLibrary // Author : Design Engineering Lab // Created : 03-05-2015 // // Last Modified By : Matt Campbell // Last Modified On : 05-28-2016 // *********************************************************************** // <copyright file="ComplexifyTessellation.cs" company="Design Engineering Lab"> // Copyright © 2014 // </copyright> // <summary></summary> // *********************************************************************** using System; using System.Collections.Generic; using System.Linq; namespace TVGL { /// <summary> /// This portion of ModifyTessellation includes the functions to complexify a solid, which means /// adding more elements to it. /// </summary> public static partial class ModifyTessellation { /// <summary> /// Complexifies the model by splitting the any edges that are half or more than the longest edge. /// </summary> /// <param name="ts">The ts.</param> public static void Complexify(this TessellatedSolid ts) { Complexify(ts, ts.NumberOfFaces / 2, ts.Edges.Max(x => x.Length) * 0.5); } /// <summary> /// Complexifies the tessellation by adding more faces of the provided number. /// </summary> /// <param name="ts">The ts.</param> /// <param name="numberOfNewFaces">The number of faces.</param> public static void Complexify(this TessellatedSolid ts, int numberOfNewFaces) { Complexify(ts, numberOfNewFaces, 0.0); } /// <summary> /// Complexifies the tessellation so that no edge is longer than provided the maximum edge length. /// </summary> /// <param name="ts">The ts.</param> /// <param name="maxLength">The tolerance.</param> public static void Complexify(this TessellatedSolid ts, double maxLength) { Complexify(ts, -1, maxLength); } /// <summary> /// Complexifies the tesssellation so that no edge is longer than provided the maximum edge length /// or for adding the provided number of faces - whichever comes first /// </summary> /// <param name="ts">The ts.</param> /// <param name="numberOfFaces">The number of new faces to add.</param> /// <param name="maxLength">The maximum length.</param> public static void Complexify(TessellatedSolid ts, int numberOfFaces, double maxLength) { var sortedEdges = new SortedSet<Edge>(ts.Edges, new SortByLength(false)); var addedEdges = new List<Edge>(); var addedVertices = new List<Vertex>(); var addedFaces = new List<PolygonalFace>(); var edge = sortedEdges.First(); var iterations = numberOfFaces > 0 ? (int)Math.Ceiling(numberOfFaces / 2.0) : numberOfFaces; while (iterations-- != 0 && edge.Length >= maxLength) { sortedEdges.Remove(edge); var origLeftFace = edge.OtherFace; var origRightFace = edge.OwnedFace; var leftFarVertex = origLeftFace.OtherVertex(edge); var rightFarVertex = origRightFace.OtherVertex(edge); var fromVertex = edge.From; var toVertex = edge.To; var addedVertex = new Vertex(DetermineIntermediateVertexPosition(fromVertex, toVertex)); // modify original faces with new intermediate vertex var index = origLeftFace.Vertices.IndexOf(toVertex); origLeftFace.Vertices[index] = addedVertex; origLeftFace.Update(); addedVertex.Faces.Add(origLeftFace); index = origRightFace.Vertices.IndexOf(toVertex); origRightFace.Vertices[index] = addedVertex; origRightFace.Update(); addedVertex.Faces.Add(origRightFace); var newLeftFace = new PolygonalFace(new[] { toVertex, addedVertex, leftFarVertex }, true); var newRightFace = new PolygonalFace(new[] { addedVertex, toVertex, rightFarVertex }, true); toVertex.Faces.Remove(origLeftFace); toVertex.Faces.Remove(origRightFace); var inlineEdge = new Edge(addedVertex, toVertex, newRightFace, newLeftFace, true); toVertex.Edges.Remove(edge); edge.To = addedVertex; addedVertex.Edges.Add(edge); edge.Update(); var newLeftEdge = new Edge(leftFarVertex, addedVertex, origLeftFace, newLeftFace, true); var newRightEdge = new Edge(rightFarVertex, addedVertex, newRightFace, origRightFace, true); origLeftFace.AddEdge(newLeftEdge); origRightFace.AddEdge(newRightEdge); var bottomEdge = toVertex.Edges.First(e => e.OtherVertex(toVertex) == leftFarVertex); if (bottomEdge.OwnedFace == origLeftFace) bottomEdge.OwnedFace = newLeftFace; else bottomEdge.OtherFace = newLeftFace; newLeftFace.AddEdge(bottomEdge); bottomEdge.Update(); bottomEdge = toVertex.Edges.First(e => e.OtherVertex(toVertex) == rightFarVertex); if (bottomEdge.OwnedFace == origRightFace) bottomEdge.OwnedFace = newRightFace; else bottomEdge.OtherFace = newRightFace; newRightFace.AddEdge(bottomEdge); bottomEdge.Update(); // need to re-add the edge. It was modified in the SplitEdge function (now, half the lenght), but // it may still be met by this criteria sortedEdges.Add(edge); sortedEdges.Add(inlineEdge); addedEdges.Add(inlineEdge); sortedEdges.Add(newLeftEdge); addedEdges.Add(newLeftEdge); sortedEdges.Add(newRightEdge); addedEdges.Add(newRightEdge); addedFaces.Add(newLeftFace); addedFaces.Add(newRightFace); addedVertices.Add(addedVertex); edge = sortedEdges.First(); } ts.AddVertices(addedVertices); ts.AddEdges(addedEdges); ts.AddFaces(addedFaces); } } }
46.442857
113
0.573054
[ "MIT" ]
micampbell/TVGLSTEPImport
TessellationAndVoxelizationGeometryLibrary/TessellatedSolid/ModifyTessellation/ComplexifyTessellation.cs
6,505
C#
using System.Threading; namespace MemoryLeak { public class ShortLivedEventPublisher { public static int Count; private readonly IEventPublisher publisher; public ShortLivedEventPublisher(IEventPublisher publisher) { this.publisher = publisher; Interlocked.Increment(ref Count); } public void PublishSomething() { publisher.Publish("Hello world"); } ~ShortLivedEventPublisher() { Interlocked.Decrement(ref Count); } } }
22
66
0.596154
[ "MIT" ]
Janek91/-EventMemoryLeakExample
MemoryLeak/ShortLivedEventPublisher.cs
574
C#
using System.Collections.Generic; using System.Windows.Forms; using NUnit.Framework; using RaceGame2.Lib.Cars; using RaceGame2.Lib.Maps; namespace RaceGame2.Lib.Tests { class CheckpointTest { [Test] public void testCheckpoint() { Car car = new Pickup(); car.TestMode = true; car.SetImage("green"); car.setControls(Keys.Left, Keys.Right, Keys.Up, Keys.Down, Keys.RControlKey); car.player = 1; List<Car> cars = new List<Car> {car}; Map map = new DirtMap{TestMode = true}; map.cars = cars; map.cars[0].position.X = 0; map.cars[0].position.Y = 0; //checkpoint test for (int i = 0; i < map.checkpoints.Count; i++) { map.cars[0].position.X = (map.checkpoints[i].Value[0].X + map.checkpoints[i].Value[1].X) / 2; map.cars[0].position.Y = (map.checkpoints[i].Value[0].Y + map.checkpoints[i].Value[1].Y) / 2; map.checkpointChecker(); Assert.AreEqual(i + 1, map.cars[0].checkpointCounter); } //lapcounter test int lapCounter = car.lapCounter; map.cars[0].position.X = (map.checkpoints[0].Value[0].X + map.checkpoints[0].Value[1].X) / 2; map.cars[0].position.Y = (map.checkpoints[0].Value[0].Y + map.checkpoints[0].Value[1].Y) / 2; car.checkpointCounter = map.checkpoints.Count; map.checkpointChecker(); Assert.AreEqual(lapCounter + 1, car.lapCounter); //respawn position map.cars[0].position.X = (map.pitstop[0].X + map.pitstop[1].X) / 2; map.cars[0].position.Y = (map.pitstop[0].Y + map.pitstop[1].Y) / 2; map.pitstopChecker(); Assert.AreEqual(1, map.cars[0].checkpointCounter); } } }
35.90566
109
0.549658
[ "Apache-2.0" ]
aranna00/racegame
RaceGame2/Tests/CheckpointTest.cs
1,905
C#
using Bing.Biz.OAuthLogin.Core; namespace Bing.Biz.OAuthLogin.Alibaba { /// <summary> /// 阿里巴巴授权提供程序 /// </summary> public interface IAlibabaAuthorizationProvider: IAuthorizationUrlProvider<AlibabaAuthorizationRequest> { } }
20.916667
106
0.713147
[ "MIT" ]
Alean-singleDog/Bing.NetCore
src/Bing.Biz.OAuthLogin/Alibaba/IAlibabaAuthorizationProvider.cs
273
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; using static Utils; using static TilemapManager; public static class Terrain { // Constants public const float HEIGHT_DIFF = 0.2f; //0.3f default //height difference used to calc. heightmap values from noise public const float H_NOISE_FREQUENCY = 0.25f; //frequency of height noise // Scriptable Tiles public static TerrainTile terrain_tile; // Physics public static Dictionary<int, float[]> collider_types = new Dictionary<int, float[]>(); public static Mesh ridge_mesh = new Mesh(); public static List<GameObject> ground_objs = new List<GameObject>(); public static List<GameObject> ridge_objs = new List<GameObject>(); //============== // Initialize //============== public static void initialize() { // custom tiles // ------------ terrain_tile = Resources.Load<TerrainTile>("Tiles/TerrainTile"); // physics colliders // ----------------- // collider types according to mask in order to account for non uniform box shapes // collider_type[index] = new float[] { x_init, y_init, x_size, y_size }; collider_types[14] = new float[] { 0f, 0f, 1, 0.1f }; // top flat tile collider_types[6] = new float[] { 0.87f , 0f, 0.13f, 0.1f }; // top left corner collider_types[12] = new float[] { 0f, 0f, 0.13f, 0.1f }; // top right corner collider_types[7] = new float[] { 0.87f, 0f, 0.13f, 1f }; // left outer flat wall collider_types[3] = new float[] { 0.87f, 0f, 0.13f, 1f }; // left outer corner wall collider_types[13] = new float[] { 0f, 0f, 0.13f, 1f }; // right outer wall collider_types[9] = new float[] { 0f, 0f, 0.13f, 1f }; // right outer corner wall // create the ridge_mesh List<Vector3> verts = new List<Vector3> { new Vector3(1, 1, 0), // top right, 0 new Vector3(1, 0, 0), // bottom right, 1 new Vector3(0, 0, 0), // bottom left, 2 new Vector3(0, 1, 0), // top left, 3 new Vector3(0, 1, -LEVEL_HEIGHT), // upper top left, 4 new Vector3(1, 1, -LEVEL_HEIGHT), // upper top right, 5 }; List<int> tris = new List<int> { // clockwise // main ridge 0, 1, 3, 3, 1, 2, // bottom 4, 2, 3, 5, 0, 1, // sides 5, 4, 3, 3, 0, 5, // back 4, 1, 2, 4, 5, 1, // front }; ridge_mesh.vertices = verts.ToArray(); ridge_mesh.triangles = tris.ToArray(); } //============== // Load //============== public static void load() { loadGraphics(); loadPhysics(); } public static void loadGraphics() { fillMap(); cleanMap(); fillMaskmap(); } public static void loadPhysics() { int i = 0, j = 0, z = 0; GameObject ground_obj; GameObject ridge_obj; // create ridge colliders for (z = 0; z < MAX_LEVEL; ++z) { ridge_obj = new GameObject("Ridge_Colliders_" + z); ridge_obj.transform.parent = parent_obj.transform; ridge_obj.layer = 10; ridge_objs.Add(ridge_obj); } for (int y = top_left.y; y < top_left.y + CHUNK_HEIGHT; ++y) { i = 0; for (int x = top_left.x; x < top_left.x + CHUNK_WIDTH; ++x) { for (z = 0; z < MAX_LEVEL; ++z) { createRidgeCollider(i, j, new Vector2Int(x, y), z); } i++; } j++; } // create merged colliders for (z = 0; z < MAX_LEVEL; ++z) { ground_obj = new GameObject("Ground_Colliders_" + z); ground_obj.transform.parent = parent_obj.transform; ground_obj.layer = 9; ground_objs.Add(ground_obj); } j = 0; for (int y = top_left.y; y < top_left.y + CHUNK_HEIGHT; ++y) { i = 0; for (int x = top_left.x; x < top_left.x + CHUNK_WIDTH; ++x) { for (z = 0; z < MAX_LEVEL; ++z) { if (!map[i, j].merged[z] && map[i, j].level >= z) { createMergedCollider(x, y, i, j, z); } } i++; } j++; } } //============== // Reload //============== public static void reload() { // delete old resources // TODO replace with deactivating objects/ using an object pool foreach(GameObject o in ground_objs) { GameObject.Destroy(o); } foreach(GameObject o in ridge_objs) { GameObject.Destroy(o); } // load new resources load(); } //================ // Helpers //================ public static void fillMap() { // fill map with initial height values from perlin noise for (int y = 0; y < map.GetLength(1); y++) { for (int x = 0; x < map.GetLength(0); x++) { float h = noise(x + current_map_center.x, y + current_map_center.y, H_NOISE_FREQUENCY); map[x, y].raw_height = h; map[x, y].level = Mathf.FloorToInt(h / HEIGHT_DIFF); map[x, y].tile_height = -map[x, y].level * LEVEL_HEIGHT; } } } public static void cleanMap() { // clean values in the map // List<int> illegal_values = new List<int> { 0, 1, 2, 4, 5, 8, 10 }; // CHUNK_WIDTH = map.GetLength(0); // CHUNK_HEIGHT = map.GetLength(1); // Debug.Log("CHUNK_WIDTH == CHUNK_WIDTH" + CHUNK_WIDTH == CHUNK_WIDTH); // int z = 0; // int mask; // for (int y = 0; y < CHUNK_HEIGHT; y++) { // for (int x = 0; x < CHUNK_WIDTH; x++) { // z = 0; // while (z < MAX_LEVEL) { // for (int i = 0; i < 3; i++) { // // remove illegal values // mask = y + 1 < CHUNK_HEIGHT && map[x, y + 1, z] == 1 ? 1 : 0; //top // mask += x + 1 < CHUNK_WIDTH && map[x + 1, y, z] == 1 ? 2 : 0; //right // mask += y - 1 >= 0 && map[x, y - 1, z] == 1 ? 4 : 0; //bottom // mask += x - 1 >= 0 && map[x - 1, y, z] == 1 ? 8 : 0; //left // // if (illegal_values.Contains(mask)) { // map[x, y, z] = 0; // } // // // check 110 at x = 0, 0110 every where, 011 at x - 3 == CHUNK_WIDTH horizontal // // if ((x == 0 && map[x, y, z] == 1 && map[x + 1, y, z] == 1 // && map[x + 2, y, z] == 0) || (x + 3 == CHUNK_WIDTH // && map[x, y, z] == 0 && map[x + 1, y, z] == 1 // && map[x + 2, y, z] == 1) || (x + 3 < CHUNK_WIDTH // && map[x, y, z] == 0 && map[x + 1, y, z] == 1 // && map[x + 2, y, z] == 1 && map[x + 3, y, z] == 0)) { // map[x, y, z] = 0; // map[x + 1, y, z] = 0; // map[x + 2, y, z] = 0; // } // // // remove 110, 0110, 011 vertical paterns // // if ((y + 3 < CHUNK_HEIGHT && map[x, y, z] == 0 && map[x, y + 1, z] == 1 // && map[x, y + 2, z] == 1 && map[x, y + 3, z] == 0)) { // map[x, y, z] = 0; // map[x, y + 1, z] = 0; // map[x, y + 2, z] = 0; // } // } // z++; // } // } // } } public static void fillMaskmap() { // mask values hold a bit mask indicating the neighbors of each MapTile for (int y = 0; y < CHUNK_HEIGHT; ++y) { for (int x = 0; x < CHUNK_WIDTH; ++x) { for (int z = 0; z < MAX_LEVEL; ++z) { int mask = y + 1 < CHUNK_HEIGHT && map[x, y + 1].level >= z ? 1 : 0; //top mask += x + 1 < CHUNK_WIDTH && map[x + 1, y].level >= z ? 2 : 0; //right mask += y - 1 >= 0 && map[x, y - 1].level >= z ? 4 : 0; //bottom mask += x - 1 >= 0 && map[x - 1, y].level >= z ? 8 : 0; //left map[x, y].mask[z] = mask; } } } } public static bool isRidge(int init_i, int init_j, int z) { int mask = map[init_i, init_j].mask[z]; bool create_ridge = false; if (mask == 11) { create_ridge = true; } else if (mask == 15) { // find mask2 since mask == 15 means we have neighbors right, left, top, bottom int x = init_i; int y = init_j; int mask2 = x + 1 < CHUNK_WIDTH && y + 1 < CHUNK_HEIGHT && map[x + 1, y + 1].level >= z ? 1 : 0; // top_right mask2 += x - 1 >= 0 && y + 1 < CHUNK_HEIGHT && map[x - 1, y + 1].level >= z ? 2 : 0; // top_left mask2 += x + 1 < CHUNK_WIDTH && y - 1 >= 0 && map[x + 1, y - 1].level >= z ? 4 : 0; // bottom_right mask2 += x - 1 >= 0 && y - 1 >= 0 && map[x - 1, y - 1].level >= z ? 8 : 0; // bottom_left // if bottom_right or bottom_left is empty this is a ridge if (mask2 == 11 || mask2 == 7) { create_ridge = true; // if top_left or top_right is not empty we don't have a corner, thus this is a flat tile } else if (mask2 != 13 && mask2 != 14) { if (z == map[init_i, init_j].level) { map[init_i, init_j].isFlat = true; } } } if (create_ridge) { map[init_i, init_j].isRidge = true; } return create_ridge; } public static void createRidgeCollider(int init_i, int init_j, Vector2Int init_pos, int z) { if (!isRidge(init_i, init_j, z)) return; // means this index is already accounted for by collider physics map[init_i, init_j].merged[z] = true; GameObject ridge_obj = ridge_objs[z]; MeshCollider ridge_collider = ridge_obj.AddComponent<MeshCollider>(); ridge_collider.convex = true; Mesh world_ridge_mesh = new Mesh(); world_ridge_mesh.vertices = modelToWorld(ridge_mesh.vertices, init_pos, z); world_ridge_mesh.triangles = ridge_mesh.triangles; ridge_collider.sharedMesh = world_ridge_mesh; } public static Vector3[] modelToWorld(Vector3[] verts, Vector2Int init_pos, int z) { Vector3 new_pos = new Vector3(init_pos.x, init_pos.y, (z * -LEVEL_HEIGHT) + LEVEL_HEIGHT); for (int i = 0; i < verts.Length; ++i) { verts[i] += new_pos; } return verts; } public static void createMergedCollider(float init_x, float init_y, int init_i, int init_j, int z) { BoxCollider new_collider; int i = init_i, j = init_j; int mask = map[init_i, init_j].mask[z]; float[] c_type; if (!collider_types.TryGetValue(mask, out c_type)) c_type = new float[] { 0f, 0f, 1f, 1f }; float true_init_x = init_x + c_type[0], true_init_y = init_y + c_type[1]; float x_size = c_type[2], y_size = c_type[3]; GameObject ground_obj = ground_objs[z]; if (mask == 12 || mask == 6) { map[i, j].merged[z] = true; new_collider = ground_obj.AddComponent<BoxCollider>(); new_collider.size = new Vector3(x_size, y_size, LEVEL_HEIGHT); new_collider.center = new Vector3(true_init_x + x_size * 0.5f, true_init_y + y_size * 0.5f, -z * LEVEL_HEIGHT + LEVEL_HEIGHT * 0.5f); return; } // find x_size and x_count // ----------------------- float[] other_c_type; Vector2 expected_init = new Vector2(true_init_x + x_size, true_init_y); Vector2 current_cell = new Vector2(init_x + 1, init_y); int x_count = 1; i++; // if the next collider is not already in the merge map we can proceed while (i < map.GetLength(0) && map[i, j].level >= z && !map[i, j].merged[z]) { mask = map[i, j].mask[z]; if (!collider_types.TryGetValue(mask, out other_c_type)) other_c_type = new float[] { 0f, 0f, 1f, 1f }; // if the next collider starts where the prev collider ends and has the same y size // we can merge horizontally if (expected_init == current_cell + new Vector2(other_c_type[0], other_c_type[1]) && c_type[3] == other_c_type[3] && !map[i, j].merged[z]) { expected_init = new Vector2(current_cell.x + other_c_type[0] + other_c_type[2], expected_init.y); current_cell.x += 1; x_size += other_c_type[2]; x_count++; } else { // exit the loop we found a value we cannot merge i = map.GetLength(0); } i++; } // find y_size and y_count // ----------------------- j = init_j + 1; int y_count = 1; int current_x_count; float current_x_size; while (j < map.GetLength(1)) { current_x_count = 0; current_x_size = 0; i = init_i; // next vertical collider can merge if x_init for the collider == x_init for first collider // and if the next collider is not merged already mask = map[i, j].mask[z]; if (!collider_types.TryGetValue(mask, out other_c_type)) other_c_type = new float[] { 0f, 0f, 1f, 1f }; if (c_type[0] == other_c_type[0] && map[i, j].level >= z && !map[i, j].merged[z]) { c_type = other_c_type; current_cell = new Vector2(init_x, init_y + y_count); expected_init = new Vector2(current_cell.x + c_type[0] + c_type[2], current_cell.y + c_type[1]); current_x_count = 1; current_x_size = c_type[2]; current_cell.x += 1; i++; // check horizontal values while (i < init_i + x_count && i < map.GetLength(0) && map[i, j].level >= z && !map[i, j].merged[z]) { mask = map[i, j].mask[z]; if (!collider_types.TryGetValue(mask, out other_c_type)) other_c_type = new float[] { 0f, 0f, 1f, 1f }; if (expected_init == current_cell + new Vector2(other_c_type[0], other_c_type[1]) && c_type[3] == other_c_type[3]) { expected_init = new Vector2(current_cell.x + other_c_type[0] + other_c_type[2], expected_init.y); current_cell.x += 1; current_x_count++; current_x_size += other_c_type[2]; i++; } else { // exit while loop we found a value we cannot merge i = map.GetLength(0); } } } else { // initial value does not work complete loop j = map.GetLength(1); } if (current_x_count == x_count && current_x_size == x_size) { y_count++; y_size += c_type[3]; } else { // complete loop we know y_size and y_count j = map.GetLength(1); } j++; } // update merged values in merge map // --------------------------------- for (i = init_i; i < init_i + x_count; i++) { for (j = init_j; j < init_j + y_count; j++) { map[i, j].merged[z] = true; } } // create collider // --------------- new_collider = ground_obj.AddComponent<BoxCollider>(); // size = BR - TL // center = TL + SIZE * 0.5f new_collider.size = new Vector3(x_size, y_size, LEVEL_HEIGHT); new_collider.center = new Vector3(true_init_x + x_size * 0.5f, true_init_y + y_size * 0.5f, -z * LEVEL_HEIGHT + LEVEL_HEIGHT * 0.5f); } }
40.275701
130
0.454287
[ "MIT" ]
obecerra3/OpenWorld2D_Unity
Scripts/World/Terrain.cs
17,238
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. #nullable disable using System; using System.Linq; using Microsoft.Extensions.Internal; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp { // Note: This type should be kept in sync with the one in Razor.LanguageServer assembly. internal class RazorMapToDocumentEditsParams : IEquatable<RazorMapToDocumentEditsParams> { public RazorLanguageKind Kind { get; set; } public Uri RazorDocumentUri { get; set; } public TextEdit[] ProjectedTextEdits { get; set; } public TextEditKind TextEditKind { get; set; } public FormattingOptions FormattingOptions { get; set; } // Everything below this is for testing purposes only. public bool Equals(RazorMapToDocumentEditsParams other) { if (object.ReferenceEquals(this, other)) { return true; } return other != null && Kind == other.Kind && RazorDocumentUri == other.RazorDocumentUri && Enumerable.SequenceEqual(ProjectedTextEdits?.Select(p => p.NewText), other.ProjectedTextEdits?.Select(p => p.NewText)) && Enumerable.SequenceEqual(ProjectedTextEdits?.Select(p => p.Range), other.ProjectedTextEdits?.Select(p => p.Range)) && TextEditKind == other.TextEditKind && IsEqual(other.FormattingOptions); } public override bool Equals(object obj) { return Equals(obj as RazorMapToDocumentEditsParams); } public override int GetHashCode() { var hash = new HashCodeCombiner(); hash.Add(Kind); hash.Add(RazorDocumentUri); hash.Add(ProjectedTextEdits); return hash; } private bool IsEqual(FormattingOptions other) { if (FormattingOptions is null || other is null) { return FormattingOptions == other; } return FormattingOptions.InsertSpaces == other.InsertSpaces && FormattingOptions.TabSize == other.TabSize && (object.ReferenceEquals(FormattingOptions.OtherOptions, other.OtherOptions) || (FormattingOptions.OtherOptions != null && other.OtherOptions != null && FormattingOptions.OtherOptions.OrderBy(k => k.Key).SequenceEqual(other.OtherOptions.OrderBy(k => k.Key)))); } } }
36.445946
137
0.621431
[ "MIT" ]
50Wliu/razor-tooling
src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/RazorMapToDocumentEditsParams.cs
2,699
C#
using FlatRedBall.Glue.CodeGeneration; using FlatRedBall.Glue.CodeGeneration.CodeBuilder; using FlatRedBall.Glue.Parsing; using FlatRedBall.Glue.SaveClasses; using System; using System.Collections.Generic; using System.Text; using ToolsUtilities; namespace OfficialPlugins.Compiler.CodeGeneration { class CompilerPluginElementCodeGenerator : ElementComponentCodeGenerator { public override ICodeBlock GenerateFields(ICodeBlock codeBlock, IElement element) { if(MainPlugin.MainViewModel.IsGenerateGlueControlManagerInGame1Checked && element is EntitySave && // If it has a base element, then the base will handle this... string.IsNullOrEmpty(element.BaseElement)) { codeBlock.Line($"public string EditModeType {{ get; set; }} = \"{CodeWriter.GetGlueElementNamespace(element as GlueElement)}.{FileManager.RemovePath(element.Name)}\";"); } return codeBlock; } } }
38.269231
185
0.710553
[ "MIT" ]
vchelaru/FlatRedBall
FRBDK/Glue/OfficialPlugins/Compiler/CodeGeneration/CompilerPluginElementCodeGenerator.cs
997
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101 { using Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.PowerShell; /// <summary>Defines the request body for bulk remove of move resources operation.</summary> [System.ComponentModel.TypeConverter(typeof(BulkRemoveRequestTypeConverter))] public partial class BulkRemoveRequest { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.BulkRemoveRequest" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal BulkRemoveRequest(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).ValidateOnly = (bool?) content.GetValueForProperty("ValidateOnly",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).ValidateOnly, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResource = (string[]) content.GetValueForProperty("MoveResource",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResource, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResourceInputType = (Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Support.MoveResourceInputType?) content.GetValueForProperty("MoveResourceInputType",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResourceInputType, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Support.MoveResourceInputType.CreateFrom); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.BulkRemoveRequest" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal BulkRemoveRequest(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).ValidateOnly = (bool?) content.GetValueForProperty("ValidateOnly",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).ValidateOnly, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResource = (string[]) content.GetValueForProperty("MoveResource",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResource, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResourceInputType = (Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Support.MoveResourceInputType?) content.GetValueForProperty("MoveResourceInputType",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequestInternal)this).MoveResourceInputType, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Support.MoveResourceInputType.CreateFrom); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.BulkRemoveRequest" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequest" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequest DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new BulkRemoveRequest(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.BulkRemoveRequest" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequest" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequest DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new BulkRemoveRequest(content); } /// <summary> /// Creates a new instance of <see cref="BulkRemoveRequest" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IBulkRemoveRequest FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Defines the request body for bulk remove of move resources operation. [System.ComponentModel.TypeConverter(typeof(BulkRemoveRequestTypeConverter))] public partial interface IBulkRemoveRequest { } }
74
487
0.713814
[ "MIT" ]
Amrinder-Singh29/azure-powershell
src/ResourceMover/generated/api/Models/Api202101/BulkRemoveRequest.PowerShell.cs
9,856
C#
//The MIT License (MIT) // //Copyright (c) 2015 Fabian Fischer // //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 IProxy.DataSerializing; namespace IProxy.Networking.ClientPackets { public class ShootAckPacket : ClientPacket { public int Time { get; set; } public override PacketID ID { get { return PacketID.SHOOTACK; } } public override Packet CreateInstance() { return new ShootAckPacket(); } protected override void Read(DReader rdr) { Time = rdr.ReadInt32(); } protected override void Write(DWriter wtr) { wtr.Write(Time); } } }
35.040816
80
0.695399
[ "MIT" ]
ossimc82/RotMG-Proxy-Alpha-
IProxy/networking/cliPackets/ShootAckPacket.cs
1,719
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 Xunit; using Xunit.Abstractions; using System.IO; using System.Linq; using System.Xml.Schema; namespace System.Xml.Tests { public class TC_SchemaSet_AnyAttribute : TC_SchemaSetBase { private readonly ITestOutputHelper _output; private int _errorCount; private int _warningCount; private bool _warningInnerExceptionSet; private bool _errorInnerExceptionSet; public TC_SchemaSet_AnyAttribute(ITestOutputHelper output) { _output = output; } //hook up validaton callback private void ValidationCallback(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { _output.WriteLine("WARNING: "); _warningCount++; _warningInnerExceptionSet = (args.Exception.InnerException != null); _output.WriteLine("\nInnerExceptionSet : " + _warningInnerExceptionSet + "\n"); } else if (args.Severity == XmlSeverityType.Error) { _output.WriteLine("ERROR: "); _errorCount++; _errorInnerExceptionSet = (args.Exception.InnerException != null); _output.WriteLine("\nInnerExceptionSet : " + _errorInnerExceptionSet + "\n"); } _output.WriteLine(args.Message); } public XmlSchema GetUnionSchema(string ns1, string ns2, string attrNs) { var xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='" + attrNs + @"' xmlns='" + attrNs + @"'> <xs:attribute name='baseattribute'> <xs:simpleType > <xs:restriction base = 'xs:int' > <xs:maxInclusive value = '1000' /> </xs:restriction > </xs:simpleType > </xs:attribute > <xs:complexType name = 't'> <xs:sequence > <xs:element name = 'e1' type = 'xs:string' /> </xs:sequence > <xs:anyAttribute namespace='" + ns2 + @"'/> </xs:complexType> <xs:complexType name = 't1'> <xs:complexContent> <xs:extension base='t'> <xs:sequence > <xs:element name = 'e2' type = 'xs:string' /> </xs:sequence> <xs:anyAttribute namespace='" + ns1 + @"'/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name = 't2'> <xs:complexContent> <xs:restriction base='t1'> <xs:sequence > <xs:element name = 'e1' type = 'xs:string' fixed='name'/> <xs:element name = 'e2' type = 'xs:string' fixed='name'/> </xs:sequence > <xs:attribute ref='baseattribute'/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema>"; return XmlSchema.Read(new StringReader(xsd), null); } public XmlSchema GetIntersectionSchema(string ns1, string ns2, string attrNs) { var xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='" + attrNs + @"' xmlns='" + attrNs + @"'> <xs:attribute name='baseattribute'> <xs:simpleType > <xs:restriction base = 'xs:int' > <xs:maxInclusive value = '1000' /> </xs:restriction > </xs:simpleType > </xs:attribute > <xs:attributeGroup name = 'attr-gr' > <xs:attribute name = 'a1' type = 'xs:int' /> <xs:anyAttribute namespace='" + ns2 + @"'/> </xs:attributeGroup > <xs:complexType name = 't'> <xs:sequence > <xs:element name = 'e1' type = 'xs:string' /> </xs:sequence > <xs:attributeGroup ref='attr-gr' /> <xs:anyAttribute namespace='" + ns1 + @"'/> </xs:complexType> <xs:complexType name = 't1'> <xs:complexContent> <xs:restriction base='t'> <xs:sequence > <xs:element name = 'e1' type = 'xs:string' fixed='name'/> </xs:sequence > <xs:attribute ref='baseattribute'/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:schema>"; return XmlSchema.Read(new StringReader(xsd), null); } public XmlSchema GetSimpleSchema(string ns, string attrNs) { var xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='" + attrNs + @"' xmlns='" + attrNs + @"'> <xs:complexType name = 't'> <xs:sequence > <xs:element name = 'e1' type = 'xs:string' /> </xs:sequence > <xs:anyAttribute namespace='" + ns + @"'/> </xs:complexType> </xs:schema>"; return XmlSchema.Read(new StringReader(xsd), null); } //Intersection namespaces [Theory] //[Variation(Desc = "complextype Any ns - ##any, attrgroup Any ns2, allow ns2 attribute")] [InlineData("##any", "ns2", "ns2", 0, "##targetNamespace")] //[Variation(Desc = "complextype Any ns - ##any, attrgroup Any ns2, not allow ns1 attribute")] [InlineData("##any", "ns2", "ns1", 1)] //[Variation(Desc = "complextype Any ns - ns2, attrgroup Any ##any, allow ns2 attribute")] [InlineData("ns2", "##any", "ns2", 0, "##targetNamespace")] //[Variation(Desc = "complextype Any ns - ns2, attrgroup Any ##any, not allow ns1 attribute")] [InlineData("ns2", "##any", "ns1", 1)] //[Variation(Desc = "complextype Any ns - ns1 ns2, attrgroup Any ##other, not allow ns1 attribute")] [InlineData("ns1 ns2", "##other", "ns1", 1)] //[Variation(Desc = "complextype Any ns - ns1 ns2, attrgroup Any ##other, not allow ns2 attribute")] [InlineData("ns1 ns2", "##other", "ns2", 1)] //[Variation(Desc = "complextype Any ns - ns1 ns2, attrgroup Any #other, not allow ns3 attribute")] [InlineData("ns1 ns2", "##other", "ns3", 1)] //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ns1 ns2, not allow ns1 attribute")] [InlineData("##other", "ns1 ns2", "ns1", 1)] //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ns1 ns2, not allow ns2 attribute")] [InlineData("##other", "ns1 ns2", "ns2", 1)] //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ns1 ns2, not allow ns3 attribute")] [InlineData("##other", "ns1 ns2", "ns3", 1)] //[Variation(Desc = "complextype Any ns - ns1 ns3, attrgroup Any ns1 ns2, not allow ns3 attribute")] [InlineData("ns1 ns3", "ns1 ns2", "ns3", 1)] //[Variation(Desc = "complextype Any ns - ns1 ns3, attrgroup Any ns1 ns2, not allow ns2 attribute")] [InlineData("ns1 ns3", "ns1 ns2", "ns2", 1)] //[Variation(Desc = "complextype Any ns - ns1 ns3, attrgroup Any ns1 ns2, allow ns1 attribute")] [InlineData("ns1 ns3", "ns1 ns2", "ns1", 0, "ns1")] //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ##other, not allow ns1 attribute")] [InlineData("##other", "##other", "ns1", 1)] public void v1(string ns1, string ns2, string attrNs, int expectedError, string expectedNs = null) { XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); xss.Add(GetIntersectionSchema(ns1, ns2, attrNs)); xss.Compile(); Assert.Equal(expectedError, _errorCount); // .NET Framework does not set the namespace property for intersections and unions if (!PlatformDetection.IsNetFramework && expectedNs != null) { XmlSchemaAnyAttribute attributeWildcard = ((XmlSchemaComplexType)xss.GlobalTypes[new XmlQualifiedName("t", attrNs)]).AttributeWildcard; CompareWildcardNamespaces(expectedNs, attributeWildcard.Namespace); } } [Theory] //[Variation(Desc = "basetype Any ns - ##any, derivedType Any ns - ns1, allow ns2 attribute")] [InlineData("##any", "ns1", "ns2", 0, "##any")] //[Variation(Desc = "basetype Any ns - ns1, derivedType Any ns - ##any, allow ns2 attribute")] [InlineData("ns1", "##any", "ns2", 0, "##any")] //[Variation(Desc = "basetype Any ns - ns1 ns2, derivedType Any ns - ns2 ns3 , allow ns3 attribute")] [InlineData("ns1 ns2", "ns2 ns3", "ns3", 0, "ns1 ns2 ##targetNamespace")] //[Variation(Desc = "basetype Any ns - ##other, derivedType Any ns - ##other , not allow current ns")] [InlineData("##other", "##other", "ns1", 1)] //[Variation(Desc = "basetype Any ns - ns1 ns2, derivedType Any ns - ##other , allow ns1")] [InlineData("ns1 ns2", "##other", "ns1", 0, "##other")] //[Variation(Desc = "basetype Any ns - ns1 ns2, derivedType Any ns - ##other , allow ns2")] [InlineData("ns1 ns2", "##other", "ns2", 0, "##other")] //[Variation(Desc = "basetype Any ns - ##other, derivedType Any ns - ns1 ns2 , allow ns2")] [InlineData("##other", "ns1 ns2", "ns1", 0, "##other")] //[Variation(Desc = "basetype Any ns - ##other, derivedType Any ns - ns1 ns2 , allow ns2")] [InlineData("##other", "ns1 ns2", "ns2", 0, "##other")] public void v2(string ns1, string ns2, string attrNs, int expectedError, string expectedNs = null) { XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); xss.Add(GetUnionSchema(ns1, ns2, attrNs)); xss.Compile(); Assert.Equal(expectedError, _errorCount); // .NET Framework does not set the namespace property for intersections and unions if (!PlatformDetection.IsNetFramework && expectedNs != null) { XmlSchemaAnyAttribute attributeWildcard = ((XmlSchemaComplexType)xss.GlobalTypes[new XmlQualifiedName("t1", attrNs)]).AttributeWildcard; CompareWildcardNamespaces(expectedNs, attributeWildcard.Namespace); } } [Theory] //[Variation(Desc = "ns - ##any, allow any attribute")] [InlineData("##any", "ns1", "##any")] //[Variation(Desc = "ns - ##other, not allow ns1 attribute")] [InlineData("##other", "ns1", "##other")] //[Variation(Desc = "ns - ns1 ns2, allow ns1 and ns2 attribute")] [InlineData("ns1 ns2", "ns1", "ns1 ns2")] //[Variation(Desc = "##targetNamespace, allow current ns")] [InlineData("##targetNamespace", "ns1", "##targetNamespace")] public void v3(string ns, string attrNs, string expectedNs) { XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); xss.Add(GetSimpleSchema(ns, attrNs)); xss.Compile(); XmlSchemaAnyAttribute attributeWildcard = ((XmlSchemaComplexType)xss.GlobalTypes[new XmlQualifiedName("t", attrNs)]).AttributeWildcard; CompareWildcardNamespaces(expectedNs, attributeWildcard.Namespace); } [Fact] public void NewInstanceReturnsNullNamespace() { var any = new XmlSchemaAnyAttribute(); Assert.Null(any.Namespace); } [Fact] public void ReadFromFileWithoutNamespaceReturnsNull() { var xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='ns'> <xs:complexType name = 't'> <xs:anyAttribute/> </xs:complexType> </xs:schema>"; XmlSchema xs = XmlSchema.Read(new StringReader(xsd), null); XmlSchemaAnyAttribute any = ((XmlSchemaComplexType)xs.Items[0]).AnyAttribute; Assert.Null(any.Namespace); } private static void CompareWildcardNamespaces(string expected, string actual) { var orderedExpected = string.Join(" ", expected.Split(' ').OrderBy(ns => ns)); var orderedActual = string.Join(" ", actual.Split(' ').OrderBy(ns => ns)); Assert.Equal(orderedExpected, orderedActual); } } }
51.341912
152
0.527103
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/TC_SchemaSet_AnyAttribute.cs
13,967
C#
namespace UnityEditor.TestTools.TestRunner.GUI { internal class RenderingOptions { public string nameFilter; public bool showSucceeded; public bool showFailed; public bool showIgnored; public bool showNotRunned; public string[] categories; } }
24.307692
47
0.639241
[ "MIT" ]
AI-Pree/Small-World
Library/PackageCache/com.unity.test-framework@1.1.24/UnityEditor.TestRunner/GUI/TestListBuilder/RenderingOptions.cs
316
C#
/* Copyright 2010-2012 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MongoDB.Bson.Serialization { /// <summary> /// Modifies a member map. /// </summary> public interface IBsonMemberMapModifier { /// <summary> /// Applies a modification to the member map. /// </summary> /// <param name="memberMap">The member map.</param> void Apply(BsonMemberMap memberMap); } }
29.628571
74
0.701061
[ "Apache-2.0" ]
nilayparikh/mongo-csharp-driver
Bson/Serialization/IBsonMemberMapModifier.cs
1,039
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace AESEncryptDecyptFile { public class SettingsProvider { [DllImport("kernel32.dll")] private static extern long WritePrivateProfileString(string section, string key, string val, string filepath); [DllImport("kernel32.dll")] private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath); /// <summary> /// szFile: This is a path of file INI /// szSection: This is a key type, which formatted: [AutoLogin] \n etc=value /// szKey: This is a key title, which formatted: etc=value /// </summary> /// <param name="szFile"></param> /// <param name="szSection"></param> /// <param name="szKey"></param> /// <returns></returns> public static string ReadSettings(string szFile, string szSection, string szKey) { StringBuilder builder = new StringBuilder(255); long i = GetPrivateProfileString(szSection, szKey, "", builder, 255, szFile); return builder.ToString(); } /// <summary> /// szFile: This is a path of file INI /// szSection: This is a key type, which formatted: [AutoLogin] \n etc=value /// szKey: This is a key title, which formatted: etc=value /// szData: This is a value of key title, which formatted: etc=value /// </summary> /// <param name="szFile"></param> /// <param name="szSection"></param> /// <param name="szKey"></param> /// <param name="szData"></param> public static void WriteSettings(string szFile, string szSection, string szKey, string szData) { WritePrivateProfileString(szSection, szKey, szData, szFile); } public bool checkFileSettingsAvailble(string path, int action) { if (!File.Exists(path) && action == 0) { return false; } else if (!File.Exists(path) && action == 1) { File.Create(path); return true; } else if (File.Exists(path) && action == 0) { return true; } else if (File.Exists(path) && action == 1) { return true; } return true; } } }
36.383562
149
0.552711
[ "MIT" ]
Duy-Thanh/AESEncryptDecryptFile
AESEncryptDecyptFile/AESEncryptDecyptFile/SettingsProvider.cs
2,658
C#
// The MIT License(MIT) // // Copyright(c) 2021 Alberto Rodriguez Orozco & LiveCharts Contributors // // 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 LiveChartsCore.Drawing; using LiveChartsCore.SkiaSharpView.Drawing; using SkiaSharp.Views.Desktop; using SkiaSharp.Views.WPF; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace LiveChartsCore.SkiaSharpView.WPF { /// <summary> /// Defines the motion canvas control for WPF, <see cref="MotionCanvas{TDrawingContext}"/>. /// </summary> /// <seealso cref="Control" /> public class MotionCanvas : Control { /// <summary> /// The skia element /// </summary> protected SKElement? skiaElement; private bool _isDrawingLoopRunning = false; static MotionCanvas() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MotionCanvas), new FrameworkPropertyMetadata(typeof(MotionCanvas))); } /// <summary> /// Initializes a new instance of the <see cref="MotionCanvas"/> class. /// </summary> public MotionCanvas() { CanvasCore.Invalidated += OnCanvasCoreInvalidated; Unloaded += OnUnloaded; } /// <summary> /// The paint tasks property /// </summary> public static readonly DependencyProperty PaintTasksProperty = DependencyProperty.Register( nameof(PaintTasks), typeof(HashSet<IDrawableTask<SkiaSharpDrawingContext>>), typeof(MotionCanvas), new PropertyMetadata(new HashSet<IDrawableTask<SkiaSharpDrawingContext>>(), new PropertyChangedCallback(OnPaintTaskChanged))); /// <summary> /// Gets or sets the paint tasks. /// </summary> /// <value> /// The paint tasks. /// </value> public HashSet<IDrawableTask<SkiaSharpDrawingContext>> PaintTasks { get => (HashSet<IDrawableTask<SkiaSharpDrawingContext>>)GetValue(PaintTasksProperty); set => SetValue(PaintTasksProperty, value); } /// <summary> /// Gets or sets the frames per second. /// </summary> /// <value> /// The frames per second. /// </value> public double FramesPerSecond { get; set; } = 90; /// <summary> /// Gets the canvas core. /// </summary> /// <value> /// The canvas core. /// </value> public MotionCanvas<SkiaSharpDrawingContext> CanvasCore { get; } = new(); /// <inheritdoc cref="OnApplyTemplate" /> public override void OnApplyTemplate() { base.OnApplyTemplate(); skiaElement = Template.FindName("skiaElement", this) as SKElement; if (skiaElement == null) throw new Exception( $"SkiaElement not found. This was probably caused because the control {nameof(MotionCanvas)} template was overridden, " + $"If you override the template please add an {nameof(SKElement)} to the template and name it 'skiaElement'"); skiaElement.PaintSurface += OnPaintSurface; } /// <inheritdoc cref="OnPaintSurface(object?, SKPaintSurfaceEventArgs)" /> protected virtual void OnPaintSurface(object? sender, SKPaintSurfaceEventArgs args) { (var dpiX, var dpiY) = GetPixelDensity(); args.Surface.Canvas.Scale(dpiX, dpiY); CanvasCore.DrawFrame(new SkiaSharpDrawingContext(CanvasCore, args.Info, args.Surface, args.Surface.Canvas)); } private (float dpiX, float dpiY) GetPixelDensity() { var presentationSource = PresentationSource.FromVisual(this); if (presentationSource == null) return (1f, 1f); var compositionTarget = presentationSource.CompositionTarget; if (compositionTarget == null) return (1f, 1f); var matrix = compositionTarget.TransformToDevice; return ((float)matrix.M11, (float)matrix.M22); } private void OnCanvasCoreInvalidated(MotionCanvas<SkiaSharpDrawingContext> sender) { RunDrawingLoop(); } private void OnUnloaded(object sender, RoutedEventArgs e) { CanvasCore.Invalidated -= OnCanvasCoreInvalidated; } private async void RunDrawingLoop() { if (_isDrawingLoopRunning || skiaElement == null) return; _isDrawingLoopRunning = true; var ts = TimeSpan.FromSeconds(1 / FramesPerSecond); while (!CanvasCore.IsValid) { skiaElement.InvalidateVisual(); await Task.Delay(ts); } _isDrawingLoopRunning = false; } private static void OnPaintTaskChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var motionCanvas = (MotionCanvas)sender; motionCanvas.CanvasCore.SetPaintTasks(motionCanvas.PaintTasks); } } }
37.640244
142
0.640369
[ "MIT" ]
SheepChao/LiveCharts2
src/skiasharp/LiveChartsCore.SkiaSharp.WPF/MotionCanvas.cs
6,175
C#
namespace UpgradeOctoSystem.Abstractions.Enums { public enum BlobContainers { None, SomeFile } }
15.625
47
0.632
[ "Unlicense" ]
d3ullist/upgraded-octo-system
UpgradeOctoSystem/UpgradeOctoSystem.Abstractions/Enums/BlobContainers.cs
127
C#
using System; namespace SharpOffice.Core.Attributes { /// <summary> /// Specifies SharpOffice applications that may load this class or assembly. /// </summary> [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public class ApplicationAttribute : Attribute { public string Application { get; private set; } public ApplicationAttribute(string application) { Application = application; } } }
25.714286
80
0.65
[ "MIT" ]
manio143/SharpOffice
SharpOffice.Core/Attributes/ApplicationAttribute.cs
542
C#
using System; using Bridge.Html5; using Philadelphia.Common; namespace Philadelphia.Web { public class LoginFormView : IFormView<HTMLElement> { public InputView Login { get; } = new InputView(I18n.Translate("Username")) .With(x => x.InputWidget.Name = "username") .With(x => x.InputWidget.SetAttribute("autocapitalize", "none")); //to make autocomplete work better public InputView Password { get; } = new InputView(I18n.Translate("Password"), InputView.TypePassword) .With(x => x.InputWidget.Name = "password"); //to make autocomplete work better public IActionView<HTMLElement> AttemptLogin { get; } public LoginFormView(Func<LabelDescr,IActionView<HTMLElement>> customActionBuilder = null) { AttemptLogin = (customActionBuilder ?? Toolkit.DefaultActionBuilder) .Invoke(new LabelDescr {Label = I18n.Translate("Login")}) .With(x => x.MarkAsFormsDefaultButton()); } public RenderElem<HTMLElement>[] Render(HTMLElement _) { return new RenderElem<HTMLElement>[] { $"<div class='{Magics.CssClassTableLike}' style='position: relative'>", Login, Password, "</div>" }; } public IView<HTMLElement>[] Actions => new IView<HTMLElement>[] {AttemptLogin}; } }
43.53125
112
0.623833
[ "Apache-2.0" ]
todo-it/philadelphia
Philadelphia.Web/Mvp/Forms/LoginFormView.cs
1,393
C#
namespace Tauron.Application.ImageOrginazer.ViewModels.Views.ContainerManager { public class SyncErrorNoStade { } }
19.571429
78
0.715328
[ "MIT" ]
Tauron1990/ImageOrgenizer
Tauron.Application.ImageOrginazer.ViewModels/Views/ContainerManager/SyncErrorNoStade.cs
139
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.Runtime.InteropServices; using Microsoft.AspNetCore.Razor.TagHelpers; namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers; /// <summary> /// A class used to run <see cref="ITagHelper"/>s. /// </summary> public class TagHelperRunner { /// <summary> /// Calls the <see cref="ITagHelperComponent.ProcessAsync"/> method on <see cref="ITagHelper"/>s. /// </summary> /// <param name="executionContext">Contains information associated with running <see cref="ITagHelper"/>s. /// </param> /// <returns>Resulting <see cref="TagHelperOutput"/> from processing all of the /// <paramref name="executionContext"/>'s <see cref="ITagHelper"/>s.</returns> public Task RunAsync(TagHelperExecutionContext executionContext) { if (executionContext == null) { throw new ArgumentNullException(nameof(executionContext)); } var tagHelperContext = executionContext.Context; var tagHelpers = CollectionsMarshal.AsSpan(executionContext.TagHelperList); tagHelpers.Sort(default(SortTagHelpers)); foreach (var tagHelper in tagHelpers) { tagHelper.Init(tagHelperContext); } var tagHelperOutput = executionContext.Output; for (var i = 0; i < tagHelpers.Length; i++) { var task = tagHelpers[i].ProcessAsync(tagHelperContext, tagHelperOutput); if (!task.IsCompletedSuccessfully) { return Awaited(task, executionContext, i + 1, tagHelpers.Length); } } return Task.CompletedTask; static async Task Awaited(Task task, TagHelperExecutionContext executionContext, int i, int count) { await task; var tagHelpers = executionContext.TagHelperList; var tagHelperOutput = executionContext.Output; var tagHelperContext = executionContext.Context; for (; i < count; i++) { await tagHelpers[i].ProcessAsync(tagHelperContext, tagHelperOutput); } } } private readonly struct SortTagHelpers : IComparer<ITagHelper> { public int Compare(ITagHelper left, ITagHelper right) => left.Order.CompareTo(right.Order); } }
34.15493
110
0.645361
[ "MIT" ]
3ejki/aspnetcore
src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperRunner.cs
2,425
C#
// // BinaryConverterFactory.cs // This file is part of Stardust // // Author: Jonas Syrstad (jsyrstad2+StardustCore@gmail.com), http://no.linkedin.com/in/jonassyrstad/) // Copyright (c) 2014 Jonas Syrstad. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, 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 Stardust.Clusters.Converters; using Stardust.Nucleus; namespace Stardust.Clusters.Clusters { public static class BinaryConverterFactory { public static IBinaryConverter CreateConverter(ConverterTypes converterType) { return Resolver.Activate<IBinaryConverter>(converterType); } } }
40.219512
102
0.751364
[ "Apache-2.0" ]
JonasSyrstad/Stardust.Nucleus
Stardust.Clusters/Clusters/BinaryConverterFactory.cs
1,651
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Text; using Kalk.Core.Helpers; using Scriban.Functions; using Scriban.Helpers; using Scriban.Runtime; using Scriban.Syntax; namespace Kalk.Core { /// <summary> /// Misc module (builtin). /// </summary> public sealed partial class MiscModule : KalkModuleWithFunctions { public const string CategoryMisc = "Misc Functions"; public static readonly Encoding EncodingExtendedAscii = CodePagesEncodingProvider.Instance.GetEncoding(1252); public MiscModule() { IsBuiltin = true; DateObject = new DateTimeFunctions {Format = "%D %T"}; RegisterFunctionsAuto(); } /// <summary> /// The date object used by the <see cref="Date"/> function. /// </summary> public DateTimeFunctions DateObject { get; } /// <summary> /// Gets the current date, parse the input date or return the date object, depending on use cases. /// - If this function doesn't have any parameter and is not used to index a member, it returns the current date. It is equivalent of `date.now` /// /// The return date object has the following properties: /// /// | Name | Description /// |-------------- |----------------- /// | `.year` | Gets the year of a date object /// | `.month` | Gets the month of a date object /// | `.day` | Gets the day in the month of a date object /// | `.day_of_year` | Gets the day within the year /// | `.hour` | Gets the hour of the date object /// | `.minute` | Gets the minute of the date object /// | `.second` | Gets the second of the date object /// | `.millisecond` | Gets the millisecond of the date object /// /// - If this function has a string parameter, it will try to parse the string as a date /// - Otherwise, if this function provides the following sub functions and members: /// - `date.add_days`: Example `'2016/01/05' |> date |> date.add_days 1` /// - `date.add_months`: Example `'2016/01/05' |> date |> date.add_months 1` /// - `date.add_years`: Example `'2016/01/05' |> date |> date.add_years 1` /// - `date.add_hours` /// - `date.add_minutes` /// - `date.add_seconds` /// - `date.add_milliseconds` /// - `date.to_string`: Converts a datetime object to a textual representation using the specified format string. /// /// By default, if you are using a date, it will use the format specified by `date.format` which defaults to `date.default_format` (readonly) which default to `%d %b %Y` /// /// You can override the format used for formatting all dates by assigning the a new format: `date.format = '%a %b %e %T %Y';` /// /// You can recover the default format by using `date.format = date.default_format;` /// /// By default, the to_string format is using the **current culture**, but you can switch to an invariant culture by using the modifier `%g` /// /// For example, using `%g %d %b %Y` will output the date using an invariant culture. /// /// If you are using `%g` alone, it will output the date with `date.format` using an invariant culture. /// /// Suppose that `date.now` would return the date `2013-09-12 22:49:27 +0530`, the following table explains the format modifiers: /// /// | Format | Result | Description /// |--------|-------------------|-------------------------------------------- /// | `"%a"` | `"Thu"` | Name of week day in short form of the /// | `"%A"` | `"Thursday"` | Week day in full form of the time /// | `"%b"` | `"Sep"` | Month in short form of the time /// | `"%B"` | `"September"` | Month in full form of the time /// | `"%c"` | | Date and time (%a %b %e %T %Y) /// | `"%C"` | `"20"` | Century of the time /// | `"%d"` | `"12"` | Day of the month of the time /// | `"%D"` | `"09/12/13"` | Date (%m/%d/%y) /// | `"%e"` | `"12"` | Day of the month, blank-padded ( 1..31) /// | `"%F"` | `"2013-09-12"` | ISO 8601 date (%Y-%m-%d) /// | `"%h"` | `"Sep"` | Alias for %b /// | `"%H"` | `"22"` | Hour of the time in 24 hour clock format /// | `"%I"` | `"10"` | Hour of the time in 12 hour clock format /// | `"%j"` | `"255"` | Day of the year (001..366) (3 digits, left padded with zero) /// | `"%k"` | `"22"` | Hour of the time in 24 hour clock format, blank-padded ( 0..23) /// | `"%l"` | `"10"` | Hour of the time in 12 hour clock format, blank-padded ( 0..12) /// | `"%L"` | `"000"` | Millisecond of the time (3 digits, left padded with zero) /// | `"%m"` | `"09"` | Month of the time /// | `"%M"` | `"49"` | Minutes of the time (2 digits, left padded with zero e.g 01 02) /// | `"%n"` | | Newline character (\n) /// | `"%N"` | `"000000000"` | Nanoseconds of the time (9 digits, left padded with zero) /// | `"%p"` | `"PM"` | Gives AM / PM of the time /// | `"%P"` | `"pm"` | Gives am / pm of the time /// | `"%r"` | `"10:49:27 PM"` | Long time in 12 hour clock format (%I:%M:%S %p) /// | `"%R"` | `"22:49"` | Short time in 24 hour clock format (%H:%M) /// | `"%s"` | | Number of seconds since 1970-01-01 00:00:00 +0000 /// | `"%S"` | `"27"` | Seconds of the time /// | `"%t"` | | Tab character (\t) /// | `"%T"` | `"22:49:27"` | Long time in 24 hour clock format (%H:%M:%S) /// | `"%u"` | `"4"` | Day of week of the time (from 1 for Monday to 7 for Sunday) /// | `"%U"` | `"36"` | Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) /// | `"%v"` | `"12-SEP-2013"` | VMS date (%e-%b-%Y) (culture invariant) /// | `"%V"` | `"37"` | Week number of the current year according to ISO 8601 (01..53) /// | `"%W"` | `"36"` | Week number of the current year, starting with the first Monday as the first day of the first week (00..53) /// | `"%w"` | `"4"` | Day of week of the time (from 0 for Sunday to 6 for Saturday) /// | `"%x"` | | Preferred representation for the date alone, no time /// | `"%X"` | | Preferred representation for the time alone, no date /// | `"%y"` | `"13"` | Gives year without century of the time /// | `"%Y"` | `"2013"` | Year of the time /// | `"%Z"` | `"IST"` | Gives Time Zone of the time /// | `"%%"` | `"%"` | Output the character `%` /// /// Note that the format is using a good part of the ruby format ([source](http://apidock.com/ruby/DateTime/strftime)) /// </summary> /// <returns>The current date, parse the input date or return the date object, depending on use cases.</returns> /// <example> /// ```kalk /// >>> today = date /// # today = date /// today = 11/22/20 10:13:00 /// >>> today.year /// # today.year /// out = 2020 /// >>> today.month /// # today.month /// out = 11 /// >>> "30 Nov 2020" |> date /// # "30 Nov 2020" |> date /// out = 11/30/20 00:00:00 /// >>> out |> date.add_days 4 /// # out |> date.add_days(4) /// out = 12/04/20 00:00:00 /// >>> date.format = "%F" /// >>> date /// # date /// out = 2020-11-22 /// ``` /// </example> [KalkExport("date", CategoryMisc)] public object Date(string date = null) { if (!string.IsNullOrEmpty(date)) { return DateTimeFunctions.Parse(Engine, date); } // If we are used in the context an expression that doesn't use a member of the date object // then return the current date var parentNode = Engine.CurrentNode.Parent; if (parentNode != null && !(parentNode is ScriptMemberExpression || parentNode is ScriptIndexerExpression)) { // In testing, we return a fake method return Engine.IsTesting ? new DateTime(2020, 11, 22, 10, 13, 00) : DateTimeFunctions.Now(); } return DateObject; } /// <summary> /// Prints the ascii table or convert an input string to an ascii array, or an ascii array to a string. /// </summary> /// <param name="obj">An optional input (string or array of numbers or directly an integer).</param> /// <returns>Depending on the input: /// - If no input, it will display the ascii table /// - If the input is an integer, it will convert it to the equivalent ascii char. /// - If the input is a string, it will convert the string to a byte buffer containing the corresponding ascii bytes. /// - If the input is an array of integer, it will convert each element to the equivalent ascii char. /// </returns> /// <example> /// ```kalk /// >>> ascii 65 /// # ascii(65) /// out = "A" /// >>> ascii 97 /// # ascii(97) /// out = "a" /// >>> ascii "A" /// # ascii("A") /// out = 65 /// >>> ascii "kalk" /// # ascii("kalk") /// out = bytebuffer([107, 97, 108, 107]) /// >>> ascii out /// # ascii(out) /// out = "kalk" /// ``` /// </example> [KalkExport("ascii", CategoryMisc)] public object Ascii(object obj = null) { if (obj == null && Engine.CurrentNode.Parent is ScriptExpressionStatement) { var builder = new StringBuilder(); const int alignControls = -38; const int alignStandard = 13; const int columnWidth = 3 + 4 + 1; for (int y = 0; y < 32; y++) { builder.Length = 0; for (int x = 0; x < 8; x++) { var c = x * 32 + y; if (x > 0) builder.Append(" "); var index = $"{c,3}"; var valueAsString = StringFunctions.Escape(ConvertAscii(c)); var strValue = $"\"{valueAsString}\""; var column = x == 0 ? $"{index} {strValue,-6} {$"({AsciiSpecialCodes[y]})",-27}" : $"{index} {strValue,-4}"; OutputColumn(builder, x, column); } if (y == 0) { Engine.WriteHighlightLine($" {"ASCII controls",alignControls} {"ASCII printable characters",-(columnWidth * 2 + alignStandard + 1)} {"Extended ASCII Characters"}"); } Engine.WriteHighlightLine(builder.ToString()); } void OutputColumn(StringBuilder output, int columnIndex, string text) { output.Append(columnIndex == 0 ? $"{text,-alignControls}" : columnIndex == 3 ? $"{text,-alignStandard}" : $"{text}"); } return null; } // Otherwise convert the argument. return ConvertAscii(Engine, obj); } /// <summary> /// Returns the keys of the specified object. /// </summary> /// <param name="obj">An object to get the keys from.</param> /// <returns>The keys of the parameter obj.</returns> /// <example> /// ```kalk /// >>> obj = {m: 1, n: 2}; keys obj /// # obj = {m: 1, n: 2}; keys(obj) /// obj = {m: 1, n: 2} /// out = ["m", "n"] /// ``` /// </example> [KalkExport("keys", CategoryMisc)] public IEnumerable Keys(object obj) { return ObjectFunctions.Keys(Engine, obj); } /// <summary> /// Returns a new GUID as a string. /// </summary> /// <returns>A new GUID as a string.</returns> /// <example> /// ```kalk /// >>> guid /// # guid /// out = "0deafe30-de4d-47c3-9631-2d3292afbb8e" /// ``` /// </example> [KalkExport("guid", CategoryMisc)] public string Guid() { return Engine.IsTesting ? "0deafe30-de4d-47c3-9631-2d3292afbb8e" : System.Guid.NewGuid().ToString(); } /// <summary> /// Returns the size of the specified object. /// </summary> /// <param name="obj">The object value.</param> /// <returns>The size of the object.</returns> /// <example> /// ```kalk /// >>> size 1 /// # size(1) /// out = 0 /// >>> size "kalk" /// # size("kalk") /// out = 4 /// >>> size float4(1,2,3,4) /// # size(float4(1, 2, 3, 4)) /// out = 4 /// >>> size [1, 2, 3] /// # size([1, 2, 3]) /// out = 3 /// ``` /// </example> [KalkExport("size", CategoryMisc)] public int Size(object obj) { return ObjectFunctions.Size(obj); } /// <summary> /// Returns the values of the specified object. /// </summary> /// <param name="obj">An object to get the values from.</param> /// <returns>The values of the parameter obj.</returns> /// <example> /// ```kalk /// >>> obj = {m: 1, n: 2}; values obj /// # obj = {m: 1, n: 2}; values(obj) /// obj = {m: 1, n: 2} /// out = [1, 2] /// ``` /// </example> [KalkExport("values", CategoryMisc)] public IEnumerable Values(object obj) { switch (obj) { case IDictionary<string, object> dict: return ObjectFunctions.Values(dict); case IEnumerable list: return new ScriptArray(list); default: return new ScriptArray() {obj}; } } /// <summary> /// Converts an integral/bytebuffer input to an hexadecimal representation or convert an hexadecimal input string /// to an integral/bytebuffer representation. /// </summary> /// <param name="value">The input value.</param> /// <param name="separator">The character used to separate hexadecimal bytes when converting /// from integral to hexadecimal.</param> /// <param name="prefix">Output the prefix `0x` in front of each hexadecimal bytes when converting /// from integral to hexadecimal.</param> /// <returns>The hexadecimal representation of the input or convert the hexadecimal input string /// to an integral representation.</returns> /// <remarks> When converting from a hexadecimal string to an integral representation, this method /// will skip any white-space characters, comma `,`, colon `:`, semi-colon `;`, underscore `_` and /// dash `-`. /// When the hexadecimal input string can be converted to an integral less than or equal 8 bytes (64 bits) /// it will convert it to a single integral result, otherwise it will convert to a bytebuffer. /// See the following examples. /// </remarks> /// <example> /// ```kalk /// >>> hex 10 /// # hex(10) /// out = "0A" /// >>> hex "0a" /// # hex("0a") /// out = 10 /// >>> hex "0xff030201" /// # hex("0xff030201") /// out = 4278387201 /// >>> hex out /// # hex(out) /// out = "01 02 03 FF" /// >>> hex "01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F" /// # hex("01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F") /// out = bytebuffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) /// >>> hex(out, true, ",") /// # hex(out, true, ",") /// out = "0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F" /// >>> hex out /// # hex(out) /// out = bytebuffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) /// >>> hex("1a,2b;3c 4d-5e_6f") /// # hex("1a,2b;3c 4d-5e_6f") /// out = 103832130169626 /// >>> hex out /// # hex(out) /// out = "1A 2B 3C 4D 6F 5E 00 00" /// >>> hex float4(1,2,3,4) /// # hex(float4(1, 2, 3, 4)) /// out = "00 00 80 3F 00 00 00 40 00 00 40 40 00 00 80 40" /// ``` /// </example> /// <test> /// ```kalk /// >>> hex short(12345) /// # hex(short(12345)) /// out = "39 30" /// >>> hex int (12345789) /// # hex(int(12345789)) /// out = "BD 61 BC 00" /// ``` /// </test> [KalkExport("hex", CategoryMisc)] public object Hexadecimal(object value, bool prefix = false, string separator = " ") { return Hexadecimal(value, prefix, separator, false); } /// <summary> /// Converts an integral/bytebuffer input to a binary representation or convert a binary input string /// to an integral/bytebuffer representation. /// </summary> /// <param name="value">The input value.</param> /// <param name="prefix">Output the prefix `0x` in front of each binary bytes when converting /// from integral to binary.</param> /// <param name="separator">The character used to separate binary bytes when converting /// from integral to binary.</param> /// <returns>The binary representation of the input or convert the binary input string /// to an integral representation.</returns> /// <remarks> When converting from a binary string to an integral representation, this method /// will skip any white-space characters, comma `,`, colon `:`, semi-colon `;`, underscore `_` and /// dash `-`. /// When the binary input string can be converted to an integral less than or equal 8 bytes (64 bits) /// it will convert it to a single integral result, otherwise it will convert to a bytebuffer. /// See the following examples. /// </remarks> /// <example> /// ```kalk /// >>> bin 10 /// # bin(10) /// out = "00001010 00000000 00000000 00000000" /// >>> bin out /// # bin(out) /// out = 10 /// >>> bin 0xff030201 /// # bin(-16580095) /// out = "00000001 00000010 00000011 11111111" /// >>> bin out /// # bin(out) /// out = 4278387201 /// >>> bin "11111111000000110000001000000001" /// # bin("11111111000000110000001000000001") /// out = 4278387201 /// >>> bin(byte(5)) /// # bin(byte(5)) /// out = "00000101" /// >>> bin(long(6)) /// # bin(long(6)) /// out = "00000110 00000000 00000000 00000000 00000000 00000000 00000000 00000000" /// >>> bin(out) /// # bin(out) /// out = 6 /// >>> kind(out) /// # kind(out) /// out = "long" /// ``` /// </example> [KalkExport("bin", CategoryMisc)] public object Binary(object value, bool prefix = false, string separator = " ") { return Binary(value, prefix, separator, false); } /// <summary> /// Converts a string to an UTF8 bytebuffer or convert a bytebuffer of UTF8 bytes to a string. /// </summary> /// <param name="value">The specified input.</param> /// <returns>The UTF8 bytebuffer representation of the input string or the string representation of the input UTF8 bytebuffer.</returns> /// <example> /// ```kalk /// >>> utf8 "kalk" /// # utf8("kalk") /// out = bytebuffer([107, 97, 108, 107]) /// >>> utf8 out /// # utf8(out) /// out = "kalk" /// ``` /// </example> [KalkExport("utf8", CategoryMisc)] public object GetUtf8(object value) { switch (value) { case string str: { var buffer = Encoding.UTF8.GetBytes(str); return KalkNativeBuffer.AsBytes(buffer.Length, in buffer[0]); } case IEnumerable it: { var bytes = new MemoryStream(); foreach (var b in it) { bytes.WriteByte(Engine.ToObject<byte>(0, b)); } return Encoding.UTF8.GetString(bytes.GetBuffer(), 0, (int) bytes.Length); } default: throw new ArgumentException($"The type {Engine.GetTypeName(value)} is not supported ", nameof(value)); } } /// <summary> /// Converts a string to an UTF16 bytebuffer or convert a bytebuffer of UTF16 bytes to a string. /// </summary> /// <param name="value">The specified input.</param> /// <returns>The UTF16 bytebuffer representation of the input string or the string representation of the input UTF16 bytebuffer.</returns> /// <example> /// ```kalk /// >>> utf16 "kalk" /// # utf16("kalk") /// out = bytebuffer([107, 0, 97, 0, 108, 0, 107, 0]) /// >>> utf16 out /// # utf16(out) /// out = "kalk" /// ``` /// </example> [KalkExport("utf16", CategoryMisc)] public object GetUtf16(object value) { switch (value) { case string str: { unsafe { fixed (void* pBuffer = str) { return KalkNativeBuffer.AsBytes(str.Length * 2, in *(byte*)pBuffer); } } } case IEnumerable it: { var bytes = new MemoryStream(); foreach (var b in it) { bytes.WriteByte(Engine.ToObject<byte>(0, b)); } unsafe { fixed (void* pBuffer = bytes.GetBuffer()) return new string((char*) pBuffer, 0, (int) bytes.Length / 2); } } default: throw new ArgumentException($"The type {Engine.GetTypeName(value)} is not supported ", nameof(value)); } } /// <summary> /// Converts a string to an UTF32 bytebuffer or convert a bytebuffer of UTF32 bytes to a string. /// </summary> /// <param name="value">The specified input.</param> /// <returns>The UTF32 bytebuffer representation of the input string or the string representation of the input UTF32 bytebuffer.</returns> /// <example> /// ```kalk /// >>> utf32 "kalk" /// # utf32("kalk") /// out = bytebuffer([107, 0, 0, 0, 97, 0, 0, 0, 108, 0, 0, 0, 107, 0, 0, 0]) /// >>> utf32 out /// # utf32(out) /// out = "kalk" /// ``` /// </example> [KalkExport("utf32", CategoryMisc)] public object GetUtf32(object value) { switch (value) { case string str: { var buffer = Encoding.UTF32.GetBytes(str); return KalkNativeBuffer.AsBytes(buffer.Length, in buffer[0]); } case IEnumerable it: { var bytes = new MemoryStream(); foreach (var b in it) { bytes.WriteByte(Engine.ToObject<byte>(0, b)); } return Encoding.UTF32.GetString(bytes.GetBuffer(), 0, (int)bytes.Length); } default: throw new ArgumentException($"The type {Engine.GetTypeName(value)} is not supported ", nameof(value)); } } /// <summary> /// Inserts an item into a string or list at the specified index. /// </summary> /// <param name="list">A string or list to insert an item into.</param> /// <param name="index">The index at which to insert the item.</param> /// <param name="item">The item to insert.</param> /// <returns>A new string with the item inserted, or a new list with the item inserted at the specified index.</returns> /// <remarks>The index is adjusted at the modulo of the length of the input value. /// If the index is &lt; 0, then the index starts from the end of the string/list length + 1. A value of -1 for the index would insert the item at the end, after the last element of the string or list. /// </remarks> /// <example> /// ```kalk /// >>> insert_at("kalk", 0, "YES") /// # insert_at("kalk", 0, "YES") /// out = "YESkalk" /// >>> insert_at("kalk", -1, "YES") /// # insert_at("kalk", -1, "YES") /// out = "kalkYES" /// >>> insert_at(0..10, 1, 50) /// # insert_at(0..10, 1, 50) /// out = [0, 50, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] /// >>> insert_at(0..9, 21, 50) # final index is 21 % 10 = 1 /// # insert_at(0..9, 21, 50) # final index is 21 % 10 = 1 /// out = [0, 50, 1, 2, 3, 4, 5, 6, 7, 8, 9] /// >>> insert_at([], 3, 1) /// # insert_at([], 3, 1) /// out = [1] /// ``` /// </example> [KalkExport("insert_at", CategoryMisc)] public object InsertAt(object list, int index, object item) { if (list == null) throw new ArgumentNullException(nameof(list)); if (item == null) throw new ArgumentNullException(nameof(item)); if (list is string valueStr) { var itemStr = Engine.ObjectToString(item); index = valueStr.Length == 0 ? 0 : index < 0 ? valueStr.Length + (index + 1) % valueStr.Length : index % valueStr.Length; var builder = new StringBuilder(valueStr.Substring(0, index)); builder.Append(itemStr); if (index < valueStr.Length) { builder.Append(valueStr.Substring(index)); } return builder.ToString(); } else if (list is KalkNativeBuffer buffer) { var byteItem = Engine.ToObject<byte>(2, item); index = buffer.Count == 0 ? 0 : index < 0 ? buffer.Count + (index + 1) % buffer.Count : index % buffer.Count; var newBuffer = new KalkNativeBuffer(buffer.Count + 1); for (int i = 0; i < index; i++) newBuffer[i] = buffer[i]; newBuffer[index] = byteItem; for (int i = index + 1; i < newBuffer.Count; i++) newBuffer[i] = buffer[i - 1]; return newBuffer; } else if (list is IList listCollection) { index = listCollection.Count == 0 ? 0 : index < 0 ? listCollection.Count + (index + 1) % listCollection.Count : index % listCollection.Count; listCollection.Insert(index, item); return listCollection; } else { throw new ArgumentException($"The type {Engine.GetTypeName(list)} is not supported ", nameof(list)); } } /// <summary> /// Removes an item from a string or list at the specified index. /// </summary> /// <param name="list">A string or list to remove an item from.</param> /// <param name="index">The index at which to remove the item.</param> /// <returns>A new string/list with the item at the specified index removed.</returns> /// <remarks>The index is adjusted at the modulo of the length of the input value. /// If the index is &lt; 0, then the index starts from the end of the string/list length. A value of -1 for the index would remove the last element. /// </remarks> /// <example> /// ```kalk /// >>> remove_at("kalk", 0) /// # remove_at("kalk", 0) /// out = "alk" /// >>> remove_at("kalk", -1) /// # remove_at("kalk", -1) /// out = "kal" /// >>> remove_at(0..9, 5) /// # remove_at(0..9, 5) /// out = [0, 1, 2, 3, 4, 6, 7, 8, 9] /// >>> remove_at(0..9, -1) /// # remove_at(0..9, -1) /// out = [0, 1, 2, 3, 4, 5, 6, 7, 8] /// >>> remove_at(asbytes(0x04030201), 1) /// # remove_at(asbytes(67305985), 1) /// out = bytebuffer([1, 3, 4]) /// ``` /// </example> [KalkExport("remove_at", CategoryMisc)] public object RemoveAt(object list, int index) { if (list == null) throw new ArgumentNullException(nameof(list)); if (list is string valueStr) { if (valueStr == string.Empty) return valueStr; index = index < 0 ? valueStr.Length + index % valueStr.Length : index % valueStr.Length; var builder = new StringBuilder(valueStr.Substring(0, index)); if (index < valueStr.Length) { builder.Append(valueStr.Substring(index + 1)); } return builder.ToString(); } else if (list is KalkNativeBuffer buffer) { if (buffer.Count == 0) return buffer; index = index < 0 ? buffer.Count + index % buffer.Count : index % buffer.Count; var newBuffer = new KalkNativeBuffer(buffer.Count - 1); for (int i = 0; i < index; i++) newBuffer[i] = buffer[i]; for (int i = index; i < newBuffer.Count; i++) newBuffer[i] = buffer[i + 1]; return newBuffer; } else if (list is IList listCollection) { if (listCollection.Count == 0) return listCollection; index = index < 0 ? listCollection.Count + index % listCollection.Count : index % listCollection.Count; listCollection.RemoveAt(index); return listCollection; } else { throw new ArgumentException($"The type {Engine.GetTypeName(list)} is not supported ", nameof(list)); } } /// <summary> /// Checks if an object (string, list, vector types, bytebuffer...) is containing the specified value. /// </summary> /// <param name="list">The list to search into.</param> /// <param name="value">The value to search into the list.</param> /// <returns>true if value was found in the list input; otherwise false.</returns> /// <example> /// ```kalk /// >>> contains("kalk", "l") /// # contains("kalk", "l") /// out = true /// >>> contains("kalk", "e") /// # contains("kalk", "e") /// out = false /// >>> contains([1,2,3,4,5], 3) /// # contains([1,2,3,4,5], 3) /// out = true /// >>> contains([1,2,3,4,5], 6) /// # contains([1,2,3,4,5], 6) /// out = false /// >>> contains(float4(1,2,3,4), 3) /// # contains(float4(1, 2, 3, 4), 3) /// out = true /// >>> contains(float4(1,2,3,4), 6) /// # contains(float4(1, 2, 3, 4), 6) /// out = false /// ``` /// </example> [KalkExport("contains", CategoryMisc)] public KalkBool Contains(object list, object value) { if (list == null) throw new ArgumentNullException(nameof(list)); if (value == null) throw new ArgumentNullException(nameof(value)); if (list is string valueStr) { var matchStr = Engine.ObjectToString(value); return valueStr.Contains(matchStr, StringComparison.Ordinal); } var composite = new KalkCompositeValue(list); bool contains = false; // Force the evaluation of the object composite.Visit(Engine, Engine.CurrentSpan, input => { var result = (bool) ScriptBinaryExpression.Evaluate(Engine, Engine.CurrentSpan, ScriptBinaryOperator.CompareEqual, input, value); if (result) { contains = true; return false; } return true; }); return contains; } /// <summary> /// Replaces in an object (string, list, vector types, bytebuffer...) an item of the specified value by another value. /// </summary> /// <param name="list">The list to search into to replace an element.</param> /// <param name="value">The item to replace.</param> /// <param name="by">The value to replace with.</param> /// <returns>The modified object.</returns> /// <example> /// ```kalk /// >>> replace("kalk", "k", "woo") /// # replace("kalk", "k", "woo") /// out = "wooalwoo" /// >>> replace([1,2,3,4], 3, 5) /// # replace([1,2,3,4], 3, 5) /// out = [1, 2, 5, 4] /// >>> replace(float4(1,2,3,4), 3, 5) /// # replace(float4(1, 2, 3, 4), 3, 5) /// out = float4(1, 2, 5, 4) /// ``` /// </example> [KalkExport("replace", CategoryMisc)] public object Replace(object list, object value, object by) { if (list == null) throw new ArgumentNullException(nameof(list)); if (value == null) throw new ArgumentNullException(nameof(value)); if (@by == null) throw new ArgumentNullException(nameof(@by)); if (list is string valueStr) { var matchStr = Engine.ObjectToString(value); var byStr = Engine.ObjectToString(by); return valueStr.Replace(matchStr, byStr); } var composite = new KalkCompositeValue(list); return composite.Transform(Engine, Engine.CurrentSpan, input => ReplaceImpl(input, value, @by), typeof(object)); } /// <summary> /// Creates a slice of an object (string, list, vector types, bytebuffer...) starting at the specified index and with the specified length; /// </summary> /// <param name="list">The object to create a slice from.</param> /// <param name="index">The index into the object.</param> /// <param name="length">The optional length of the slice. If the length is not defined, the length will start from index with the remaining elements.</param> /// <returns>A slice of the input object.</returns> /// <remarks>The index is adjusted at the modulo of the specified length of the input object. /// If the index is &lt; 0, then the index starts from the end of the input object length. A value of -1 for the index would take a slice with the only the last element. /// </remarks> /// <example> /// ```kalk /// >>> slice("kalk", 1) /// # slice("kalk", 1) /// out = "alk" /// >>> slice("kalk", -2) /// # slice("kalk", -2) /// out = "lk" /// >>> slice("kalk", 1, 2) /// # slice("kalk", 1, 2) /// out = "al" /// >>> slice([1,2,3,4], 1) /// # slice([1,2,3,4], 1) /// out = [2, 3, 4] /// >>> slice([1,2,3,4], -1) /// # slice([1,2,3,4], -1) /// out = [4] /// >>> slice([1,2,3,4], -1, 3) # length is bigger than expected, no errors /// # slice([1,2,3,4], -1, 3) # length is bigger than expected, no errors /// out = [4] /// >>> slice(asbytes(0x04030201), 1, 2) /// # slice(asbytes(67305985), 1, 2) /// out = slice(bytebuffer([2, 3]), 1, 2) /// ``` /// </example> [KalkExport("slice", CategoryMisc)] public object Slice(object list, int index, int? length = null) { if (list is string str) { return StringFunctions.Slice(str, index, length); } var listCollection = list as IList; if (listCollection == null) { if (list is IEnumerable it) { listCollection = new ScriptRange(it); } else { throw new ArgumentException("The argument is not a string, bytebuffer or array.", nameof(list)); } } // Wrap index index = index < 0 ? listCollection.Count + index % listCollection.Count : index % listCollection.Count; // Compute length length ??= listCollection.Count; if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0"); } // Trim length if required if (index + length > listCollection.Count) { length = listCollection.Count - index; } if (list is KalkNativeBuffer nativeBuffer) { return nativeBuffer.Slice(index, length.Value); } return new ScriptRange(listCollection.Cast<object>().Skip(index).Take(length.Value)); } /// <summary> /// Extract lines from the specified string. /// </summary> /// <param name="text">A string to extract lines from.</param> /// <returns>Lines extracted from the input string.</returns> /// <example> /// ```kalk /// >>> lines("k\na\nl\nk") /// # lines("k\na\nl\nk") /// out = ["k", "a", "l", "k"] /// ``` /// </example> [KalkExport("lines", CategoryMisc)] public ScriptRange Lines(string text) { if (text == null) return new ScriptRange(); return new ScriptRange(new LineReader(() => new StringReader(text))); } /// <summary> /// Display or returns the known CSS colors. /// </summary> /// <returns>Prints known CSS colors or return a list if this function is used in an expression.</returns> /// <example> /// ```kalk /// >>> colors[0] /// # colors[0] /// out = rgb(240, 248, 255) ## F0F8FF AliceBlue ## /// >>> mycolor = colors["AliceBlue"]; mycolor.name /// # mycolor = colors["AliceBlue"]; mycolor.name /// mycolor = rgb(240, 248, 255) ## F0F8FF AliceBlue ## /// out = "AliceBlue" /// ``` /// </example> [KalkExport("colors", CategoryMisc)] public object Colors() { var knownColorsInternal = KalkColorRgb.GetKnownColors(); if (!(Engine?.CurrentNode is ScriptVariable) || !(Engine?.CurrentNode?.Parent is ScriptExpressionStatement)) { var colors = new ScriptArray(knownColorsInternal); foreach (var color in knownColorsInternal) { colors.SetValue(color.Name, color, false); } return colors; } var builder = new StringBuilder(); int count = 0; const int PerColumn = 2; foreach (var knownColor in knownColorsInternal) { var colorName = knownColor.ToString("aligned", Engine); builder.Append(colorName); count++; if (count == PerColumn) { Engine.WriteHighlightLine(builder.ToString()); builder.Clear(); count = 0; } else { builder.Append(" "); } } if (builder.Length > 0) { Engine.WriteHighlightLine(builder.ToString()); builder.Clear(); } return null; } private object ReplaceImpl(object value, object match, object by) { var result = (bool)ScriptBinaryExpression.Evaluate(Engine, Engine.CurrentSpan, ScriptBinaryOperator.CompareEqual, value, match); return result ? @by : value; } private object Hexadecimal(object value, bool prefix, string separator, bool returnString) { Engine.CheckAbort(); switch (value) { case string str when returnString: throw new ArgumentException($"Cannot convert a string to hexadecimal inside a list", nameof(value)); case string str: { var array = new List<byte>(); var temp = new List<byte>(); int count = 0; bool hasPrefix = false; int hexa = 0; void FlushBytes() { if (count > 0) { array.Add((byte)hexa); } count = 0; if (temp.Count > 0) { for (int j = temp.Count - 1; j >= 0; j--) { array.Add(temp[j]); } temp.Clear(); } } for (int i = 0; i < str.Length; i++) { var c = str[i]; if (char.IsWhiteSpace(c) || c == ',' || c == ':' || c == ';' || c == '_' || c == '-') { if (c != '_') { FlushBytes(); } hasPrefix = c == '_' && hasPrefix; // reset prefix after parsing but not for `_` continue; } // Skip 0x prefix if (!hasPrefix && c == '0' && i + 1 < str.Length && str[i + 1] == 'x') { FlushBytes(); hasPrefix = true; i++; continue; } //if (c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c ) if (CharHelper.TryHexaToInt(c, out var n)) { // TODO: Add parsing for 0x00 hexa = (hexa << 4) | n; if (count == 1) { temp.Add((byte)hexa); hexa = 0; count = 0; } else { count++; } } else { throw new ArgumentException($"Invalid character found `{StringFunctions.Escape(c.ToString())}`. Expecting only hexadecimal.", nameof(value)); } } FlushBytes(); if (array.Count <= 8) { long ulongValue = 0; unsafe { for (int i = 0; i < array.Count; i++) { ((byte*)&ulongValue)[i] = array[i]; } } return ulongValue; } return new KalkNativeBuffer(array); } case byte vbyte: return HexaFromBytes(1, vbyte, prefix, separator); case sbyte vsbyte: return HexaFromBytes(1, vsbyte, prefix, separator); case short vshort: { int size = 2; if (vshort >= sbyte.MinValue && vshort <= byte.MaxValue) size = 1; return HexaFromBytes(size, vshort, prefix, separator); } case ushort vushort: { int size = 2; if (vushort <= byte.MaxValue) size = 1; return HexaFromBytes(size, vushort, prefix, separator); } case int vint: { int size = 4; if (vint >= sbyte.MinValue && vint <= byte.MaxValue) size = 1; else if (vint >= short.MinValue && vint <= ushort.MaxValue) size = 2; return HexaFromBytes(size, vint, prefix, separator); } case uint vuint: { int size = 4; if (vuint <= byte.MaxValue) size = 1; else if (vuint <= ushort.MaxValue) size = 2; return HexaFromBytes(size, vuint, prefix, separator); } case long vlong: { int size = 8; if (vlong >= sbyte.MinValue && vlong <= byte.MaxValue) size = 1; else if (vlong >= short.MinValue && vlong <= ushort.MaxValue) size = 2; else if (vlong >= int.MinValue && vlong <= uint.MaxValue) size = 4; return HexaFromBytes(size, vlong, prefix, separator); } case ulong vulong: { int size = 8; if (vulong <= byte.MaxValue) size = 1; else if (vulong <= ushort.MaxValue) size = 2; else if (vulong <= uint.MaxValue) size = 4; return HexaFromBytes(size, vulong, prefix, separator); } case float vfloat: { var floatAsInt = BitConverter.SingleToInt32Bits(vfloat); return HexaFromBytes(4, floatAsInt, prefix, separator); } case double vdouble: { var doubleAsLong = BitConverter.DoubleToInt64Bits(vdouble); return HexaFromBytes(8, doubleAsLong, prefix, separator); } case BigInteger bigInt: { var array = bigInt.ToByteArray(); return HexaFromBytes(array.Length, array[0], prefix, separator); } case KalkValue kalkValue: { var span = kalkValue.AsSpan(); return HexaFromBytes(span.Length, span[0], prefix, separator); } case IEnumerable list: { var builder = new StringBuilder(); bool isFirst = true; foreach (var item in list) { if (!isFirst) { builder.Append(separator); } isFirst = false; byte byteItem = Engine.ToObject<byte>(0, item); if (prefix) builder.Append("0x"); builder.Append(byteItem.ToString("X2")); } return builder.ToString(); } default: throw new ArgumentException($"The type {Engine.GetTypeName(value)} is not supported ", nameof(value)); } } private static string HexaFromBytes<T>(int byteCount, in T element, bool prefix, string separator) { var builder = new StringBuilder(byteCount * 2); for (int i = 0; i < byteCount; i++) { if (i > 0) builder.Append(separator); var b = Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(element), new IntPtr(i))); if (prefix) builder.Append("0x"); builder.Append(b.ToString("X2")); } return builder.ToString(); } private object Binary(object value, bool prefix, string separator, bool returnString) { Engine.CheckAbort(); switch (value) { case string str when returnString: throw new ArgumentException($"Cannot convert a string to binary inside a list", nameof(value)); case string str: { var array = new List<byte>(); var temp = new List<byte>(); int count = 0; bool hasPrefix = false; int bin = 0; void FlushBytes() { if (count > 0) { array.Add((byte)bin); } bin = 0; count = 0; if (temp.Count > 0) { for (int j = temp.Count - 1; j >= 0; j--) { array.Add(temp[j]); } temp.Clear(); } } for (int i = 0; i < str.Length; i++) { var c = str[i]; if (char.IsWhiteSpace(c) || c == ',' || c == ':' || c == ';' || c == '_' || c == '-') { if (c != '_') { FlushBytes(); } hasPrefix = c == '_' && hasPrefix; // reset prefix after parsing but not for `_` continue; } // Skip 0b prefix if (!hasPrefix && c == '0' && i + 1 < str.Length && str[i + 1] == 'b') { FlushBytes(); hasPrefix = true; i++; continue; } if (c == '0' || c == '1') { bin = (bin << 1) | (c - '0'); if (count == 7) { temp.Add((byte)bin); bin = 0; count = 0; } else { count++; } } else { throw new ArgumentException($"Invalid character found `{StringFunctions.Escape(c.ToString())}`. Expecting only binary 0 or 1.", nameof(value)); } } FlushBytes(); if (array.Count <= 8) { long ulongValue = 0; unsafe { for (int i = 0; i < array.Count; i++) { ((byte*)&ulongValue)[i] = array[i]; } } return ulongValue; } return new KalkNativeBuffer(array); } case byte vbyte: return BinaryFromBytes(1, vbyte, prefix, separator); case sbyte vsbyte: return BinaryFromBytes(1, vsbyte, prefix, separator); case short vshort: { int size = 2; return BinaryFromBytes(size, vshort, prefix, separator); } case ushort vushort: { int size = 2; return BinaryFromBytes(size, vushort, prefix, separator); } case int vint: { int size = 4; return BinaryFromBytes(size, vint, prefix, separator); } case uint vuint: { int size = 4; return BinaryFromBytes(size, vuint, prefix, separator); } case long vlong: { int size = 8; return BinaryFromBytes(size, vlong, prefix, separator); } case ulong vulong: { int size = 8; return BinaryFromBytes(size, vulong, prefix, separator); } case float vfloat: { var floatAsInt = BitConverter.SingleToInt32Bits(vfloat); return BinaryFromBytes(4, floatAsInt, prefix, separator); } case double vdouble: { var doubleAsLong = BitConverter.DoubleToInt64Bits(vdouble); return BinaryFromBytes(8, doubleAsLong, prefix, separator); } case BigInteger bigInt: { var array = bigInt.ToByteArray(); return BinaryFromBytes(array.Length, array[0], prefix, separator); } case KalkValue kalkValue: { var span = kalkValue.AsSpan(); return BinaryFromBytes(span.Length, span[0], prefix, separator); } case IEnumerable list: { var builder = new StringBuilder(); bool isFirst = true; foreach (var item in list) { if (!isFirst) { builder.Append(separator); } isFirst = false; byte byteItem = Engine.ToObject<byte>(0, item); if (prefix) builder.Append("0b"); AppendBinaryByte(builder, byteItem); } return builder.ToString(); } default: throw new ArgumentException($"The type {Engine.GetTypeName(value)} is not supported ", nameof(value)); } } private static void AppendBinaryByte(StringBuilder builder, byte byteItem) { for (int i = 0; i < 8; i++) { var b = (byteItem >> (7 - i)) & 1; builder.Append(b == 1 ? '1' : '0'); } } private static string BinaryFromBytes<T>(int byteCount, in T element, bool prefix, string separator) { var builder = new StringBuilder(byteCount * 8); for (int i = 0; i < byteCount; i++) { if (i > 0) builder.Append(separator); var b = Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref Unsafe.AsRef(element), new IntPtr(i))); if (prefix) builder.Append("0b"); AppendBinaryByte(builder, b); } return builder.ToString(); } private static object ConvertAscii(KalkEngine context, object argument) { if (argument is string text) { var bytes = EncodingExtendedAscii.GetBytes(text); if (bytes.Length == 1) { return bytes[0]; } return new KalkNativeBuffer(bytes); } else if (argument is KalkNativeBuffer buffer) { return EncodingExtendedAscii.GetString(buffer.AsSpan()); } else if (argument is IEnumerable it) { return new ScriptRange(ConvertAsciiIteration(context, it)); } else { return ConvertAscii(context.ToInt(context.CurrentSpan, argument)); } } private static IEnumerable ConvertAsciiIteration(KalkEngine context, IEnumerable it) { var iterator = it.GetEnumerator(); while (iterator.MoveNext()) { yield return ConvertAscii(context, iterator.Current); } } private static unsafe string ConvertAscii(int c) { var value = (byte)c; return EncodingExtendedAscii.GetString(&value, 1); } private static readonly string[] AsciiSpecialCodes = new string[32] { "NUL / Null", "SOH / Start of Heading", "STX / Start of Text", "ETX / End of Text", "EOT / End of Transmission", "ENQ / Enquiry", "ACK / Acknowledgment", "BEL / Bell", "BS / Backspace", "HT / Horizontal Tab", "LF / Line Feed", "VT / Vertical Tab", "FF / Form Feed", "CR / Carriage Return", "SO / Shift Out", "SI / Shift In", "DLE / Data Link Escape", "DC1 / Device Control 1", "DC2 / Device Control 2", "DC3 / Device Control 3", "DC4 / Device Control 4", "NAK / Negative Ack", "SYN / Synchronous Idle", "ETB / End of Trans Block", "CAN / Cancel", "EM / End of Medium", "SUB / Substitute", "ESC / Escape", "FS / File Separator", "GS / Group Separator", "RS / Record Separator", "US / Unit Separator", }; } }
41.424931
209
0.44965
[ "BSD-2-Clause" ]
thild/kalk
src/Kalk.Core/Modules/MiscModule.cs
60,151
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.NewRelic.Inputs { public sealed class OneDashboardPageGetArgs : Pulumi.ResourceArgs { /// <summary> /// Brief text describing the dashboard. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The unique entity identifier of the dashboard page in New Relic. /// </summary> [Input("guid")] public Input<string>? Guid { get; set; } /// <summary> /// The title of the dashboard. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; [Input("widgetAreas")] private InputList<Inputs.OneDashboardPageWidgetAreaGetArgs>? _widgetAreas; /// <summary> /// (Optional) A nested block that describes an Area widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetAreaGetArgs> WidgetAreas { get => _widgetAreas ?? (_widgetAreas = new InputList<Inputs.OneDashboardPageWidgetAreaGetArgs>()); set => _widgetAreas = value; } [Input("widgetBars")] private InputList<Inputs.OneDashboardPageWidgetBarGetArgs>? _widgetBars; /// <summary> /// (Optional) A nested block that describes a Bar widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetBarGetArgs> WidgetBars { get => _widgetBars ?? (_widgetBars = new InputList<Inputs.OneDashboardPageWidgetBarGetArgs>()); set => _widgetBars = value; } [Input("widgetBillboards")] private InputList<Inputs.OneDashboardPageWidgetBillboardGetArgs>? _widgetBillboards; /// <summary> /// (Optional) A nested block that describes a Billboard widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetBillboardGetArgs> WidgetBillboards { get => _widgetBillboards ?? (_widgetBillboards = new InputList<Inputs.OneDashboardPageWidgetBillboardGetArgs>()); set => _widgetBillboards = value; } [Input("widgetBullets")] private InputList<Inputs.OneDashboardPageWidgetBulletGetArgs>? _widgetBullets; /// <summary> /// (Optional) A nested block that describes a Bullet widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetBulletGetArgs> WidgetBullets { get => _widgetBullets ?? (_widgetBullets = new InputList<Inputs.OneDashboardPageWidgetBulletGetArgs>()); set => _widgetBullets = value; } [Input("widgetFunnels")] private InputList<Inputs.OneDashboardPageWidgetFunnelGetArgs>? _widgetFunnels; /// <summary> /// (Optional) A nested block that describes a Funnel widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetFunnelGetArgs> WidgetFunnels { get => _widgetFunnels ?? (_widgetFunnels = new InputList<Inputs.OneDashboardPageWidgetFunnelGetArgs>()); set => _widgetFunnels = value; } [Input("widgetHeatmaps")] private InputList<Inputs.OneDashboardPageWidgetHeatmapGetArgs>? _widgetHeatmaps; /// <summary> /// (Optional) A nested block that describes a Heatmap widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetHeatmapGetArgs> WidgetHeatmaps { get => _widgetHeatmaps ?? (_widgetHeatmaps = new InputList<Inputs.OneDashboardPageWidgetHeatmapGetArgs>()); set => _widgetHeatmaps = value; } [Input("widgetHistograms")] private InputList<Inputs.OneDashboardPageWidgetHistogramGetArgs>? _widgetHistograms; /// <summary> /// (Optional) A nested block that describes a Histogram widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetHistogramGetArgs> WidgetHistograms { get => _widgetHistograms ?? (_widgetHistograms = new InputList<Inputs.OneDashboardPageWidgetHistogramGetArgs>()); set => _widgetHistograms = value; } [Input("widgetJsons")] private InputList<Inputs.OneDashboardPageWidgetJsonGetArgs>? _widgetJsons; /// <summary> /// (Optional) A nested block that describes a JSON widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetJsonGetArgs> WidgetJsons { get => _widgetJsons ?? (_widgetJsons = new InputList<Inputs.OneDashboardPageWidgetJsonGetArgs>()); set => _widgetJsons = value; } [Input("widgetLines")] private InputList<Inputs.OneDashboardPageWidgetLineGetArgs>? _widgetLines; /// <summary> /// (Optional) A nested block that describes a Line widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetLineGetArgs> WidgetLines { get => _widgetLines ?? (_widgetLines = new InputList<Inputs.OneDashboardPageWidgetLineGetArgs>()); set => _widgetLines = value; } [Input("widgetMarkdowns")] private InputList<Inputs.OneDashboardPageWidgetMarkdownGetArgs>? _widgetMarkdowns; /// <summary> /// (Optional) A nested block that describes a Markdown widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetMarkdownGetArgs> WidgetMarkdowns { get => _widgetMarkdowns ?? (_widgetMarkdowns = new InputList<Inputs.OneDashboardPageWidgetMarkdownGetArgs>()); set => _widgetMarkdowns = value; } [Input("widgetPies")] private InputList<Inputs.OneDashboardPageWidgetPyGetArgs>? _widgetPies; /// <summary> /// (Optional) A nested block that describes a Pie widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetPyGetArgs> WidgetPies { get => _widgetPies ?? (_widgetPies = new InputList<Inputs.OneDashboardPageWidgetPyGetArgs>()); set => _widgetPies = value; } [Input("widgetTables")] private InputList<Inputs.OneDashboardPageWidgetTableGetArgs>? _widgetTables; /// <summary> /// (Optional) A nested block that describes a Table widget. See Nested widget blocks below for details. /// </summary> public InputList<Inputs.OneDashboardPageWidgetTableGetArgs> WidgetTables { get => _widgetTables ?? (_widgetTables = new InputList<Inputs.OneDashboardPageWidgetTableGetArgs>()); set => _widgetTables = value; } public OneDashboardPageGetArgs() { } } }
41.510989
125
0.650827
[ "ECL-2.0", "Apache-2.0" ]
bob-bins/pulumi-newrelic
sdk/dotnet/Inputs/OneDashboardPageGetArgs.cs
7,555
C#
using System.ComponentModel; using System.Runtime.CompilerServices; namespace PetitGeo30.Models { public abstract class BaseModel : INotifyPropertyChanged { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
27.388889
86
0.713996
[ "MIT" ]
RodgerLeblanc/PetitGeo30
PetitGeo30/PetitGeo30/Models/BaseModel.cs
495
C#
using System.Collections.Generic; namespace HaloOnline.Server.Model.TitleResource { //TODO: Remove TitleInstanceImpl once all TitleInstance subclasses are documented public class TitleInstanceImpl : TitleInstance { private readonly string _className; private readonly List<TitleProperty> _properties; public TitleInstanceImpl(string instanceName, string className) : base(instanceName) { _className = className; _properties = new List<TitleProperty>(); } public override string ClassName { get { return _className; } } public override List<TitleProperty> Properties { get { return _properties; } } } }
28.074074
92
0.643799
[ "MIT" ]
Atvaark/Emurado
HaloOnline.Server.Model/TitleResource/TitleInstanceImpl.cs
760
C#
/* ---------------------------------------------------------- 文件名称:UnicodeConverter.h 作者:秦建辉 MSN:splashcn@msn.com 当前版本:V1.0 历史版本: V1.0 2011年05月12日 完成正式版本。 功能描述: Unicode内码转换器。用于utf-8、utf-16(UCS2)、utf-32(UCS4)之间的编码转换 ------------------------------------------------------------ */ using System; using System.Text; namespace Warfare.Coding { /// <summary> /// UTF8、UTF16(UCS2)、UTF32(UCS4)编码转换器 /// </summary> public class UnicodeConverter { static string base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static int[] base64DecodeChars = new int[]{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1}; //base64解码 public static string base64decode(string str) { int c1, c2, c3, c4; int i, len;//out; string out2; len = str.Length; i = 0; out2 = ""; while (i < len) { /* c1 */ do { c1 = base64DecodeChars[str[i++] & 0xff]; } while (i < len && c1 == -1); if (c1 == -1) break; /* c2 */ do { c2 = base64DecodeChars[str[i++] & 0xff]; } while (i < len && c2 == -1); if (c2 == -1) break; out2 += Convert.ToChar((c1 << 2) | ((c2 & 0x30) >> 4)); /* c3 */ do { c3 = str[i++] & 0xff; if (c3 == 61) return out2; c3 = base64DecodeChars[c3]; } while (i < len && c3 == -1); if (c3 == -1) break; out2 += Convert.ToChar(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2)); /* c4 */ do { c4 = str[i++] & 0xff; if (c4 == 61) return out2; c4 = base64DecodeChars[c4]; } while (i < len && c4 == -1); if (c4 == -1) break; out2 += Convert.ToChar(((c3 & 0x03) << 6) | c4); } return out2; } public static string Base64Encode(string str) { //加密 string Out = ""; int i = 0, len = str.Length; char c1, c2, c3; while (i < len) { c1 = Convert.ToChar(str[i++] & 0xff); if (i == len) { Out += base64EncodeChars[c1 >> 2]; Out += base64EncodeChars[(c1 & 0x3) << 4]; Out += "=="; break; } c2 = str[i++]; if (i == len) { Out += base64EncodeChars[c1 >> 2]; Out += base64EncodeChars[((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)]; Out += base64EncodeChars[(c2 & 0xF) << 2]; Out += "="; break; } c3 = str[i++]; Out += base64EncodeChars[c1 >> 2]; Out += base64EncodeChars[((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)]; Out += base64EncodeChars[((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6)]; Out += base64EncodeChars[c3 & 0x3F]; } return Out; } //utf-16转utf-8 public static string utf8to16(string str) { string out2; char c; int i, len; char char2, char3; out2 = ""; len = str.Length; i = 0; while (i < len) { c = str[i++]; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out2 += str[i - 1]; break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = str[i++]; out2 += Convert.ToChar(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = str[i++]; char3 = str[i++]; out2 += Convert.ToChar(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out2; } public string utf16to8(string str) { string Out = ""; int i, len; char c;//char为16位Unicode字符,范围0~0xffff,感谢vczh提醒 len = str.Length; for (i = 0; i < len; i++) {//根据字符的不同范围分别转化 c = str[i]; if ((c >= 0x0001) && (c <= 0x007F)) { Out += str[i]; } else if (c > 0x07FF) { Out += (char)(0xE0 | ((c >> 12) & 0x0F)); Out += (char)(0x80 | ((c >> 6) & 0x3F)); Out += (char)(0x80 | ((c >> 0) & 0x3F)); } else { Out += (char)(0xC0 | ((c >> 6) & 0x1F)); Out += (char)(0x80 | ((c >> 0) & 0x3F)); } } return Out; } } }
30.909548
109
0.328239
[ "BSD-3-Clause" ]
qingfengzs/LollipopGo
LollipopGo/src/LollipopU3D/class5/Assets/UnicodeConverter.cs
6,347
C#
using AutoMapper; using FleetControl.Application.Interfaces.Mapping; using FleetControl.Core; using FleetControl.Domain; using System; namespace FleetControl.Application.Queries { public class CustomerDto : IHaveCustomMapping { public int BAID { get; set; } public string LiftingNumber { get; set; } public int? VoyagerAccountId { get; set; } //.. this is going to be the primary key within the Voyager application public string CustomerName { get; set; } public string EmbossedCustomerName { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string UsState { get; set; } public string ZipCode { get; set; } public string Telephone { get; set; } public string Contact { get; set; } public int? CreditLimit { get; set; } public string LockCode { get; set; } public DateTime? LockDate { get; set; } public string SalesPerson { get; set; } public string BillingCode { get; set; } public string WetHosing { get; set; } public string NYCAccount { get; set; } public DateTime? LastActivityDate { get; set; } public string SpecialCustomerCode { get; set; } public string FMRGroup { get; set; } public string InvoiceSeparation { get; set; } public string PinGeneration { get; set; } public ProductUse ProductUse { get; set; } public int? TransactionDollarLimit { get; set; } public HardSoftModes TransactionDollarLimitMode { get; set; } public int? DailyDollarLimit { get; set; } public HardSoftModes DailyDollarLimitMode { get; set; } public int? WeeklyDollarLimit { get; set; } public HardSoftModes WeeklyDollarLimitMode { get; set; } public int? MonthlyDollarLimit { get; set; } public HardSoftModes MonthlyDollarLimitMode { get; set; } public int? DailyTransactionLimit { get; set; } public HardSoftModes DailyTransactionLimitMode { get; set; } public int? WeeklyTransactionLimit { get; set; } public HardSoftModes WeeklyTransactionLimitMode { get; set; } public int? MonthlyTransactionLimit { get; set; } public HardSoftModes MonthlyTransactionLimitMode { get; set; } public PurchaseDayEnum PurchaseDay { get; set; } public HardSoftExceptionModes PurchaseDayMode { get; set; } public DateTime? PurchaseFromTimeBand1 { get; set; } public DateTime? PurchaseToTimeBand1 { get; set; } public HardSoftExceptionModes PurchaseDayBand1Mode { get; set; } public DateTime? PurchaseFromTimeBand2 { get; set; } public DateTime? PurchaseToTimeBand2 { get; set; } public HardSoftExceptionModes PurchaseDayBand2Mode { get; set; } public BooleanEnum OdometerValidation { get; set; } public OdometerType OdometerType { get; set; } public int OrgLevelsUsed { get; set; } public BooleanEnum DepartmentRequired { get; set; } public BooleanEnum CompanySelectsPin { get; set; } //.. Sprague establishes PIN ( 0 = No, 1 = Yes (default) ) public BooleanEnum CompanySelectsCardNumber { get; set; } public BooleanEnum CompanySelectsVehicleNumber { get; set; } //.. Sprague establishes VehicleId ( 0 = No, 1 = Yes (default) ) public BooleanEnum CompanySelectsDriverNumber { get; set; } //.. Sprague establishes DriverId ( 0 = No, 1 = Yes (default) ) public CardEntityType CardsTiedToEntity { get; set; } //.. Cards tied to vehicle or driver --- 0 = Vehicle (default), 1 = Driver, 3 = None public CardPromptPattern CardPromptPattern { get; set; } //.. Card Prompts for data at pump --- 0 = PIN # (default), 1 = Driver Id, 2 = Vehicle Id public EmbossingOnCard EmbossingOnCard { get; set; } //.. 5 = Vehicle License or Driver Name, 6 = Vehicle Description or Driver Name, 7 = VIN Number or Driver Name public EmbossingElement EmbossingElement1 { get; set; } public EmbossingElement EmbossingElement2 { get; set; } public EmbossingElement EmbossingElement3 { get; set; } public BooleanEnum InternalCustomer { get; set; } public StatusMode Status { get; set; } public BooleanEnum RetailCustomer { get; set; } public BooleanEnum PORequired { get; set; } public string BillingFrequency { get; set; } public CardRestrictionCode RestrictionCode { get; set; } public string CustNo { get; set; } public string ExternalDatabaseFilePath { get; set; } public bool IsConsignment { get; set; } public int MinDriverNumber { get; set; } public int MaxDriverNumber { get; set; } public string ExternalFMSNumber { get; set; } public bool IsFuelMaster { get; set; } public bool IsWinC6 { get; set; } public bool IsVoyager { get; set; } public BooleanEnum DepartmentRequiredForDriver { get; set; } public BooleanEnum DepartmentRequiredForCard { get; set; } public BooleanEnum DepartmentRequiredForVehicle { get; set; } public int? CardAddressId { get; set; } public void CreateMappings(Profile configuration) { configuration.CreateMap<Customer, CustomerDto>() //.ForMember(cDTO => cDTO.LastUpdated, opt => opt.Ignore()) //.ForMember(cDTO => cDTO.ProductId, opt => opt.MapFrom(c => c.ProductId)) //.ForMember(cDTO => cDTO.Name, opt => opt.MapFrom(c => c.CompanyName) ; } } }
55.509804
175
0.65136
[ "MIT" ]
sdemaine/FleetControl_CQRS
FleetControl.Application.Queries.Core/SharedDtos/CustomerDto.cs
5,664
C#
using Content.Shared.Eui; using Robust.Shared.Serialization; namespace Content.Shared.Administration { [Serializable, NetSerializable] public sealed class SetOutfitEuiState : EuiStateBase { public EntityUid TargetEntityId; } }
21
56
0.75
[ "MIT" ]
14th-Batallion-Marine-Corps/14-Marine-Corps
Content.Shared/Administration/SetOutfitEuiState.cs
252
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V231.Segment; using NHapi.Model.V231.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V231.Group { ///<summary> ///Represents the PPP_PCB_PATHWAY_ROLE Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: ROL (Role) </li> ///<li>1: VAR (Variance) optional repeating</li> ///</ol> ///</summary> [Serializable] public class PPP_PCB_PATHWAY_ROLE : AbstractGroup { ///<summary> /// Creates a new PPP_PCB_PATHWAY_ROLE Group. ///</summary> public PPP_PCB_PATHWAY_ROLE(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(ROL), true, false); this.add(typeof(VAR), false, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating PPP_PCB_PATHWAY_ROLE - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns ROL (Role) - creates it if necessary ///</summary> public ROL ROL { get{ ROL ret = null; try { ret = (ROL)this.GetStructure("ROL"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of VAR (Variance) - creates it if necessary ///</summary> public VAR GetVAR() { VAR ret = null; try { ret = (VAR)this.GetStructure("VAR"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of VAR /// * (Variance) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public VAR GetVAR(int rep) { return (VAR)this.GetStructure("VAR", rep); } /** * Returns the number of existing repetitions of VAR */ public int VARRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("VAR").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the VAR results */ public IEnumerable<VAR> VARs { get { for (int rep = 0; rep < VARRepetitionsUsed; rep++) { yield return (VAR)this.GetStructure("VAR", rep); } } } ///<summary> ///Adds a new VAR ///</summary> public VAR AddVAR() { return this.AddStructure("VAR") as VAR; } ///<summary> ///Removes the given VAR ///</summary> public void RemoveVAR(VAR toRemove) { this.RemoveStructure("VAR", toRemove); } ///<summary> ///Removes the VAR at the given index ///</summary> public void RemoveVARAt(int index) { this.RemoveRepetition("VAR", index); } } }
26.052632
158
0.660317
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V231/Group/PPP_PCB_PATHWAY_ROLE.cs
3,465
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Windows.Storage; using Windows.UI.Xaml.Controls; namespace HoloLensCommander { /// <summary> /// Delegate defining the method signature for handling the AppInstalled event. /// </summary> /// <param name="sender">The object sending the event.</param> public delegate void AppInstalledEventHandler(DeviceMonitorControl sender); /// <summary> /// Delegate defining the method signature for handling the AppUninstalled event. /// </summary> /// <param name="sender">The object sending the event.</param> public delegate void AppUninstalledEventHandler(DeviceMonitorControl sender); /// <summary> /// Delegate defining the method signature for handling the DeviceDisconnected event. /// </summary> /// <param name="sender">The object sending the event.</param> public delegate void DeviceDisconnectedEventHandler(DeviceMonitorControl sender); /// <summary> /// Delegate defining the method signature for handling the IsSelectedChanged event. /// </summary> /// <param name="sender">The object sending the event.</param> public delegate void IsSelectionChangedEventHander(DeviceMonitorControl sender); /// <summary> /// Delegate defining the method signature for handling the TagChanged event. /// </summary> /// <param name="sender">The object sending the event.</param> public delegate void TagChangedEventHandler(DeviceMonitorControl sender); /// <summary> /// The class that implements the custom xaml control used to monitor a connected device. /// </summary> public sealed partial class DeviceMonitorControl : Page, IDisposable { /// <summary> /// Event that is sent when an application install has completed. /// </summary> public event AppInstalledEventHandler AppInstalled; /// <summary> /// Event that is sent when an application uninstall has completed. /// </summary> public event AppUninstalledEventHandler AppUninstalled; /// <summary> /// Event that is sent when the device has been disconnected. /// </summary> public event DeviceDisconnectedEventHandler DeviceDisconnected; /// <summary> /// Event that is sent when the device's selection state has been changed. /// </summary> public event IsSelectionChangedEventHander SelectedChanged; /// <summary> /// Event that is sent when the data tagged to the device has been changed. /// </summary> public event TagChangedEventHandler TagChanged; /// <summary> /// Gets this page's DataContext as the underlying object's type. /// </summary> internal DeviceMonitorControlViewModel ViewModel { get { return this.DataContext as DeviceMonitorControlViewModel; } } /// <summary> /// Initializes a new instance of the <see cref="DeviceMonitorControl" /> class. /// </summary> /// <param name="monitor">The DeviceMonitor that is responsible for communication with the device.</param> public DeviceMonitorControl( DeviceMonitor monitor) { this.DataContext = new DeviceMonitorControlViewModel( this, monitor); this.InitializeComponent(); } /// <summary> /// Finalizer so that we are assured we clean up all encapsulated resources. /// </summary> /// <remarks>Call Dispose on this object to avoid running the finalizer.</remarks> ~DeviceMonitorControl() { this.Dispose(); } /// <summary> /// Cleans up objects managed by the DeviceMonitorControl. /// </summary> /// <remarks> /// Failure to call this method will result in the object not being collected until /// finalization occurs. /// </remarks> public void Dispose() { try { this.ViewModel.Dispose(); } catch { // TODO: Investigate what causes this.DataContext to throw. } GC.SuppressFinalize(this); } /// <summary> /// Clears the status message for this device. /// </summary> internal void ClearStatusMessage() { if (this.ViewModel.IsSelected) { this.ViewModel.ClearStatusMessage(); } } /// <summary> /// Closes all applications running on this device. /// </summary> /// <returns>Task object used for tracking method completion.</returns> internal async Task CloseAllAppsAsync() { await this.ViewModel.CloseAllAppsAsync(); } /// <summary> /// Disconnect from this device. /// </summary> internal void Disconnect() { this.ViewModel.Disconnect(); } /// <summary> /// Queries the device for the names of all installed applications. /// </summary> /// <returns>List of application names.</returns> internal async Task<List<string>> GetInstalledAppNamesAsync() { return await this.ViewModel.GetInstalledAppNamesAsync(); } /// <summary> /// Downloads the mixed reality capture files on the device. /// </summary> /// <param name="parentFolder">The name of the folder in which to download the files.</param> /// <param name="deleteAfterDownload">True to remove the downloaded files from the device.</param> /// <returns>Task object used for tracking method completion.</returns> internal async Task GetMixedRealityFilesAsync( StorageFolder parentFolder, bool deleteAfterDownload) { await this.ViewModel.GetMixedRealityFilesAsync( parentFolder, deleteAfterDownload); } /// <summary> /// Installs an application on this device. /// </summary> /// <param name="installFiles">Object describing the file(s) required to install an application.</param> /// <returns>Task object used for tracking method completion.</returns> internal async Task InstallAppAsync(AppInstallFiles installFiles) { await this.ViewModel.InstallAppAsync(installFiles); } /// <summary> /// Launches an application on this device. /// </summary> /// <param name="appName">The name of the application to launch.</param> /// <returns>The process identifier of the running application.</returns> internal async Task<int> LaunchAppAsync(string appName) { return await this.ViewModel.LaunchAppAsync(appName); } /// <summary> /// Sends the AppIninstalled event to registered handlers. /// </summary> internal void NotifyAppInstall() { this.AppInstalled?.Invoke(this); } /// <summary> /// Sends the AppUninstalled event to registered handlers. /// </summary> internal void NotifyAppUninstall() { this.AppUninstalled?.Invoke(this); } /// <summary> /// Sends the Disconnected event to registered handlers. /// </summary> internal void NotifyDisconnected() { this.DeviceDisconnected?.Invoke(this); } /// <summary> /// Sends the SelectedChanged event to registered handlers. /// </summary> internal void NotifySelectedChanged() { this.SelectedChanged?.Invoke(this); } /// <summary> /// Sends the TagChanged event to registered handlers. /// </summary> internal void NotifyTagChanged() { this.TagChanged?.Invoke(this); } /// <summary> /// Reboots this device. /// </summary> /// <returns>Task object used for tracking method completion.</returns> internal async Task RebootAsync() { await this.ViewModel.RebootAsync(); } /// <summary> /// Shuts down this device. /// </summary> /// <returns>Task object used for tracking method completion.</returns> internal async Task ShutdownAsync() { await this.ViewModel.ShutdownAsync(); } /// <summary> /// Starts recording a mixed reality video on this device. /// </summary> /// <returns>Task object used for tracking method completion.</returns> internal async Task StartMixedRealityRecordingAsync() { await this.ViewModel.StartMixedRealityRecordingAsync(); } /// <summary> /// Stops thea mixed reality recording on this device. /// </summary> /// <returns>Task object used for tracking method completion.</returns> internal async Task StopMixedRealityRecordingAsync() { await this.ViewModel.StopMixedRealityRecordingAsync(); } /// <summary> /// Uninstalls an application on this device. /// </summary> /// <param name="appName">The name of the application to uninstall.</param> /// <returns>Task object used for tracking method completion.</returns> internal async Task UninstallAppAsync(string appName) { await this.ViewModel.UninstallAppAsync(appName); } /// <summary> /// Wipes camera roll contents on this device. /// </summary> /// <returns></returns> internal async Task WipeCameraRollAsync() { await this.ViewModel.WipeCameraRollAsync(); } /// <summary> /// Uninstalls all side loaded applications of this device. /// </summary> /// <returns></returns> internal async Task UninstallAllAppsAsync() { await this.ViewModel.UninstallAllAppsAsync(); } } }
34.636964
114
0.597523
[ "MIT" ]
AMollis/MixedRealityCompanionKit
HoloLensCommander/HoloLensCommander/Controls/DeviceMonitorControl.xaml.cs
10,497
C#
using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace ImprintCMS.Models { [MetadataType(typeof(ConfigurationMetadata))] public partial class Configuration { } public class ConfigurationMetadata { [Required(ErrorMessage = "*")] [StringLength(50, ErrorMessageResourceName = "ValidationStringLength50", ErrorMessageResourceType = typeof(Phrases))] public string Name { get; set; } public bool IsActive { get; set; } [Required(ErrorMessage = "*")] [StringLength(50, ErrorMessageResourceName = "ValidationStringLength50", ErrorMessageResourceType = typeof(Phrases))] public string SiteName { get; set; } [Required(ErrorMessage = "*")] [AllowHtml] public string SiteFooter { get; set; } [StringLength(50, ErrorMessageResourceName = "ValidationStringLength50", ErrorMessageResourceType = typeof(Phrases))] public string GoogleAnalyticsTrackingCode { get; set; } public string PersonImageDownloadNotice { get; set; } public string CoverImageDownloadNotice { get; set; } [Required(ErrorMessage = "*")] [StringLength(50, ErrorMessageResourceName = "ValidationStringLength50", ErrorMessageResourceType = typeof(Phrases))] public string ShopEmailRecipient { get; set; } [AllowHtml] public string ShopDisclaimer { get; set; } [Required(ErrorMessage = "*")] [StringLength(50, ErrorMessageResourceName = "ValidationStringLength50", ErrorMessageResourceType = typeof(Phrases))] public string EmailSenderAddress { get; set; } [Required(ErrorMessage = "*")] [StringLength(50, ErrorMessageResourceName = "ValidationStringLength50", ErrorMessageResourceType = typeof(Phrases))] public string EmailSenderName { get; set; } [Required(ErrorMessage = "*")] public decimal DistributionCostAmount { get; set; } [Required(ErrorMessage = "*")] public decimal DistributionCostLimit { get; set; } public bool ShopIsVisible { get; set; } [Required(ErrorMessage = "*")] public int CachedCoverWidth { get; set; } [Required(ErrorMessage = "*")] public int CachedPortraitWidth { get; set; } } }
44.019231
125
0.671909
[ "Apache-2.0" ]
peders/Imprint-CMS
ImprintCMS/Models/Configuration.cs
2,291
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. #nullable enable using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [Shared] [ExportLspMethod(Methods.TextDocumentOnTypeFormattingName)] internal class FormatDocumentOnTypeHandler : IRequestHandler<DocumentOnTypeFormattingParams, TextEdit[]> { public async Task<TextEdit[]> HandleRequestAsync(Solution solution, DocumentOnTypeFormattingParams request, ClientCapabilities? clientCapabilities, CancellationToken cancellationToken) { var edits = new ArrayBuilder<TextEdit>(); var document = solution.GetDocumentFromURI(request.TextDocument.Uri); if (document != null) { var formattingService = document.Project.LanguageServices.GetRequiredService<IEditorFormattingService>(); var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(request.Character)) { return edits.ToArrayAndFree(); } IList<TextChange>? textChanges; if (SyntaxFacts.IsNewLine(request.Character[0])) { textChanges = await GetFormattingChangesOnReturnAsync(formattingService, document, position, cancellationToken).ConfigureAwait(false); } else { textChanges = await GetFormattingChangesAsync(formattingService, document, request.Character[0], position, cancellationToken).ConfigureAwait(false); } var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (textChanges != null) { edits.AddRange(textChanges.Select(change => ProtocolConversions.TextChangeToTextEdit(change, text))); } } return edits.ToArrayAndFree(); } protected virtual Task<IList<TextChange>?> GetFormattingChangesOnReturnAsync(IEditorFormattingService formattingService, Document document, int position, CancellationToken cancellationToken) => formattingService.GetFormattingChangesOnReturnAsync(document, position, cancellationToken); protected virtual Task<IList<TextChange>?> GetFormattingChangesAsync(IEditorFormattingService formattingService, Document document, char typedChar, int position, CancellationToken cancellationToken) => formattingService.GetFormattingChangesAsync(document, typedChar, position, cancellationToken); } }
48.424242
206
0.706508
[ "Apache-2.0" ]
Sliptory/roslyn
src/Features/LanguageServer/Protocol/Handler/Formatting/FormatDocumentOnTypeHandler.cs
3,198
C#
using UnityEngine; using UnityEngine.Events; /// <summary> /// Virtual Controller to handle the input from Unity. /// </summary> public class VirtualController : Common<VirtualController> { private readonly UnityEvent fireEvent = new UnityEvent(); /// <summary> /// Update is called once per frame. /// </summary> private void Update() { HandleFireEvent(); } /// <summary> /// Invokes the event. /// </summary> public void FireEvent() { fireEvent.Invoke(); } /// <summary> /// Informs the event to trigger the callback when event is invoked. /// </summary> /// <param name="callback"></param> public void FireEventSubscribe(UnityAction callback) { fireEvent.AddListener(callback); } /// <summary> /// Stops the event from triggering the callback. /// </summary> /// <param name="callback"></param> public void FireEventUnsubscribe(UnityAction callback) { fireEvent.RemoveListener(callback); } /// <summary> /// Logic for handling the Fire Event. /// </summary> private void HandleFireEvent() { var leftMouseButton = 0; if (Input.GetMouseButtonDown(leftMouseButton)) { FireEvent(); } } }
23.263158
76
0.588989
[ "MIT" ]
kevinkabatra/UnityTutorialBlockBreaker
Assets/UnityLayer/Player/VirtualController.cs
1,328
C#
namespace UIWidgets.Styles { using System; using UnityEngine; using UnityEngine.UI; /// <summary> /// Style for the Dropdown. /// </summary> [Serializable] public class StyleDropdown : IStyleDefaultValues { /// <summary> /// Style for the background. /// </summary> [SerializeField] public StyleImage Background; /// <summary> /// Style for the selected item text. /// </summary> [SerializeField] public StyleText Label; /// <summary> /// Style for the arrow. /// </summary> [SerializeField] public StyleImage Arrow; /// <summary> /// Style for the options background. /// </summary> [SerializeField] public StyleImage OptionsBackground; /// <summary> /// Style for the item background. /// </summary> [SerializeField] public StyleImage ItemBackground; /// <summary> /// Style for the checkmark. /// </summary> [SerializeField] public StyleImage ItemCheckmark; /// <summary> /// Style for the item text. /// </summary> [SerializeField] public StyleText ItemLabel; #if UNITY_5_2 || UNITY_5_3 || UNITY_5_3_OR_NEWER /// <summary> /// Apply style to the specified slider. /// </summary> /// <param name="component">Slider.</param> /// <param name="style">Style.</param> public virtual void ApplyTo(Dropdown component, Style style) { if (component == null) { return; } Background.ApplyTo(component.GetComponent<Image>()); Label.ApplyTo(component.captionText); Arrow.ApplyTo(component.transform.Find("Arrow")); OptionsBackground.ApplyTo(component.template); var scroll_rect = component.template.GetComponent<ScrollRect>(); OptionsBackground.ApplyTo(scroll_rect.viewport); if (scroll_rect.horizontalScrollbar != null) { style.ApplyTo(scroll_rect.horizontalScrollbar.gameObject); } if (scroll_rect.verticalScrollbar != null) { style.ApplyTo(scroll_rect.verticalScrollbar.gameObject); } var item = component.itemText.transform.parent; if (item != null) { ItemBackground.ApplyTo(item.Find("Item Background")); var toggle = item.GetComponent<Toggle>(); if (toggle != null) { ItemCheckmark.ApplyTo(toggle.graphic as Image); } } ItemLabel.ApplyTo(component.itemText); } #endif #if UNITY_EDITOR /// <summary> /// Sets the default values. /// </summary> public void SetDefaultValues() { Background.SetDefaultValues(); Label.SetDefaultValues(); Arrow.SetDefaultValues(); OptionsBackground.SetDefaultValues(); ItemBackground.SetDefaultValues(); ItemCheckmark.SetDefaultValues(); ItemLabel.SetDefaultValues(); } #endif } }
21.900826
67
0.678868
[ "MIT" ]
cschladetsch/CardChess
Assets/External/NewUIWidgets/Scripts/Style/Unity/StyleDropdown.cs
2,652
C#
using Newtonsoft.Json; namespace DGP.Genshin.DataModel.Character { public class CharStatValues { [JsonProperty("1")] public string? Level1 { get; set; } [JsonProperty("20")] public string? Level20 { get; set; } [JsonProperty("20+")] public string? Level20p { get; set; } [JsonProperty("40")] public string? Level40 { get; set; } [JsonProperty("40+")] public string? Level40p { get; set; } [JsonProperty("50")] public string? Level50 { get; set; } [JsonProperty("50+")] public string? Level50p { get; set; } [JsonProperty("60")] public string? Level60 { get; set; } [JsonProperty("60+")] public string? Level60p { get; set; } [JsonProperty("70")] public string? Level70 { get; set; } [JsonProperty("70+")] public string? Level70p { get; set; } [JsonProperty("80")] public string? Level80 { get; set; } [JsonProperty("80+")] public string? Level80p { get; set; } [JsonProperty("90")] public string? Level90 { get; set; } } }
45.608696
67
0.601525
[ "MIT" ]
CzHUV/Snap.Genshin
DGP.Genshin/DataModel/Character/CharStatValues.cs
1,051
C#
using System.ComponentModel.DataAnnotations; using TaskoMask.Application.Share.Resources; namespace TaskoMask.Application.Share.Dtos.Administration.Roles { public abstract class RoleBaseDto { public string Id { get; set; } [Display(Name = nameof(ApplicationMetadata.Name), ResourceType = typeof(ApplicationMetadata))] [StringLength(50, MinimumLength = 5, ErrorMessageResourceName = nameof(ApplicationMetadata.Length_Error), ErrorMessageResourceType = typeof(ApplicationMetadata))] [Required(ErrorMessageResourceName = nameof(ApplicationMetadata.Required), ErrorMessageResourceType = typeof(ApplicationMetadata))] public string Name { get; set; } [Display(Name = nameof(ApplicationMetadata.Description), ResourceType = typeof(ApplicationMetadata))] [StringLength(250, MinimumLength = 5, ErrorMessageResourceName = nameof(ApplicationMetadata.Length_Error), ErrorMessageResourceType = typeof(ApplicationMetadata))] [Required(ErrorMessageResourceName = nameof(ApplicationMetadata.Required), ErrorMessageResourceType = typeof(ApplicationMetadata))] public string Description { get; set; } [Display(Name = nameof(ApplicationMetadata.PermissionsId), ResourceType = typeof(ApplicationMetadata))] public string[] PermissionsId { get; set; } } }
46.482759
171
0.756677
[ "MIT" ]
hamed-shirbandi/TaskoMask
Src/Libraries/2-Application/Application.Core.Models/Dtos/Administration/Roles/RoleBaseDto.cs
1,350
C#
using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks; using FlubuCore.Tasks.Process; namespace FlubuCore.Azure.Tasks.Batch { public partial class AzureBatchApplicationPackageCreateTask : ExternalProcessTaskBase<AzureBatchApplicationPackageCreateTask> { /// <summary> /// Create a Batch application package record and activate it. /// </summary> public AzureBatchApplicationPackageCreateTask(string applicationId = null , string name = null , string packageFile = null , string resourceGroup = null , string version = null) { WithArguments("az batch application package create"); WithArguments("--application-id"); if (!string.IsNullOrEmpty(applicationId)) { WithArguments(applicationId); } WithArguments("--name"); if (!string.IsNullOrEmpty(name)) { WithArguments(name); } WithArguments("--package-file"); if (!string.IsNullOrEmpty(packageFile)) { WithArguments(packageFile); } WithArguments("--resource-group"); if (!string.IsNullOrEmpty(resourceGroup)) { WithArguments(resourceGroup); } WithArguments("--version"); if (!string.IsNullOrEmpty(version)) { WithArguments(version); } } protected override string Description { get; set; } } }
28.178571
189
0.595057
[ "MIT" ]
flubu-core/FlubuCore.Azure
FlubuCore.Azure/Tasks/Batch/AzureBatchApplicationPackageCreateTask.cs
1,578
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.Device.I2c; using System.Diagnostics; using System.Threading; using Iot.Device.Lm75; ////////////////////////////////////////////////////////////////////// // when connecting to an ESP32 device, need to configure the I2C GPIOs // used for the bus //Configuration.SetPinFunction(21, DeviceFunction.I2C1_DATA); //Configuration.SetPinFunction(22, DeviceFunction.I2C1_CLOCK); I2cConnectionSettings settings = new(1, Lm75.DefaultI2cAddress); using I2cDevice device = I2cDevice.Create(settings); using Lm75 sensor = new(device); while (true) { // read temperature Debug.WriteLine($"Temperature: {sensor.Temperature.DegreesCelsius} ℃"); Debug.WriteLine(""); Thread.Sleep(1000); }
30.642857
75
0.698135
[ "MIT" ]
KittyDotNet/nanoFramework.IoT.Device
devices/Lm75/samples/Program.cs
860
C#
namespace EraserBotFrontend { partial class TeamListView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
28.864865
108
0.536517
[ "MIT" ]
sethballantyne/eraser-bot-frontend
EraserBotFrontend/TeamListView.Designer.cs
1,070
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</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 Mim.V6301 { 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.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute(Namespace="urn:hl7-org:v3", IsNullable=false)] public enum x_ActClassDocumentEntryAct { /// <remarks/> ACT, /// <remarks/> ACCM, /// <remarks/> CONS, /// <remarks/> CTTEVENT, /// <remarks/> INC, /// <remarks/> INFRM, /// <remarks/> PCPR, /// <remarks/> REG, /// <remarks/> SPCTRT, } }
51.211538
1,358
0.681187
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/x_ActClassDocumentEntryAct.cs
2,663
C#
using System.Collections.Generic; using AoLibs.Dialogs.Core.Interfaces; namespace AoLibs.Dialogs.Core { /// <summary> /// Base implementation of <see cref="ICustomDialogsManager{TDialogIndex}"/> /// </summary> /// <typeparam name="TDialogIndex">Enum defining dialog pages.</typeparam> public abstract class CustomDialogsManagerBase<TDialogIndex> : ICustomDialogsManager<TDialogIndex> { private readonly Dictionary<TDialogIndex, ICustomDialogProvider> _dialogsDictionary; /// <summary> /// Initializes a new instance of the <see cref="CustomDialogsManagerBase{TDialogIndex}"/> class. /// </summary> /// <param name="dialogsDictionary">Dictionary defining all dialogs that will be used in the application.</param> protected CustomDialogsManagerBase(Dictionary<TDialogIndex, ICustomDialogProvider> dialogsDictionary) { _dialogsDictionary = dialogsDictionary; } /// <summary> /// Gets the dialog associated with given dialog. /// </summary> /// <param name="dialog">The dialog type to retrieve.</param> public ICustomDialog this[TDialogIndex dialog] => _dialogsDictionary[dialog].Dialog; /// <summary> /// Gets or sets currently displayed dialog. /// </summary> public ICustomDialog CurrentlyDisplayedDialog { get; set; } } }
40.085714
121
0.678546
[ "MIT" ]
mmaasstteerr/AoLibs
AoLibs.Dialogs.Core/Classes/CustomDialogsManagerBase.cs
1,405
C#
using Avalonia; using System; using System.Diagnostics; namespace AvaloniaDemo { internal class Program { private static void Main(string[] args) { try { BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } } public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() .UsePlatformDetect() .LogToTrace(); } }
23.214286
73
0.504615
[ "MIT" ]
wieslawsoltes/PanAndZoom
samples/AvaloniaDemo/Program.cs
652
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.Rdp; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpemt; using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpeudp; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace Microsoft.Protocols.TestSuites.Rdpeudp { public partial class RdpeudpTestSuite : RdpTestClassBase { #region BVT Test Cases [TestMethod] [Priority(0)] [TestCategory("BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEUDP")] [Description("Verify the RDP client will send an ACK to acknowledge the received package")] public void S2_DataTransfer_ClientReceiveData() { TransportMode[] transportModeArray = new TransportMode[] { TransportMode.Reliable, TransportMode.Lossy }; CheckPlatformCompatibility(ref transportModeArray); Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); foreach (TransportMode transportMode in transportModeArray) { this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} UDP connection.", transportMode); this.EstablishUDPConnection(transportMode, waitTime, true); this.TestSite.Log.Add(LogEntryKind.Comment, "Send the first RDPEUDP Source packet"); RdpeudpPacket packet = this.GetFirstValidUdpPacket(transportMode); this.SendPacket(transportMode, packet); #region Create Expect Ack Vectors List<AckVector> expectedAckVectors = new List<AckVector>(); AckVector ackVector = new AckVector(); ackVector.State = VECTOR_ELEMENT_STATE.DATAGRAM_RECEIVED; ackVector.Length = (byte)(packet.sourceHeader.Value.snSourceStart - getSnInitialSequenceNumber(transportMode) - 1); expectedAckVectors.Add(ackVector); #endregion Create Expect Ack Vectors this.TestSite.Log.Add(LogEntryKind.Comment, "Expect RDP client to send an ACK packet to acknowledge the receipt"); RdpeudpPacket ackpacket = WaitForACKPacket(transportMode, waitTime, expectedAckVectors.ToArray()); Site.Assert.IsNotNull(ackpacket, "Client should send an ACK to acknowledge the receipt of source packet. Transport mode is {0}", transportMode); } } [TestMethod] [Priority(0)] [TestCategory("BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEUDP")] [Description("Verify the RDP client will send an ACK to acknowledge the package loss when detect a package loss in a reliable connection.")] public void S2_DataTransfer_AcknowledgeTest_AcknowlegeLossyPackage() { TransportMode[] transportModeArray = new TransportMode[] { TransportMode.Reliable, TransportMode.Lossy }; CheckPlatformCompatibility(ref transportModeArray); CheckSecurityProtocolForMultitransport(); Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); foreach (TransportMode transportMode in transportModeArray) { DoUntilSucceed(() => { this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} UDP connection.", transportMode); this.EstablishUDPConnection(transportMode, waitTime, true); this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} RDPEMT connection.", transportMode); return this.EstablishRdpemtConnection(transportMode, waitTime); }, this.waitTime * 5, TimeSpan.FromSeconds(0.5), "RDPEMT tunnel creation failed"); this.TestSite.Log.Add(LogEntryKind.Comment, "Send one RDPUDP packet."); this.SendNextValidUdpPacket(transportMode); this.TestSite.Log.Add(LogEntryKind.Comment, "Send the second RDPUDP packet, don't really send it, it is as a lost packet"); RdpeudpPacket losspacket = this.GetNextValidUdpPacket(transportMode); this.TestSite.Log.Add(LogEntryKind.Comment, "Send the third and the forth RDPUDP packet."); this.SendNextValidUdpPacket(transportMode); this.SendNextValidUdpPacket(transportMode); #region Create Expect Ack Vectors List<AckVector> expectedAckVectors = new List<AckVector>(); // All packet before the lost one are received. AckVector ackVector = new AckVector(); ackVector.State = VECTOR_ELEMENT_STATE.DATAGRAM_RECEIVED; ackVector.Length = (byte)(losspacket.sourceHeader.Value.snSourceStart - getSnInitialSequenceNumber(transportMode) - 2); expectedAckVectors.Add(ackVector); // One packet lost. ackVector = new AckVector(); ackVector.State = VECTOR_ELEMENT_STATE.DATAGRAM_NOT_YET_RECEIVED; ackVector.Length = 0; expectedAckVectors.Add(ackVector); // Two packet received. ackVector = new AckVector(); ackVector.State = VECTOR_ELEMENT_STATE.DATAGRAM_RECEIVED; ackVector.Length = 1; expectedAckVectors.Add(ackVector); #endregion Create Expect Ack Vectors // Expect an ACK packet with expected acknowledge information. this.TestSite.Log.Add(LogEntryKind.Comment, "expect an ACK packet with expected acknowledge information."); RdpeudpPacket ackpacket = WaitForACKPacket(transportMode, waitTime, expectedAckVectors.ToArray()); Site.Assert.IsNotNull(ackpacket, "Client should send an ACK to acknowledge the receipt of source packets correctly, transport mode is {0}.", transportMode); this.TestSite.Log.Add(LogEntryKind.Comment, "Send the second RDPUDP packet, which is lost before"); this.SendPacket(transportMode, losspacket); #region Create Expect Ack Vectors expectedAckVectors.Clear(); // All packet before the lost one are received. ackVector = new AckVector(); ackVector.State = VECTOR_ELEMENT_STATE.DATAGRAM_RECEIVED; ackVector.Length = (byte)(losspacket.sourceHeader.Value.snSourceStart - getSnInitialSequenceNumber(transportMode) - 2); // The lost one and the next two packed are received too. ackVector.Length += 3; expectedAckVectors.Add(ackVector); #endregion // Expect an ACK packet with acknowledge all packets recieved. this.TestSite.Log.Add(LogEntryKind.Comment, "expect an ACK packet with acknowledge all packets received."); ackpacket = WaitForACKPacket(transportMode, waitTime, expectedAckVectors.ToArray()); Site.Assert.IsNotNull(ackpacket, "Client should send an ACK to acknowledge the receipt of source packets correctly, transport mode is {0}.", transportMode); } } [TestMethod] [Priority(0)] [TestCategory("BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEUDP")] [Description("Verify the RDP client support congestion control as a receiver.")] public void S2_DataTransfer_CongestionControlTest_ClientReceiveData() { TransportMode[] transportModeArray = new TransportMode[] { TransportMode.Reliable, TransportMode.Lossy }; CheckPlatformCompatibility(ref transportModeArray); CheckSecurityProtocolForMultitransport(); Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); foreach (TransportMode transportMode in transportModeArray) { DoUntilSucceed(() => { this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} UDP connection.", transportMode); this.EstablishUDPConnection(transportMode, waitTime, true); this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} RDPEMT connection.", transportMode); return this.EstablishRdpemtConnection(transportMode, waitTime); }, this.waitTime * 5, TimeSpan.FromSeconds(0.5), "RDPEMT tunnel creation failed"); this.TestSite.Log.Add(LogEntryKind.Comment, "Send one RDPUDP packet."); this.SendNextValidUdpPacket(transportMode); this.TestSite.Log.Add(LogEntryKind.Comment, "Send the second RDPUDP packet, don't really send it, it is as a lost packet"); RdpeudpPacket losspacket = this.GetNextValidUdpPacket(transportMode); this.TestSite.Log.Add(LogEntryKind.Comment, "Send another three RDPUDP packet."); this.SendNextValidUdpPacket(transportMode); this.SendNextValidUdpPacket(transportMode); this.SendNextValidUdpPacket(transportMode); // Expect an ACK packet with RDPUDP_FLAG_SYN flag. this.TestSite.Log.Add(LogEntryKind.Comment, "expect an ACK packet with RDPUDP_FLAG_SYN flag."); RdpeudpPacket ackpacket = WaitForACKPacket(transportMode, waitTime, null, RDPUDP_FLAG.RDPUDP_FLAG_CN, 0); Site.Assert.IsNotNull(ackpacket, "Client should send an ACK packet with RDPUDP_FLAG_SYN flag, transport mode is {0}", transportMode); RdpeudpPacket packet = this.GetNextValidUdpPacket(transportMode); packet.fecHeader.uFlags = packet.fecHeader.uFlags | RDPUDP_FLAG.RDPUDP_FLAG_CWR; this.SendPacket(transportMode, packet); // Expect an ACK packet without RDPUDP_FLAG_SYN flag. this.TestSite.Log.Add(LogEntryKind.Comment, "expect an ACK packet without RDPUDP_FLAG_SYN flag."); ackpacket = WaitForACKPacket(transportMode, waitTime, null, 0, RDPUDP_FLAG.RDPUDP_FLAG_CN); Site.Assert.IsNotNull(ackpacket, "Client should send an ACK packet without RDPUDP_FLAG_SYN flag, transport mode is {0}", transportMode); } } [TestMethod] [Priority(0)] [TestCategory("BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEUDP")] [Description("Verify the TLS handshake process on the reliable RDP-UDP connection.")] public void S2_DataTransfer_SecurityChannelCreation_ReliableConnection() { CheckSecurityProtocolForMultitransport(); Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); this.TestSite.Log.Add(LogEntryKind.Comment, "Create a reliable UDP connection."); this.EstablishUDPConnection(TransportMode.Reliable, waitTime, true, true); // Set the autoHandle to true, then can be used for create security channel. this.TestSite.Log.Add(LogEntryKind.Comment, "Start TLS handshake."); String certFile = this.Site.Properties["CertificatePath"]; String certPwd = this.Site.Properties["CertificatePassword"]; X509Certificate2 cert = new X509Certificate2(certFile, certPwd); rdpemtServerR = new RdpemtServer(rdpeudpSocketR, cert, false); this.TestSite.Log.Add(LogEntryKind.Comment, "Wait for a RDP_TUNNEL_CREATEREQUEST message from client after security channel creation"); RDP_TUNNEL_CREATEREQUEST createReq = rdpemtServerR.ExpectTunnelCreateRequest(waitTime); Site.Assert.IsNotNull(createReq, "Client should send a RDP_TUNNEL_CREATEREQUEST message after security channel creation."); } [TestMethod] [Priority(0)] [TestCategory("BVT")] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEUDP")] [Description("Verify the DTLS handshake process on the lossy RDP-UDP connection.")] public void S2_DataTransfer_SecurityChannelCreation_LossyConnection() { TransportMode[] transportModeArray = new TransportMode[] { TransportMode.Lossy }; CheckPlatformCompatibility(ref transportModeArray); CheckSecurityProtocolForMultitransport(); Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); this.TestSite.Log.Add(LogEntryKind.Comment, "Create a Lossy UDP connection."); this.EstablishUDPConnection(TransportMode.Lossy, waitTime, true); // Set the autoHandle to true, then can be used for create security channel. this.TestSite.Log.Add(LogEntryKind.Comment, "Start DTLS handshake."); this.rdpeudpSocketL.AutoHandle = true; String certFile = this.Site.Properties["CertificatePath"]; String certPwd = this.Site.Properties["CertificatePassword"]; X509Certificate2 cert = new X509Certificate2(certFile, certPwd); rdpemtServerL = new RdpemtServer(rdpeudpSocketL, cert, false); this.TestSite.Log.Add(LogEntryKind.Comment, "Wait for a RDP_TUNNEL_CREATEREQUEST message from client after security channel creation"); RDP_TUNNEL_CREATEREQUEST createReq = rdpemtServerL.ExpectTunnelCreateRequest(waitTime); Site.Assert.IsNotNull(createReq, "Client should send a RDP_TUNNEL_CREATEREQUEST message after security channel creation."); } #endregion BVT Test Cases #region Normal Test Cases [TestMethod] [Priority(1)] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEUDP")] [Description("Verify the RDP client can retransmit source package in the reliable RDP-UDP connection if not receiving ACK acknowledged for a specified time.")] public void S2_DataTransfer_RetransmitTest_ClientRetransmit() { // Record the sequenceNumber of the lost source packet. uint sequenceNumberForLossPacket = 0; ushort receiveWindowSize = 0; Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); this.TestSite.Log.Add(LogEntryKind.Comment, "Create a reliable UDP connection."); this.EstablishUDPConnection(TransportMode.Reliable, waitTime, true); this.TestSite.Log.Add(LogEntryKind.Comment, "Send the first RDPEUDP Source packet, but not acknowledge the receipt of the first source packet from client."); RdpeudpPacket packet = this.GetFirstValidUdpPacket(TransportMode.Reliable); #region Change packet.ackVectorHeader To Not Acknowledge The Receipt RDPUDP_ACK_VECTOR_HEADER ackVectorHeader = new RDPUDP_ACK_VECTOR_HEADER(); ackVectorHeader.AckVectorElement = null; ackVectorHeader.uAckVectorSize = 0; packet.ackVectorHeader = ackVectorHeader; sequenceNumberForLossPacket = packet.fecHeader.snSourceAck; receiveWindowSize = packet.fecHeader.uReceiveWindowSize; packet.fecHeader.snSourceAck--; #endregion Change packet.ackVectorHeader To Not Acknowledge The Receipt this.SendPacket(TransportMode.Reliable, packet); this.TestSite.Log.Add(LogEntryKind.Comment, "Wait for 200 ms so as to fire the retransmit timer."); Thread.Sleep(this.RetransmitTimer); this.TestSite.Log.Add(LogEntryKind.Comment, "Wait for the client to resend the lost packet."); RdpeudpPacket receivedPacket = this.WaitForSourcePacket(TransportMode.Reliable, waitTime, sequenceNumberForLossPacket); Site.Assert.IsNotNull(receivedPacket, "Client should resend the packet if not receiving an ACK for a specified time."); } [TestMethod] [Priority(1)] [TestCategory("Positive")] [TestCategory("RDP8.0")] [TestCategory("RDPEUDP")] [Description("Verify the RDP client will send ACK correctly when sequence number is wrapped around")] public void S2_DataTransfer_SequenceNumberWrapAround() { TransportMode[] transportModeArray = new TransportMode[] { TransportMode.Reliable, TransportMode.Lossy }; CheckPlatformCompatibility(ref transportModeArray); CheckSecurityProtocolForMultitransport(); Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); foreach (TransportMode transportMode in transportModeArray) { DoUntilSucceed(() => { this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} UDP connection.", transportMode); initSequenceNumber = uint.MaxValue - 3; this.EstablishUDPConnection(transportMode, waitTime, true); this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} RDPEMT connection.", transportMode); return this.EstablishRdpemtConnection(transportMode, waitTime); }, this.waitTime * 5, TimeSpan.FromSeconds(0.5), "RDPEMT tunnel creation failed"); if (getSourcePacketSequenceNumber(transportMode) > getSnInitialSequenceNumber(transportMode)) { this.TestSite.Log.Add(LogEntryKind.Comment, "Not wrap around yet, Send one RDPUDP packet."); this.SendNextValidUdpPacket(transportMode); } this.TestSite.Log.Add(LogEntryKind.Comment, "Already wrap around, Send three RDPUDP packet again."); this.SendNextValidUdpPacket(transportMode); this.SendNextValidUdpPacket(transportMode); this.SendNextValidUdpPacket(transportMode); #region Create Expect Ack Vectors List<AckVector> expectedAckVectors = new List<AckVector>(); AckVector ackVector = new AckVector(); ackVector.State = VECTOR_ELEMENT_STATE.DATAGRAM_RECEIVED; ackVector.Length = (byte)(getSourcePacketSequenceNumber(transportMode) + (uint.MaxValue - getSnInitialSequenceNumber(transportMode))); expectedAckVectors.Add(ackVector); #endregion Create Expect Ack Vectors this.TestSite.Log.Add(LogEntryKind.Comment, "Expect RDP client to send an ACK packet to acknowledge the receipt correctly"); RdpeudpPacket ackpacket = WaitForACKPacket(transportMode, waitTime, expectedAckVectors.ToArray()); Site.Assert.IsNotNull(ackpacket, "Client should send an ACK to correctly acknowledge the receipt of source packet. Transport mode is {0}", transportMode); } } [TestMethod] [Priority(1)] [TestCategory("Positive")] [TestCategory("RDP8.1")] [TestCategory("RDPEUDP")] [Description("Verify the RDP client will add RDPUDP_FLAG_ACKDELAYED flag in uFlags field of ACK packet if client delayed the ack")] public void S2_DataTransfer_ClientAckDelay() { TransportMode[] transportModeArray = new TransportMode[] { TransportMode.Reliable, TransportMode.Lossy }; CheckPlatformCompatibility(ref transportModeArray); CheckSecurityProtocolForMultitransport(); Site.Log.Add(LogEntryKind.Debug, "Establishing RDP connection ..."); StartRDPConnection(); foreach (TransportMode transportMode in transportModeArray) { DoUntilSucceed(() => { this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} UDP connection.", transportMode); initSequenceNumber = uint.MaxValue - 3; this.EstablishUDPConnection(transportMode, waitTime, true); this.TestSite.Log.Add(LogEntryKind.Comment, "Create a {0} RDPEMT connection.", transportMode); return this.EstablishRdpemtConnection(transportMode, waitTime); }, this.waitTime * 5, TimeSpan.FromSeconds(0.5), "RDPEMT tunnel creation failed"); this.TestSite.Log.Add(LogEntryKind.Comment, "Send three RDPUDP packets, wait {0} ms between each send"); Thread.Sleep(DelayedACKTimer); this.SendNextValidUdpPacket(transportMode); Thread.Sleep(DelayedACKTimer); this.SendNextValidUdpPacket(transportMode); Thread.Sleep(DelayedACKTimer); this.SendNextValidUdpPacket(transportMode); this.TestSite.Log.Add(LogEntryKind.Comment, "Expect RDP client to send an ACK packet with flag: RDPUDP_FLAG_ACKDELAYED"); RdpeudpPacket ackpacket = WaitForACKPacket(transportMode, waitTime, null, RDPUDP_FLAG.RDPUDP_FLAG_ACKDELAYED); Site.Assert.IsNotNull(ackpacket, "Client should send an ACK with RDPUDP_FLAG_ACKDELAYED flag. Transport mode is {0}", transportMode); } } #endregion Normal Test Cases } }
49.248322
172
0.649859
[ "MIT" ]
hshavit-infinidat/WindowsProtocolTestSuites
TestSuites/RDP/Client/src/TestSuite/RDPEUDP/S2_DataTransfer.cs
22,014
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using NUnit.Framework; using ServiceStack.Text.Tests.Support; namespace ServiceStack.Text.Tests.JsonTests { [TestFixture] public class LowercaseUnderscoreTests : TestBase { [SetUp] public void SetUp() { JsConfig.EmitLowercaseUnderscoreNames = true; } [TearDown] public void TearDown() { JsConfig.Reset(); } [Test] public void Does_serialize_To_lowercase_underscore() { var dto = new Movie { Id = 1, ImdbId = "tt0111161", Title = "The Shawshank Redemption", Rating = 9.2m, Director = "Frank Darabont", ReleaseDate = new DateTime(1995, 2, 17, 0, 0, 0, DateTimeKind.Utc), TagLine = "Fear can hold you prisoner. Hope can set you free.", Genres = new List<string> { "Crime", "Drama" }, }; var json = dto.ToJson(); Assert.That(json, Is.EqualTo( "{\"id\":1,\"imdb_id\":\"tt0111161\",\"title\":\"The Shawshank Redemption\",\"rating\":9.2,\"director\":\"Frank Darabont\",\"release_date\":\"\\/Date(792979200000)\\/\",\"tag_line\":\"Fear can hold you prisoner. Hope can set you free.\",\"genres\":[\"Crime\",\"Drama\"]}")); Serialize(dto); } [DataContract] class Person { [DataMember(Name = "MyID")] public int Id { get; set; } [DataMember] public string Name { get; set; } } [Test] public void Can_override_name() { var person = new Person { Id = 123, Name = "Abc" }; Assert.That(TypeSerializer.SerializeToString(person), Is.EqualTo("{MyID:123,name:Abc}")); Assert.That(JsonSerializer.SerializeToString(person), Is.EqualTo("{\"MyID\":123,\"name\":\"Abc\"}")); } } }
32.102941
291
0.497481
[ "BSD-3-Clause" ]
ChuckSavage/ServiceStack.Text
tests/ServiceStack.Text.Tests/JsonTests/LowercaseUnderscoreTests.cs
2,116
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using IdentityServer4.Models; using GrantTypes = IdentityServer4.Admin.Infrastructure.GrantTypes; namespace IdentityServer4.Admin.Controllers.API.Dtos { public class CreateClientDto { /// <summary> /// Unique ID of the client /// </summary> [Required] [StringLength(200)] public string ClientId { get; set; } /// <summary> /// Client display name (used for logging and consent screen) /// </summary> [Required] [StringLength(200)] public string ClientName { get; set; } /// <summary> /// Specifies the allowed grant types (legal combinations of AuthorizationCode, Implicit, Hybrid, ResourceOwner, ClientCredentials). /// </summary> [Required] public GrantTypes AllowedGrantTypes { get; set; } /// <summary> /// Controls whether access tokens are transmitted via the browser for this client (defaults to <c>false</c>). /// This can prevent accidental leakage of access tokens when multiple response types are allowed. /// </summary> /// <value> /// <c>true</c> if access tokens can be transmitted via the browser; otherwise, <c>false</c>. /// </value> public bool AllowAccessTokensViaBrowser { get; set; } = false; /// <summary> /// Gets or sets the allowed CORS origins for JavaScript clients. /// </summary> /// <value> /// The allowed CORS origins. /// </value> [Required] [StringLength(2000)] public string AllowedCorsOrigins { get; set; } /// <summary> /// Specifies allowed URIs to return tokens or authorization codes to /// </summary> [Required] [StringLength(2000)] public string RedirectUris { get; set; } /// <summary> /// Specifies allowed URIs to redirect to after logout /// </summary> [StringLength(2000)] public string PostLogoutRedirectUris { get; set; } public bool RequireConsent { get; set; } [Required] [StringLength(2000)] public string AllowedScopes { get; set; } /// <summary> /// Gets or sets the protocol type. /// </summary> /// <value> /// The protocol type. /// </value> [StringLength(200)] public string ProtocolType { get; set; } = IdentityServerConstants.ProtocolTypes.OpenIdConnect; /// <summary> /// If set to false, no client secret is needed to request tokens at the token endpoint (defaults to <c>true</c>) /// </summary> public bool RequireClientSecret { get; set; } = true; /// <summary> /// Description of the /// </summary> [StringLength(1000)] public string Description { get; set; } /// <summary> /// URI to further information about client (used on consent screen) /// </summary> [StringLength(2000)] public string ClientUri { get; set; } /// <summary> /// URI to client logo (used on consent screen) /// </summary> [StringLength(2000)] public string LogoUri { get; set; } /// <summary> /// Specifies whether user can choose to store consent decisions (defaults to <c>true</c>) /// </summary> public bool AllowRememberConsent { get; set; } = true; /// <summary> /// Specifies whether a proof key is required for authorization code based token requests (defaults to <c>false</c>). /// </summary> public bool RequirePkce { get; set; } = false; /// <summary> /// Specifies whether a proof key can be sent using plain method (not recommended and defaults to <c>false</c>.) /// </summary> public bool AllowPlainTextPkce { get; set; } = false; /// <summary> /// Specifies logout URI at client for HTTP front-channel based logout. /// </summary> [StringLength(2000)] public string FrontChannelLogoutUri { get; set; } /// <summary> /// Specifies is the user's session id should be sent to the FrontChannelLogoutUri. Defaults to <c>true</c>. /// </summary> public bool FrontChannelLogoutSessionRequired { get; set; } = true; /// <summary> /// Specifies logout URI at client for HTTP back-channel based logout. /// </summary> [StringLength(2000)] public string BackChannelLogoutUri { get; set; } /// <summary> /// Specifies is the user's session id should be sent to the BackChannelLogoutUri. Defaults to <c>true</c>. /// </summary> public bool BackChannelLogoutSessionRequired { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether [allow offline access]. Defaults to <c>false</c>. /// </summary> public bool AllowOfflineAccess { get; set; } = false; /// <summary> /// When requesting both an id token and access token, should the user claims always be added to the id token instead of requring the client to use the userinfo endpoint. /// Defaults to <c>false</c>. /// </summary> public bool AlwaysIncludeUserClaimsInIdToken { get; set; } = false; /// <summary> /// Lifetime of identity token in seconds (defaults to 300 seconds / 5 minutes) /// </summary> public int IdentityTokenLifetime { get; set; } = 300; /// <summary> /// Lifetime of access token in seconds (defaults to 3600 seconds / 1 hour) /// </summary> public int AccessTokenLifetime { get; set; } = 3600; /// <summary> /// Lifetime of authorization code in seconds (defaults to 300 seconds / 5 minutes) /// </summary> public int AuthorizationCodeLifetime { get; set; } = 300; /// <summary> /// Maximum lifetime of a refresh token in seconds. Defaults to 2592000 seconds / 30 days /// </summary> public int AbsoluteRefreshTokenLifetime { get; set; } = 2592000; /// <summary> /// Sliding lifetime of a refresh token in seconds. Defaults to 1296000 seconds / 15 days /// </summary> public int SlidingRefreshTokenLifetime { get; set; } = 1296000; /// <summary> /// Lifetime of a user consent in seconds. Defaults to null (no expiration) /// </summary> public int? ConsentLifetime { get; set; } = null; /// <summary> /// ReUse: the refresh token handle will stay the same when refreshing tokens /// OneTime: the refresh token handle will be updated when refreshing tokens /// </summary> public TokenUsage RefreshTokenUsage { get; set; } = TokenUsage.OneTimeOnly; /// <summary> /// Gets or sets a value indicating whether the access token (and its claims) should be updated on a refresh token request. /// Defaults to <c>false</c>. /// </summary> /// <value> /// <c>true</c> if the token should be updated; otherwise, <c>false</c>. /// </value> public bool UpdateAccessTokenClaimsOnRefresh { get; set; } = false; /// <summary> /// Absolute: the refresh token will expire on a fixed point in time (specified by the AbsoluteRefreshTokenLifetime) /// Sliding: when refreshing the token, the lifetime of the refresh token will be renewed (by the amount specified in SlidingRefreshTokenLifetime). The lifetime will not exceed AbsoluteRefreshTokenLifetime. /// </summary> public TokenExpiration RefreshTokenExpiration { get; set; } = TokenExpiration.Absolute; /// <summary> /// Specifies whether the access token is a reference token or a self contained JWT token (defaults to Jwt). /// </summary> public AccessTokenType AccessTokenType { get; set; } = AccessTokenType.Jwt; /// <summary> /// Gets or sets a value indicating whether the local login is allowed for this client. Defaults to <c>true</c>. /// </summary> /// <value> /// <c>true</c> if local logins are enabled; otherwise, <c>false</c>. /// </value> public bool EnableLocalLogin { get; set; } = true; /// <summary> /// Specifies which external IdPs can be used with this client (if list is empty all IdPs are allowed). Defaults to empty. /// </summary> public ICollection<string> IdentityProviderRestrictions { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets a value indicating whether JWT access tokens should include an identifier. Defaults to <c>false</c>. /// </summary> /// <value> /// <c>true</c> to add an id; otherwise, <c>false</c>. /// </value> public bool IncludeJwtId { get; set; } = false; /// <summary> /// Gets or sets a value indicating whether client claims should be always included in the access tokens - or only for client credentials flow. /// Defaults to <c>false</c> /// </summary> /// <value> /// <c>true</c> if claims should always be sent; otherwise, <c>false</c>. /// </value> public bool AlwaysSendClientClaims { get; set; } = false; /// <summary> /// Gets or sets a value to prefix it on client claim types. Defaults to <c>client_</c>. /// </summary> /// <value> /// Any non empty string if claims should be prefixed with the value; otherwise, <c>null</c>. /// </value> [StringLength(200)] public string ClientClaimsPrefix { get; set; } = "client_"; /// <summary> /// Gets or sets a salt value used in pair-wise subjectId generation for users of this client. /// </summary> [StringLength(200)] public string PairWiseSubjectSalt { get; set; } /// <summary> /// The maximum duration (in seconds) since the last time the user authenticated. /// </summary> public int? UserSsoLifetime { get; set; } /// <summary> /// Gets or sets the type of the device flow user code. /// </summary> /// <value> /// The type of the device flow user code. /// </value> [StringLength(100)] public string UserCodeType { get; set; } /// <summary> /// Gets or sets the device code lifetime. /// </summary> /// <value> /// The device code lifetime. /// </value> public int DeviceCodeLifetime { get; set; } = 300; /// <summary> /// Gets or sets the custom properties for the client. /// </summary> /// <value> /// The properties. /// </value> public IDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>(); public ICollection<string> GetAllowedGrantTypes() { switch (AllowedGrantTypes) { case GrantTypes.Code: { return Models.GrantTypes.Code; } case GrantTypes.Hybrid: { return Models.GrantTypes.Hybrid; } case GrantTypes.Implicit: { return Models.GrantTypes.Implicit; } case GrantTypes.ClientCredentials: { return Models.GrantTypes.ClientCredentials; } case GrantTypes.DeviceFlow: { return Models.GrantTypes.DeviceFlow; } case GrantTypes.ResourceOwnerPassword: { return Models.GrantTypes.ResourceOwnerPassword; } case GrantTypes.CodeAndClientCredentials: { return Models.GrantTypes.CodeAndClientCredentials; } case GrantTypes.HybridAndClientCredentials: { return Models.GrantTypes.HybridAndClientCredentials; } case GrantTypes.ImplicitAndClientCredentials: { return Models.GrantTypes.ImplicitAndClientCredentials; } case GrantTypes.ResourceOwnerPasswordAndClientCredentials: { return Models.GrantTypes.ResourceOwnerPasswordAndClientCredentials; } } throw new ArgumentException("不支持的授权类型"); } } }
39.355828
214
0.573889
[ "MIT" ]
blinds52/IdentityServer4.Admin
src/IdentityServer4.Admin/Controllers/API/Dtos/CreateClientDto.cs
12,846
C#
// Copyright (c) 2019 Alachisoft // // 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.Collections.Generic; using System.Linq; using System.Text; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.Enum; using Alachisoft.NCache.Runtime.Serialization; using Alachisoft.NCache.Runtime.Serialization.IO; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Runtime.Caching; namespace Alachisoft.NCache.Caching.Messaging { public class MultiCastMessage : Message , ICompactSerializable { private List<SubscriptionInfo> specificReciepients = new List<SubscriptionInfo>(); public MultiCastMessage(string messageId) : base(messageId) { } public List<SubscriptionInfo> SpecificReciepients { get { return specificReciepients; } set { specificReciepients = value; } } public void AddSpecificReciepients(List<string> clientIds) { foreach (string clientId in clientIds) { SubscriptionInfo receipient = new SubscriptionInfo(); receipient.ClientId = clientId; receipient.SubscriptionId = SubscriptionInfo.EventsSubscriptionName; receipient.Type = SubscriptionType.Subscriber; receipient.SubPolicyType = SubscriptionPolicyType.EventSubscription; specificReciepients.Add(receipient); } } #region ICompactSerializable Impl public override void Deserialize(CompactReader reader) { base.Deserialize(reader); SpecificReciepients = SerializationUtility.DeserializeList<SubscriptionInfo>(reader); } public override void Serialize(CompactWriter writer) { base.Serialize(writer); SerializationUtility.SerializeList(SpecificReciepients, writer); } #endregion } }
36.029412
134
0.689388
[ "Apache-2.0" ]
delsoft/NCache
Src/NCCache/Caching/Messaging/MultiCastMessage.cs
2,452
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using static ZNCHANY.Api.Entities.Enums.CommonEnum; namespace ZNCHANY.Api.Entities { [Serializable] public class Dncsrm_parameter { /// <summary> /// 编号 /// </summary> [Key,Required] public System.Int32 Id { get; set; } /// <summary> /// 再热蒸汽设计流量 /// </summary> public System.Double Zrqll_design { get; set; } /// <summary> /// 焓增计算公式参数1 /// </summary> public System.Double Hz_a1 { get; set; } /// <summary> /// 焓增计算公式参数2 /// </summary> public System.Double Hz_a2 { get; set; } /// <summary> /// 焓增计算公式参数3 /// </summary> public System.Double Hz_a3 { get; set; } /// <summary> /// 焓增计算公式参数4 /// </summary> public System.Double Hz_a4 { get; set; } /// <summary> /// 焓增计算公式参数5 /// </summary> public System.Double Hz_a5 { get; set; } /// <summary> /// 焓增计算公式参数6 /// </summary> public System.Double Hz_a6 { get; set; } /// <summary> /// 焓增计算公式参数7 /// </summary> public System.Double Hz_a7 { get; set; } /// <summary> /// 焓增计算公式参数8 /// </summary> public System.Double Hz_a8 { get; set; } /// <summary> /// 再热器减温水量对煤耗影响系数 /// </summary> public System.Double Zrq_jws_mh_xs { get; set; } /// <summary> /// 高温再热器出口温度额定值 /// </summary> public System.Double Gz_out_temp_ed { get; set; } /// <summary> /// 高温再热器出口温度上限值 /// </summary> public System.Double Gz_out_temp_high { get; set; } /// <summary> /// 高温再热器出口温度下限值 /// </summary> public System.Double Gz_out_temp_low { get; set; } /// <summary> /// 高温再热器出口温度对煤耗影响系数 /// </summary> public System.Double Gz_out_temp_mh_xs { get; set; } /// <summary> /// 末级过热器出口温度额定值 /// </summary> public System.Double Mg_out_temp_ed { get; set; } /// <summary> /// 末级过热器出口温度上限值 /// </summary> public System.Double Mg_out_temp_high { get; set; } /// <summary> /// 末级过热器出口温度下限值 /// </summary> public System.Double Mg_out_temp_low { get; set; } /// <summary> /// 末级过热器出口温度对煤耗影响系数 /// </summary> public System.Double Mg_out_temp_mh_xs { get; set; } /// <summary> /// 负荷区间 /// </summary> public System.String Fh_zone { get; set; } /// <summary> /// 氧量上限区间 /// </summary> public System.String O2_high_zone { get; set; } /// <summary> /// 氧量下限区间 /// </summary> public System.String O2_low_zone { get; set; } /// <summary> /// Nox上限区间 /// </summary> public System.String Nox_high_zone { get; set; } /// <summary> /// Nox下限区间 /// </summary> public System.String Nox_low_zone { get; set; } /// <summary> /// 沾污系数计算负荷区间 /// </summary> public System.String Zwxs_fh_zone { get; set; } /// <summary> /// 分隔屏设计焓增参考值区间 /// </summary> public System.String Fgp_design_hz_zone { get; set; } /// <summary> /// 分隔屏设计沾污系数 /// </summary> public System.Double Fgp_design_zwxs { get; set; } /// <summary> /// 分隔屏沾污系数上限 /// </summary> public System.Double Fgp_zwxs_high { get; set; } /// <summary> /// 分隔屏沾污系数下限 /// </summary> public System.Double Fgp_zwxs_low { get; set; } /// <summary> /// 后屏设计焓增参考值区间 /// </summary> public System.String Hp_design_hz_zone { get; set; } /// <summary> /// 后屏设计沾污系数 /// </summary> public System.Double Hp_design_zwxs { get; set; } /// <summary> /// 后屏沾污系数上限 /// </summary> public System.Double Hp_zwxs_high { get; set; } /// <summary> /// 后屏沾污系数下限 /// </summary> public System.Double Hp_zwxs_low { get; set; } /// <summary> /// 末级过热器设计焓增参考值区间 /// </summary> public System.String Mg_design_hz_zone { get; set; } /// <summary> /// 末级过热器设计沾污系数 /// </summary> public System.Double Mg_design_zwxs { get; set; } /// <summary> /// 末级过热器沾污系数上限 /// </summary> public System.Double Mg_zwxs_high { get; set; } /// <summary> /// 末级过热器沾污系数下限 /// </summary> public System.Double Mg_zwxs_low { get; set; } /// <summary> /// 低温再热器设计焓增参考值区间 /// </summary> public System.String Dz_design_hz_zone { get; set; } /// <summary> /// 低温再热器设计沾污系数 /// </summary> public System.Double Dz_design_zwxs { get; set; } /// <summary> /// 低温再热器沾污系数上限 /// </summary> public System.Double Dz_zwxs_high { get; set; } /// <summary> /// 低温再热器沾污系数下限 /// </summary> public System.Double Dz_zwxs_low { get; set; } /// <summary> /// 高温再热器设计焓增参考值区间 /// </summary> public System.String Gz_design_hz_zone { get; set; } /// <summary> /// 高温再热器设计沾污系数 /// </summary> public System.Double Gz_design_zwxs { get; set; } /// <summary> /// 高温再热器沾污系数上限 /// </summary> public System.Double Gz_zwxs_high { get; set; } /// <summary> /// 高温再热器沾污系数下限 /// </summary> public System.Double Gz_zwxs_low { get; set; } /// <summary> /// 低温过热器设计焓值参考值 /// </summary> public System.String Dg_design_hz_zone { get; set; } /// <summary> /// 低温过热器设计沾污系数 /// </summary> public System.Double Dg_design_zwxs { get; set; } /// <summary> /// 低温过热器沾污系数上限 /// </summary> public System.Double Dg_zwxs_high { get; set; } /// <summary> /// 低温过热器沾污系数下限 /// </summary> public System.Double Dg_zwxs_low { get; set; } /// <summary> /// AGP风量基础工况占比(%) /// </summary> public System.Double Agp_basic_percent { get; set; } /// <summary> /// 一级过热器减温水量设计值 /// </summary> public System.String Grq_jws_design_1 { get; set; } /// <summary> /// 二级过热器减温水量设计值 /// </summary> public System.String Grq_jws_design_2 { get; set; } /// <summary> /// 三级过热器减温水量设计值 /// </summary> public System.String Grq_jws_design_3 { get; set; } /// <summary> /// /// </summary> public Dncboiler DncBoiler { get; set; } public System.Int32 DncBoilerId { get; set; } /// <summary> /// /// </summary> public System.String DncBoiler_Name { get; set; } /// <summary> /// 是否可用(0:禁用,1:可用) /// </summary> public Status Status { get; set; } /// <summary> /// 是否已删 /// </summary> public IsDeleted IsDeleted { get; set; } } }
18.562232
62
0.428786
[ "Apache-2.0" ]
zazzlec/znchany
ZNCHANY.Api/Entities/SGModels/Dncsrm_parameter.cs
9,736
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; using System.Web.Http.Controllers; using System.Web.Http.Description; using System.Xml.XPath; using GUIOdyssey.Areas.HelpPage.ModelDescriptions; namespace GUIOdyssey.Areas.HelpPage { /// <summary> /// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file. /// </summary> public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider { private XPathNavigator _documentNavigator; private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; private const string ParameterExpression = "param[@name='{0}']"; /// <summary> /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class. /// </summary> /// <param name="documentPath">The physical path to XML document.</param> public XmlDocumentationProvider(string documentPath) { if (documentPath == null) { throw new ArgumentNullException("documentPath"); } XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); } public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); return GetTagValue(typeNode, "summary"); } public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "summary"); } public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) { ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; if (reflectedParameterDescriptor != null) { XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); if (methodNode != null) { string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); if (parameterNode != null) { return parameterNode.Value.Trim(); } } } return null; } public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "returns"); } public string GetDocumentation(MemberInfo member) { string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); return GetTagValue(propertyNode, "summary"); } public string GetDocumentation(Type type) { XPathNavigator typeNode = GetTypeNode(type); return GetTagValue(typeNode, "summary"); } private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) { ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; if (reflectedActionDescriptor != null) { string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); return _documentNavigator.SelectSingleNode(selectExpression); } return null; } private static string GetMemberName(MethodInfo method) { string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 0) { string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); } return name; } private static string GetTagValue(XPathNavigator parentNode, string tagName) { if (parentNode != null) { XPathNavigator node = parentNode.SelectSingleNode(tagName); if (node != null) { return node.Value.Trim(); } } return null; } private XPathNavigator GetTypeNode(Type type) { string controllerTypeName = GetTypeName(type); string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); return _documentNavigator.SelectSingleNode(selectExpression); } private static string GetTypeName(Type type) { string name = type.FullName; if (type.IsGenericType) { // Format the generic type name to something like: Generic{System.Int32,System.String} Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.FullName; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); } if (type.IsNested) { // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. name = name.Replace("+", "."); } return name; } } }
44.351852
161
0.618232
[ "MIT" ]
manu3193/Odyssey
OdysseyTheBegining/GUIOdyssey/GUIOdyssey/Areas/HelpPage/XmlDocumentationProvider.cs
7,185
C#
#region License /* Microsoft Public License (Ms-PL) MonoGame - Copyright © 2009 The MonoGame Team All rights reserved. This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. */ #endregion License #region Statement using System; #endregion Statement namespace Microsoft.Xna.Framework.GamerServices { public class SignedInGamer : Gamer { private AchievementCollection gamerAchievements; private FriendCollection friendCollection; delegate void AuthenticationDelegate(); public IAsyncResult BeginAuthentication(AsyncCallback callback, Object asyncState) { // Go off authenticate AuthenticationDelegate ad = DoAuthentication; return ad.BeginInvoke(callback, ad); } public void EndAuthentication( IAsyncResult result ) { AuthenticationDelegate ad = (AuthenticationDelegate)result.AsyncState; ad.EndInvoke(result); } private void DoAuthentication() { } public SignedInGamer() { var result = BeginAuthentication(null, null); EndAuthentication( result ); } private void AuthenticationCompletedCallback( IAsyncResult result ) { EndAuthentication(result); } #region Methods public FriendCollection GetFriends() { if(IsSignedInToLive) { if ( friendCollection == null ) { friendCollection = new FriendCollection(); } } return friendCollection; } public bool IsFriend (Gamer gamer) { if ( gamer == null ) throw new ArgumentNullException(); if ( gamer.IsDisposed ) throw new ObjectDisposedException(gamer.ToString()); bool found = false; foreach(FriendGamer f in friendCollection) { if ( f.Gamertag == gamer.Gamertag ) { found = true; } } return found; } delegate AchievementCollection GetAchievementsDelegate(); public IAsyncResult BeginGetAchievements( AsyncCallback callback, Object asyncState) { // Go off and grab achievements GetAchievementsDelegate gad = GetAchievements; return gad.BeginInvoke(callback, gad); } private void GetAchievementCompletedCallback( IAsyncResult result ) { // get the delegate that was used to call that method GetAchievementsDelegate gad = (GetAchievementsDelegate)result.AsyncState; // get the return value from that method call gamerAchievements = gad.EndInvoke(result); } public AchievementCollection EndGetAchievements( IAsyncResult result ) { GetAchievementsDelegate gad = (GetAchievementsDelegate)result.AsyncState; gamerAchievements = gad.EndInvoke(result); return gamerAchievements; } public AchievementCollection GetAchievements() { if ( IsSignedInToLive ) { if (gamerAchievements == null) { gamerAchievements = new AchievementCollection(); } } return gamerAchievements; } delegate void AwardAchievementDelegate(string achievementId, double percentageComplete); public IAsyncResult BeginAwardAchievement(string achievementId, AsyncCallback callback, Object state) { return BeginAwardAchievement(achievementId, 100.0, callback, state); } public IAsyncResult BeginAwardAchievement( string achievementId, double percentageComplete, AsyncCallback callback, Object state ) { // Go off and award the achievement AwardAchievementDelegate aad = DoAwardAchievement; return aad.BeginInvoke(achievementId, percentageComplete, callback, aad); } public void EndAwardAchievement(IAsyncResult result) { AwardAchievementDelegate aad = (AwardAchievementDelegate)result.AsyncState; aad.EndInvoke(result); } private void AwardAchievementCompletedCallback( IAsyncResult result ) { EndAwardAchievement(result); } public void AwardAchievement( string achievementId ) { AwardAchievement(achievementId, 100.0f); } public void DoAwardAchievement( string achievementId, double percentageComplete ) { } public void AwardAchievement( string achievementId, double percentageComplete ) { if (IsSignedInToLive) { BeginAwardAchievement( achievementId, percentageComplete, AwardAchievementCompletedCallback, null ); } } public void UpdateScore( string aCategory, long aScore ) { if (IsSignedInToLive) { } } public void ResetAchievements() { if (IsSignedInToLive) { } } #endregion #region Properties public GameDefaults GameDefaults { get { throw new NotSupportedException(); } } public bool IsGuest { get { throw new NotSupportedException(); } } public bool IsSignedInToLive { get { return false; } } public int PartySize { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public PlayerIndex PlayerIndex { get { return PlayerIndex.One; } } public GamerPresence Presence { get { throw new NotSupportedException(); } } GamerPrivileges _privileges = new GamerPrivileges(); public GamerPrivileges Privileges { get { return _privileges; } } #endregion protected virtual void OnSignedIn(SignedInEventArgs e) { EventHelpers.Raise(this, SignedIn, e); } protected virtual void OnSignedOut(SignedOutEventArgs e) { EventHelpers.Raise(this, SignedOut, e); } #region Events public static event EventHandler<SignedInEventArgs> SignedIn; public static event EventHandler<SignedOutEventArgs> SignedOut; #endregion } public class SignedInEventArgs : EventArgs { public SignedInEventArgs ( SignedInGamer gamer ) { } } public class SignedOutEventArgs : EventArgs { public SignedOutEventArgs (SignedInGamer gamer ) { } } }
26.152439
276
0.711355
[ "MIT" ]
Adrriii/MonoGame
MonoGame.Framework/DesktopGL/GamerServices/SignedInGamer.cs
8,583
C#
using System; using System.Collections.Generic; namespace LJD.App.Model.DbModels { public partial class SysFunction { public SysFunction() { R_RolePermission = new HashSet<R_RolePermission>(); R_UserPermissions = new HashSet<R_UserPermissions>(); } public string ObjectID { get; set; } public string FName { get; set; } public string FFunction { get; set; } public string FURL { get; set; } public string FIcon { get; set; } public string ParentID { get; set; } public string Remark { get; set; } public int? Status { get; set; } public string CreatedBy { get; set; } public DateTime? CreatedTime { get; set; } public string ModifiedBy { get; set; } public DateTime? ModifiedTime { get; set; } public int? Sort { get; set; } public virtual SysMenus Parent { get; set; } public virtual ICollection<R_RolePermission> R_RolePermission { get; set; } public virtual ICollection<R_UserPermissions> R_UserPermissions { get; set; } } }
33.939394
85
0.614286
[ "MIT" ]
188867052/LJDAPP
src/LJD.App.Model/DbModels/SysFunction.cs
1,122
C#
using Microsoft.Xna.Framework; using Pathoschild.Stardew.TractorMod.Framework.Config; using Pathoschild.Stardew.TractorMod.Framework.ModAttachments; using StardewModdingAPI; using StardewValley; using StardewValley.TerrainFeatures; using StardewValley.Tools; using SObject = StardewValley.Object; namespace Pathoschild.Stardew.TractorMod.Framework.Attachments { /// <summary>An attachment for the hoe.</summary> internal class HoeAttachment : BaseAttachment { /********* ** Fields *********/ /// <summary>The attachment settings.</summary> private readonly HoeConfig Config; /// <summary>The item ID for an artifact spot.</summary> private const int ArtifactSpotItemID = 590; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="config">The mod configuration.</param> /// <param name="reflection">Simplifies access to private code.</param> public HoeAttachment(HoeConfig config, IReflectionHelper reflection) : base(reflection) { this.Config = config; } /// <summary>Get whether the tool is currently enabled.</summary> /// <param name="player">The current player.</param> /// <param name="tool">The tool selected by the player (if any).</param> /// <param name="item">The item selected by the player (if any).</param> /// <param name="location">The current location.</param> public override bool IsEnabled(Farmer player, Tool tool, Item item, GameLocation location) { return (this.Config.TillDirt || this.Config.ClearWeeds) && tool is Hoe && tool.GetType().FullName != SeedBagAttachment.SeedBagTypeName; } /// <summary>Apply the tool to the given tile.</summary> /// <param name="tile">The tile to modify.</param> /// <param name="tileObj">The object on the tile.</param> /// <param name="tileFeature">The feature on the tile.</param> /// <param name="player">The current player.</param> /// <param name="tool">The tool selected by the player (if any).</param> /// <param name="item">The item selected by the player (if any).</param> /// <param name="location">The current location.</param> public override bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, Farmer player, Tool tool, Item item, GameLocation location) { // clear twigs & weeds if (this.Config.ClearWeeds && this.IsWeed(tileObj)) return this.UseToolOnTile(tool, tile); // till plain dirt if (this.Config.TillDirt && tileFeature == null && tileObj == null) return this.UseToolOnTile(tool, tile); // collect artifact spots if (this.Config.DigArtifactSpots && tileObj?.ParentSheetIndex == HoeAttachment.ArtifactSpotItemID) return this.UseToolOnTile(tool, tile); return false; } } }
42.287671
153
0.62747
[ "MIT" ]
S2SKY/StardewMods-1
TractorMod/Framework/Attachments/HoeAttachment.cs
3,087
C#
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using ServiceStack.Text; using SimpleCqrs.Eventing; namespace SimpleCqrs.EventStore.SqlServer { public class SqlServerEventStore : IEventStore { private readonly IDomainEventSerializer serializer; private readonly SqlServerConfiguration configuration; public SqlServerEventStore(SqlServerConfiguration configuration, IDomainEventSerializer serializer) { this.serializer = serializer; this.configuration = configuration; Init(); } public void Init() { using (var connection = new SqlConnection(configuration.ConnectionString)) { connection.Open(); var sql = string.Format(SqlStatements.CreateTheEventStoreTable, "EventStore"); using (var command = new SqlCommand(sql, connection)) command.ExecuteNonQuery(); connection.Close(); } } public IEnumerable<DomainEvent> GetEvents(Guid aggregateRootId, int startSequence) { var events = new List<DomainEvent>(); using (var connection = new SqlConnection(configuration.ConnectionString)) { connection.Open(); var sql = string.Format(SqlStatements.GetEventsByAggregateRootAndSequence, "", "EventStore", aggregateRootId, startSequence); using (var command = new SqlCommand(sql, connection)) using (var reader = command.ExecuteReader()) while (reader.Read()) { var type = reader["EventType"].ToString(); var data = reader["data"].ToString(); try { events.Add(serializer.Deserialize(Type.GetType(type), data)); } catch(ArgumentNullException ex) { throw new Exception(string.Format("Cannot find type '{0}', yet the type is in the event store. Are you sure you haven't changed a class name or something arising from mental dullness?", type.Split(',')[0]), ex.InnerException); } } connection.Close(); } return events; } public void Insert(IEnumerable<DomainEvent> domainEvents) { var sql = new StringBuilder(); foreach (var domainEvent in domainEvents) sql.AppendFormat(SqlStatements.InsertEvents, "EventStore", TypeToStringHelperMethods.GetString(domainEvent.GetType()), domainEvent.AggregateRootId, domainEvent.EventDate, domainEvent.Sequence, (serializer.Serialize(domainEvent) ?? string.Empty) .Replace("'", "''")); if (sql.Length <= 0) return; using (var connection = new SqlConnection(configuration.ConnectionString)) { connection.Open(); using (var command = new SqlCommand(sql.ToString(), connection)) command.ExecuteNonQuery(); connection.Close(); } } public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes) { var events = new List<DomainEvent>(); var eventParameters = domainEventTypes.Select(TypeToStringHelperMethods.GetString).Join("','"); using (var connection = new SqlConnection(configuration.ConnectionString)) { connection.Open(); var sql = string.Format(SqlStatements.GetEventsByType, "EventStore", eventParameters); using (var command = new SqlCommand(sql, connection)) using (var reader = command.ExecuteReader()) while (reader.Read()) { var type = reader["EventType"].ToString(); var data = reader["data"].ToString(); var domainEvent = serializer.Deserialize(Type.GetType(type), data); events.Add(domainEvent); } connection.Close(); } return events; } public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes, Guid aggregateRootId) { throw new NotImplementedException(); } public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes, DateTime startDate, DateTime endDate) { throw new NotImplementedException(); } } }
42.598291
255
0.552568
[ "Unlicense", "MIT" ]
AdnanAsotic/SimpleCQRS
src/EventStores/SimpleCqrs.EventStore.SqlServer/SqlServerEventStore.cs
4,986
C#
// ******************************************************************************* // <copyright file="EntityTypeMapperTests.cs" company="Intuit"> // Copyright (c) 2019 Intuit // // 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> // ******************************************************************************* namespace Intuit.TSheets.Tests.Unit.Client.Utilities { using Intuit.TSheets.Client.Utilities; using Intuit.TSheets.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; [TestClass] public class EntityTypeMapperTests { [TestMethod, TestCategory("Unit")] public void EntityTypeMapper_MapsEntityTypesAsExpected() { Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("calendars")(), typeof(ScheduleCalendar)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("customfields")(), typeof(CustomField)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("customfielditems")(), typeof(CustomFieldItem)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("files")(), typeof(File)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("geolocations")(), typeof(Geolocation)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("groups")(), typeof(Group)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("jobcodes")(), typeof(Jobcode)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("locations")(), typeof(Location)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("schedule_events")(), typeof(ScheduleEvent)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("timesheets")(), typeof(Timesheet)); Assert.IsInstanceOfType(EntityTypeMapper.GetTypeCreator("users")(), typeof(User)); } [TestMethod, TestCategory("Unit")] public void EntityTypeMapper_ReturnsNullWhenProvidedUnknownEntityName() { // Mapper must return null for unknown supplemental data sections, so as // not to break existing clients when new sections are added to the API. Func<IIdentifiable> createUnknown = EntityTypeMapper.GetTypeCreator("unknown"); Assert.IsNull(createUnknown); } } }
50.714286
116
0.675704
[ "Apache-2.0" ]
LaudateCorpus1/TSheets-V1-DotNET-SDK
Intuit.TSheets.Tests/Unit/Client/Utilities/EntityTypeMapperTests.cs
2,842
C#
 using System; namespace AntMe.Extension.Community { public sealed class Extension : IExtensionPack { public string Author { get { return "Tom Wendel @ AntMe! GmbH"; } } public string Description { get { return "Test Extension um zu sehen wie das so läuft"; } } public string Name { get { return "Community Extension"; } } public Version Version { get { return new Version(2, 0); } } public void Load(ITypeMapper typeMapper, KeyValueStore settings, KeyValueStore dictionary) { } } }
26.52381
99
0.642729
[ "MIT" ]
AntMeNet/AntMeCore
src/AntMe.Extension.Community/Extension.cs
560
C#
using System.Diagnostics.CodeAnalysis; namespace Rosd.Data.Conventions; /// <summary> /// LowerCaseConverter is used in database where table/columns use the "tablename" convention. /// </summary> public sealed class LowerCaseConverter : CaseConventionConverter { [return: NotNullIfNotNull("input")] protected override string? ConvertName(string? input) { if (string.IsNullOrEmpty(input)) { return input; } return input.ToLowerInvariant(); } }
24.142857
94
0.682446
[ "Apache-2.0" ]
diev/RepofDocs
Rosd.Data/Conventions/LowerCaseConverter.cs
509
C#
using System; using System.ComponentModel.DataAnnotations; using System.Globalization; namespace Tubumu.Modules.Framework.ModelValidation.Attributes { /// <summary> /// CompareAttribute /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)] public class CompareAttribute : ValidationAttribute { private const string DefaultErrorMessage = "对{0}和{1}属性或值进行{2}型的{3}比较失败"; /// <summary> /// OtherProperty /// </summary> public string OtherProperty { get; } /// <summary> /// ValueToCompare /// </summary> public object ValueToCompare { get; } /// <summary> /// Operator /// </summary> public ValidationCompareOperator Operator { get; } /// <summary> /// DataType /// </summary> public ValidationDataType DataType { get; } /// <summary> /// Constructor /// </summary> /// <param name="originalProperty"></param> /// <param name="compareOperator"></param> /// <param name="dataType"></param> public CompareAttribute(string originalProperty, ValidationCompareOperator compareOperator, ValidationDataType dataType) : this(originalProperty, null, compareOperator, dataType) { } /// <summary> /// Constructor /// </summary> /// <param name="originalProperty"></param> /// <param name="valueToCompare"></param> /// <param name="compareOperator"></param> /// <param name="dataType"></param> public CompareAttribute(string originalProperty, object valueToCompare, ValidationCompareOperator compareOperator, ValidationDataType dataType) : base(DefaultErrorMessage) { OtherProperty = originalProperty; ValueToCompare = valueToCompare; Operator = compareOperator; DataType = dataType; } /// <summary> /// FormatErrorMessage /// </summary> /// <param name="name"></param> /// <returns></returns> public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, OtherProperty, DataType.ToString(), Operator.ToString()); } /// <summary> /// IsValid /// </summary> /// <param name="value"></param> /// <param name="validationContext"></param> /// <returns></returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ValidationResult validationResult = null; if (!string.IsNullOrEmpty(OtherProperty)) { var originalProperty = validationContext.ObjectType.GetProperty(OtherProperty); if (originalProperty == null) { throw new NullReferenceException(nameof(OtherProperty)); } var otherValue = originalProperty.GetValue(validationContext.ObjectInstance, null); if (!Compare(Operator, DataType, value, otherValue)) validationResult = new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } if (validationResult == null && ValueToCompare != null && !Compare(Operator, DataType, value, ValueToCompare)) validationResult = new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); if (validationResult != null) return validationResult; return ValidationResult.Success; } private static bool Compare(ValidationCompareOperator compareOperator, ValidationDataType dataType, object value, object otherValue) { int num = 0; try { switch (dataType) { case ValidationDataType.String: num = string.Compare(value != null ? value.ToString() : String.Empty, otherValue != null ? otherValue.ToString() : String.Empty, false, CultureInfo.CurrentCulture); break; case ValidationDataType.Integer: num = ((int)value).CompareTo(otherValue); break; case ValidationDataType.Double: num = ((double)value).CompareTo(otherValue); break; case ValidationDataType.Date: num = ((DateTime)value).CompareTo(otherValue); break; case ValidationDataType.Currency: num = ((decimal)value).CompareTo(otherValue); break; } } catch { return false; } switch (compareOperator) { case ValidationCompareOperator.Equal: return (num == 0); case ValidationCompareOperator.NotEqual: return (num != 0); case ValidationCompareOperator.GreaterThan: return (num > 0); case ValidationCompareOperator.GreaterThanEqual: return (num >= 0); case ValidationCompareOperator.LessThan: return (num < 0); case ValidationCompareOperator.LessThanEqual: return (num <= 0); } return true; } } }
35.763975
188
0.554359
[ "MIT" ]
zhaoyanwenqi/Tubumu
src/Tubumu.Modules.Framework/ModelValidation/Attributes/CompareAttribute.cs
5,788
C#
using System; namespace PersonInfo { public class StartUp { static void Main(string[] args) { string name = Console.ReadLine(); int age = int.Parse(Console.ReadLine()); string id = Console.ReadLine(); string birthdate = Console.ReadLine(); IIdentifiable identifiable = new Citizen(name, age, id, birthdate); IBirthable birthable = new Citizen(name, age, id, birthdate); Console.WriteLine(identifiable.Id); Console.WriteLine(birthable.Birthdate); } } }
29.25
79
0.586325
[ "MIT" ]
danailstratiev/Csharp-SoftUni-Development
Csharp OOP/04. Interfaces and Abstraction/P02.MultipleImplementation/StartUp.cs
587
C#
using HierarchyGrid.Definitions; using ReactiveUI; using System.Collections.Generic; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using MoreLinq; using DynamicData; using System.Diagnostics.CodeAnalysis; using System.Windows.Forms; using System.Windows.Input; using Splat; using ReactiveMarbles.ObservableEvents; namespace VirtualHierarchyGrid { partial class HierarchyGrid { // Keep a cache of cells to be reused when redrawing -- it costs less to reuse than create private readonly List<HierarchyGridCell> _cells = new List<HierarchyGridCell>(); private readonly List<(Guid, Guid, HierarchyGridCell)> _drawnCells = new List<(Guid, Guid, HierarchyGridCell)>(); private readonly List<HierarchyGridHeader> _headers = new List<HierarchyGridHeader>(); private readonly List<GridSplitter> _splitters = new List<GridSplitter>(); private readonly HashSet<HierarchyDefinition> _columnsParents = new HashSet<HierarchyDefinition>(); private readonly HashSet<HierarchyDefinition> _rowsParents = new HashSet<HierarchyDefinition>(); private void DrawCells( PositionedCell[] pCells , bool invalidate ) { // Find cells that were previously drawn var commonCells = _drawnCells.Join( pCells , o => new { pId = o.Item1 , cId = o.Item2 } , p => new { pId = p.ProducerDefinition.Guid , cId = p.ConsumerDefinition.Guid } , ( o , p ) => (drawn: o, pos: p) ) .ToArray(); commonCells.ForEach( t => { var cell = t.drawn.Item3; cell.Width = t.pos.Width; cell.Height = t.pos.Height; Canvas.SetLeft( cell , t.pos.Left ); Canvas.SetTop( cell , t.pos.Top ); if ( invalidate ) { InvalidateCell( t.pos , cell ); } } ); _drawnCells.Where( x => !commonCells.Select( c => c.drawn.Item3 ).Contains( x.Item3 ) ) .ForEach( c => HierarchyGridCanvas.Children.Remove( c.Item3 ) ); var cells = pCells.Where( x => !commonCells.Select( t => t.pos ).Contains( x ) ) .Select( pCell => (pCell.ProducerDefinition.Guid, pCell.ConsumerDefinition.Guid, CreateCell( pCell )) ) .ToArray(); foreach ( var cell in cells ) HierarchyGridCanvas.Children.Add( cell.Item3 ); _drawnCells.Clear(); _drawnCells.AddRange( cells.Concat( commonCells.Select( t => t.drawn ) ) ); } private void DrawGrid( Size size ) { ViewModel.HoveredRow = -1; ViewModel.HoveredColumn = -1; if ( !ViewModel.IsValid ) { HierarchyGridCanvas.Children.Clear(); return; } var rowDefinitions = ViewModel.RowsDefinitions.Leaves().ToArray(); var colDefinitions = ViewModel.ColumnsDefinitions.Leaves().ToArray(); foreach ( var hdr in HierarchyGridCanvas.Children.OfType<HierarchyGridHeader>().ToArray() ) HierarchyGridCanvas.Children.Remove( hdr ); foreach ( var gs in HierarchyGridCanvas.Children.OfType<GridSplitter>().ToArray() ) HierarchyGridCanvas.Children.Remove( gs ); _columnsParents.Clear(); _rowsParents.Clear(); int headerCount = 0; int splitterCount = 0; DrawColumnsHeaders( colDefinitions , size.Width / ViewModel.Scale , ref headerCount , ref splitterCount ); DrawRowsHeaders( rowDefinitions , size.Height / ViewModel.Scale , ref headerCount , ref splitterCount ); // Draw global headers afterwards or last splitter will be drawn under column headers DrawGlobalHeaders( ref headerCount , ref splitterCount ); //DrawCells( size , rowDefinitions , colDefinitions ); RestoreHighlightedCell(); RestoreHoveredCell(); } private void RestoreHighlightedCell() { var rows = ViewModel.Highlights.Items.Where( o => o.isRow ).Select( o => o.pos ).ToArray(); var columns = ViewModel.Highlights.Items.Where( o => !o.isRow ).Select( o => o.pos ).ToArray(); _cells.Where( c => columns.Contains( c.ViewModel.ColumnIndex ) || rows.Contains( c.ViewModel.RowIndex ) ) .ForAll( c => c.ViewModel.IsHighlighted = true ); } private void RestoreHoveredCell() { var hoveredCell = ( Mouse.DirectlyOver as DependencyObject )?.GetVisualParent<HierarchyGridCell>(); if ( hoveredCell != null ) { this.Log().Debug( hoveredCell ); hoveredCell.ViewModel.IsHovered = true; if ( ViewModel.EnableCrosshair ) { ViewModel.HoveredColumn = hoveredCell.ViewModel.ColumnIndex; ViewModel.HoveredRow = hoveredCell.ViewModel.RowIndex; } else { ViewModel.ClearCrosshair(); } } } private void DrawGlobalHeaders( ref int headerCount , ref int splitterCount ) { var rowDepth = ViewModel.RowsDefinitions.TotalDepth(); var colDepth = ViewModel.ColumnsDefinitions.TotalDepth(); var splitters = new List<GridSplitter>(); Action<DragCompletedEventArgs> action = e => { (int position, IDisposable drag) tag = ((int, IDisposable)) ( (GridSplitter) e.Source ).Tag; var idx = tag.position; ViewModel.RowsHeadersWidth[idx] = (double) Math.Max( ViewModel.RowsHeadersWidth[idx] + e.HorizontalChange , 10d ); Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); }; double currentX = 0, currentY = 0; var columnsVerticalSpan = ViewModel.ColumnsHeadersHeight.Take( ViewModel.ColumnsHeadersHeight.Length - 1 ).Sum(); var rowsHorizontalSpan = ViewModel.RowsHeadersWidth.Take( ViewModel.RowsHeadersWidth.Length - 1 ).Sum(); var foldAllButton = BuildHeader( ref headerCount , null , rowsHorizontalSpan , columnsVerticalSpan ); foldAllButton.ViewModel.Content = TryFindResource( "CollapseAllIcon" ); foldAllButton.ToolTip = "Collapse all"; var evts = new Queue<IDisposable>(); evts.Enqueue( foldAllButton.Events().MouseLeftButtonDown .Do( _ => { ViewModel.SelectedPositions.Clear(); ViewModel.RowsDefinitions.FlatList( true ).ForEach( x => x.IsExpanded = false ); ViewModel.ColumnsDefinitions.FlatList( true ).ForEach( x => x.IsExpanded = false ); Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); } ) .Select( _ => Unit.Default ) .InvokeCommand( ViewModel , x => x.DrawGridCommand ) ); foldAllButton.Tag = evts; Canvas.SetLeft( foldAllButton , currentX ); Canvas.SetTop( foldAllButton , currentY ); HierarchyGridCanvas.Children.Add( foldAllButton ); // Draw row headers currentY = columnsVerticalSpan; for ( int i = 0 ; i < rowDepth - 1 ; i++ ) { var width = ViewModel.RowsHeadersWidth[i]; var height = ViewModel.ColumnsHeadersHeight.Last(); var tb = BuildHeader( ref headerCount , null , width , height ); var queue = new Queue<IDisposable>(); var idx = i; // Copy to local variable or else event will always use last value of i evts.Enqueue( tb.Events().MouseLeftButtonDown .Do( _ => { ViewModel.SelectedPositions.Clear(); var defs = ViewModel.RowsDefinitions.FlatList( true ) .Where( x => x.Level == idx ) .ToArray(); var desiredState = defs.AsParallel().Any( x => x.IsExpanded ); defs.ForEach( x => x.IsExpanded = !desiredState ); Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); } ) .Select( _ => Unit.Default ) .InvokeCommand( ViewModel , x => x.DrawGridCommand ) ); tb.ViewModel.Content = ViewModel.RowsDefinitions .FlatList( true ) .AsParallel() .Where( x => x.Level == idx ) .Any( x => x.IsExpanded ) ? TryFindResource( "CollapseIcon" ) : TryFindResource( "ExpandIcon" ); tb.Tag = evts; Canvas.SetLeft( tb , currentX ); Canvas.SetTop( tb , currentY ); HierarchyGridCanvas.Children.Add( tb ); currentX += width; var gSplitter = BuildSplitter( ref splitterCount , 2 , height , GridResizeDirection.Columns , i , action ); Canvas.SetLeft( gSplitter , currentX ); Canvas.SetTop( gSplitter , currentY ); splitters.Add( gSplitter ); } // Draw column headers currentY = 0; for ( int i = 0 ; i < colDepth - 1 ; i++ ) { var width = ViewModel.RowsHeadersWidth.Last(); var height = ViewModel.ColumnsHeadersHeight[i]; var tb = BuildHeader( ref headerCount , null , width , height ); var idx = i; // Copy to local variable or else event will always use last value of i evts.Enqueue( tb.Events().MouseLeftButtonDown .Do( _ => { ViewModel.SelectedPositions.Clear(); var defs = ViewModel.ColumnsDefinitions.FlatList( true ) .Where( x => x.Level == idx ) .ToArray(); var desiredState = defs.AsParallel().Any( x => x.IsExpanded ); defs.ForEach( x => x.IsExpanded = !desiredState ); Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); } ) .Select( _ => Unit.Default ) .InvokeCommand( ViewModel , x => x.DrawGridCommand ) ); tb.ViewModel.Content = ViewModel.ColumnsDefinitions .FlatList( true ) .AsParallel() .Where( x => x.Level == idx ) .Any( x => x.IsExpanded ) ? TryFindResource( "CollapseIcon" ) : TryFindResource( "ExpandIcon" ); tb.Tag = evts; Canvas.SetLeft( tb , currentX ); Canvas.SetTop( tb , currentY ); HierarchyGridCanvas.Children.Add( tb ); currentY += height; } var expandAllButton = BuildHeader( ref headerCount , null , ViewModel.RowsHeadersWidth.Last() , ViewModel.ColumnsHeadersHeight.Last() ); expandAllButton.ViewModel.Content = TryFindResource( "ExpandAllIcon" ); expandAllButton.ToolTip = "Expand all"; evts = new Queue<IDisposable>(); evts.Enqueue( expandAllButton.Events().MouseLeftButtonDown .Do( _ => { ViewModel.SelectedPositions.Clear(); ViewModel.RowsDefinitions.FlatList( true ).ForEach( x => x.IsExpanded = true ); ViewModel.ColumnsDefinitions.FlatList( true ).ForEach( x => x.IsExpanded = true ); Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); } ) .Select( _ => Unit.Default ) .InvokeCommand( ViewModel , x => x.DrawGridCommand ) ); expandAllButton.Tag = evts; Canvas.SetLeft( expandAllButton , currentX ); Canvas.SetTop( expandAllButton , currentY ); HierarchyGridCanvas.Children.Add( expandAllButton ); var splitter = BuildSplitter( ref splitterCount , 2 , ViewModel.ColumnsHeadersHeight.Last() , GridResizeDirection.Columns , ViewModel.RowsHeadersWidth.Length - 1 , action ); Canvas.SetLeft( splitter , ViewModel.RowsHeadersWidth.Sum() ); Canvas.SetTop( splitter , currentY ); splitters.Add( splitter ); foreach ( var gridSplitter in splitters ) HierarchyGridCanvas.Children.Add( gridSplitter ); } private void InvalidateCell( PositionedCell pCell , HierarchyGridCell cell ) { cell.ViewModel.ResultSet = pCell.ResultSet; } private HierarchyGridCell CreateCell( PositionedCell pCell ) { var vm = new HierarchyGridCellViewModel( ViewModel ); var cell = new HierarchyGridCell { ViewModel = vm }; vm.ResultSet = ResultSet.Default; cell.ViewModel.IsSelected = ViewModel.SelectedPositions.Lookup( (pCell.VerticalPosition, pCell.HorizontalPosition) ).HasValue; cell.ViewModel.ColumnIndex = pCell.HorizontalPosition; cell.ViewModel.RowIndex = pCell.VerticalPosition; cell.Width = pCell.Width; cell.Height = pCell.Height; cell.ViewModel.ResultSet = HierarchyDefinition.Resolve( pCell.ProducerDefinition , pCell.ConsumerDefinition ); Canvas.SetLeft( cell , pCell.Left ); Canvas.SetTop( cell , pCell.Top ); return cell; } private void DrawColumnsHeaders( HierarchyDefinition[] hdefs , double availableWidth , ref int headerCount , ref int splitterCount ) { double currentPosition = ViewModel.RowsHeadersWidth.Sum(); int column = ViewModel.HorizontalOffset; var frozen = hdefs.Where( x => x.Frozen ).ToArray(); ViewModel.MaxHorizontalOffset = hdefs.Length - ( 1 + frozen.Length ); var splitters = new List<GridSplitter>(); foreach ( var hdef in frozen ) { var width = ViewModel.ColumnsWidths[hdefs.IndexOf( hdef )]; DrawColumnHeader( ref headerCount , ref splitterCount , ref currentPosition , column , splitters , hdef , width ); column++; } while ( column < hdefs.Length && currentPosition < availableWidth ) { var hdef = hdefs[column]; var width = ViewModel.ColumnsWidths[column]; DrawColumnHeader( ref headerCount , ref splitterCount , ref currentPosition , column , splitters , hdef , width ); column++; } foreach ( var gridSplitter in splitters ) HierarchyGridCanvas.Children.Add( gridSplitter ); } private void DrawColumnHeader( ref int headerCount , ref int splitterCount , ref double currentPosition , int column , List<GridSplitter> splitters , HierarchyDefinition hdef , double width ) { var height = hdef.IsExpanded && hdef.HasChild ? ViewModel.ColumnsHeadersHeight[hdef.Level] : Enumerable.Range( hdef.Level , ViewModel.ColumnsHeadersHeight.Length - hdef.Level ) .Select( x => ViewModel.ColumnsHeadersHeight[x] ).Sum(); var tb = BuildHeader( ref headerCount , hdef , width , height ); tb.ViewModel.ColumnIndex = column; var top = Enumerable.Range( 0 , hdef.Level ).Select( x => ViewModel.ColumnsHeadersHeight[x] ).Sum(); Canvas.SetLeft( tb , currentPosition ); Canvas.SetTop( tb , top ); HierarchyGridCanvas.Children.Add( tb ); Action<DragCompletedEventArgs> action = e => { (int position, IDisposable drag) tag = ((int, IDisposable)) ( (GridSplitter) e.Source ).Tag; var currentColumn = tag.position; ViewModel.ColumnsWidths[currentColumn] = (double) Math.Max( ViewModel.ColumnsWidths[currentColumn] + e.HorizontalChange , 10d ); Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); }; var gridSplitter = BuildSplitter( ref splitterCount , 2 , height , GridResizeDirection.Columns , column , action ); Canvas.SetLeft( gridSplitter , currentPosition + width - 1 ); Canvas.SetTop( gridSplitter , top ); splitters.Add( gridSplitter ); DrawParentColumnHeader( hdef , hdef , column , currentPosition , ref headerCount ); currentPosition += width; } private void DrawParentColumnHeader( HierarchyDefinition src , HierarchyDefinition origin , int column , double currentPosition , ref int headerCount ) { if ( src.Parent == null ) return; var hdef = src.Parent; if ( _columnsParents.Contains( hdef ) ) return; var width = Enumerable.Range( column , hdef.Count() - origin.RelativePositionFrom( hdef ) ) .Select( x => ViewModel.ColumnsWidths.TryGetValue( x , out var size ) ? size : 0 ).Sum(); var height = ViewModel.ColumnsHeadersHeight[hdef.Level]; var tb = BuildHeader( ref headerCount , hdef , width , height ); tb.ViewModel.CanToggle = true; var top = Enumerable.Range( 0 , hdef.Level ).Select( x => ViewModel.ColumnsHeadersHeight[x] ).Sum(); Canvas.SetLeft( tb , currentPosition ); Canvas.SetTop( tb , top ); HierarchyGridCanvas.Children.Add( tb ); _columnsParents.Add( hdef ); DrawParentColumnHeader( hdef , origin , column , currentPosition , ref headerCount ); } private void DrawRowsHeaders( HierarchyDefinition[] hdefs , double availableHeight , ref int headerCount , ref int splitterCount ) { double currentPosition = ViewModel.ColumnsHeadersHeight.Sum(); int row = ViewModel.VerticalOffset; var frozen = hdefs.Where( x => x.Frozen ).ToArray(); ViewModel.MaxVerticalOffset = hdefs.Length - ( 1 + frozen.Length ); var splitters = new List<GridSplitter>(); foreach ( var hdef in frozen ) { var height = ViewModel.RowsHeights[hdefs.IndexOf( hdef )]; DrawRowHeader( ref headerCount , ref splitterCount , ref currentPosition , row , splitters , hdef , height ); row++; } while ( row < hdefs.Length && currentPosition < availableHeight ) { var hdef = hdefs[row]; var height = ViewModel.RowsHeights[row]; DrawRowHeader( ref headerCount , ref splitterCount , ref currentPosition , row , splitters , hdef , height ); row++; } foreach ( var gridSplitter in splitters ) HierarchyGridCanvas.Children.Add( gridSplitter ); } private void DrawRowHeader( ref int headerCount , ref int splitterCount , ref double currentPosition , int row , List<GridSplitter> splitters , HierarchyDefinition hdef , double height ) { var width = hdef.IsExpanded && hdef.HasChild ? ViewModel.RowsHeadersWidth[hdef.Level] : Enumerable.Range( hdef.Level , ViewModel.RowsHeadersWidth.Length - hdef.Level ) .Where( x => x < ViewModel.RowsHeadersWidth.Length ) .Select( x => ViewModel.RowsHeadersWidth[x] ).Sum(); var tb = BuildHeader( ref headerCount , hdef , width , height ); tb.ViewModel.RowIndex = row; var left = Enumerable.Range( 0 , hdef.Level ).Where( x => x < ViewModel.RowsHeadersWidth.Length ).Select( x => ViewModel.RowsHeadersWidth[x] ).Sum(); Canvas.SetLeft( tb , left ); Canvas.SetTop( tb , currentPosition ); HierarchyGridCanvas.Children.Add( tb ); Action<DragCompletedEventArgs> action = e => { (int position, IDisposable drag) tag = ((int, IDisposable)) ( (GridSplitter) e.Source ).Tag; var currentRow = tag.position; ViewModel.RowsHeights[currentRow] = (double) Math.Max( ViewModel.RowsHeights[currentRow] + e.VerticalChange , 10d ); Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); }; var gridSplitter = BuildSplitter( ref splitterCount , width , 2 , GridResizeDirection.Rows , row , action ); Canvas.SetLeft( gridSplitter , left ); Canvas.SetTop( gridSplitter , currentPosition + height - 1 ); splitters.Add( gridSplitter ); DrawParentRowHeader( hdef , hdef , row , currentPosition , ref headerCount ); currentPosition += height; } private void DrawParentRowHeader( HierarchyDefinition src , HierarchyDefinition origin , int row , double currentPosition , ref int headerCount ) { if ( src.Parent == null ) return; var hdef = src.Parent; if ( _rowsParents.Contains( hdef ) ) return; var height = Enumerable.Range( row , hdef.Count() - origin.RelativePositionFrom( hdef ) ) .Select( x => ViewModel.RowsHeights.TryGetValue( x , out var size ) ? size : 0 ).Sum(); var width = ViewModel.RowsHeadersWidth[hdef.Level]; var tb = BuildHeader( ref headerCount , hdef , width , height ); tb.ViewModel.CanToggle = true; var left = Enumerable.Range( 0 , hdef.Level ).Where( x => x < ViewModel.RowsHeadersWidth.Length ).Select( x => ViewModel.RowsHeadersWidth[x] ).Sum(); Canvas.SetLeft( tb , left ); Canvas.SetTop( tb , currentPosition ); HierarchyGridCanvas.Children.Add( tb ); _rowsParents.Add( hdef ); DrawParentRowHeader( hdef , origin , row , currentPosition , ref headerCount ); } private HierarchyGridHeader BuildHeader( ref int headerCount , [AllowNull] HierarchyDefinition hdef , double width , double height ) { HierarchyGridHeader tb = null; if ( headerCount < _headers.Count ) { tb = _headers[headerCount]; if ( tb.Tag is Queue<IDisposable> previousEvents ) previousEvents.ForEach( e => e.Dispose() ); tb.Tag = null; tb.ViewModel.RowIndex = null; tb.ViewModel.ColumnIndex = null; tb.ViewModel.CanToggle = false; } else { tb = new HierarchyGridHeader { ViewModel = new HierarchyGridHeaderViewModel( ViewModel ) }; _headers.Add( tb ); } tb.ViewModel.Content = hdef?.Content ?? string.Empty; tb.Height = height; tb.Width = width; tb.ViewModel.IsChecked = hdef?.HasChild == true && hdef?.IsExpanded == true; tb.ViewModel.IsHighlighted = hdef?.IsHighlighted ?? false; var evts = new Queue<IDisposable>(); if ( hdef?.HasChild == true ) { tb.ViewModel.CanToggle = true; evts.Enqueue( tb.Events().MouseLeftButtonDown .Do( _ => { ViewModel.SelectedPositions.Clear(); hdef.IsExpanded = !hdef.IsExpanded; Observable.Return( (ViewModel.HorizontalOffset, ViewModel.VerticalOffset, ViewModel.Width, ViewModel.Height, ViewModel.Scale, false) ) .InvokeCommand( ViewModel , x => x.FindCellsToDrawCommand ); } ) .Select( _ => Unit.Default ) .InvokeCommand( ViewModel , x => x.DrawGridCommand ) ); } else if ( hdef != null ) // Clicking on header should add/remove from highlights evts.Enqueue( tb.Events().MouseLeftButtonDown .Throttle( TimeSpan.FromMilliseconds( 200 ) ) .ObserveOn( RxApp.MainThreadScheduler ) .Select( _ => { hdef.IsHighlighted = !hdef.IsHighlighted; tb.ViewModel.IsHighlighted = hdef.IsHighlighted; return tb.ViewModel; } ) .InvokeCommand( ViewModel , x => x.UpdateHighlightsCommand ) ); tb.Tag = evts; headerCount++; return tb; } private GridSplitter BuildSplitter( ref int splitterCount , double width , double height , GridResizeDirection direction , int position , Action<DragCompletedEventArgs> action ) { GridSplitter gridSplitter = null; if ( splitterCount < _splitters.Count ) { gridSplitter = _splitters[splitterCount]; (int position, IDisposable drag) tag = ((int, IDisposable)) gridSplitter.Tag; tag.drag.Dispose(); } else { gridSplitter = new GridSplitter(); _splitters.Add( gridSplitter ); } gridSplitter.Width = width; gridSplitter.Height = height; gridSplitter.ResizeDirection = direction; gridSplitter.Background = Brushes.Transparent; var drag = gridSplitter.Events().DragCompleted .Do( e => action( e ) ) .Select( _ => Unit.Default ) .ObserveOn( RxApp.MainThreadScheduler ) .InvokeCommand( ViewModel , x => x.DrawGridCommand ); gridSplitter.Tag = (position, drag); splitterCount++; return gridSplitter; } } }
46.426045
200
0.545936
[ "MIT" ]
CyLuGh/HierarchyGrid
src/VirtualHierarchyGrid/HierarchyGrid.Render.cs
28,879
C#
 // -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="TestRecurringInfo.cs"> // Copyright (c) 2018 Aspose.Tasks for Cloud // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- using Aspose.Tasks.Cloud.Sdk.Model; using Aspose.Tasks.Cloud.Sdk.Model.Requests; using Aspose.Tasks.Cloud.Sdk.Tests.Base; using NUnit.Framework; using System; using System.Linq; using System.Net; using Task = System.Threading.Tasks.Task; namespace Aspose.Tasks.Cloud.Sdk.Tests.Tasks { [TestFixture] public class TestRecurringInfo : BaseTestContext { [Test] public async Task TestGetTaskRecurringInfo() { var remoteName = await UploadFileToStorageAsync("sample.mpp"); var response = await TasksApi.GetTaskRecurringInfoAsync(new GetTaskRecurringInfoRequest { Name = remoteName, Folder = this.DataFolder, TaskUid = 6 }); Assert.AreEqual((int)HttpStatusCode.OK, response.Code); Assert.IsNotNull(response.RecurringInfo); var entity = response.RecurringInfo; Assert.AreEqual(2, (int)entity.Occurrences); Assert.AreEqual(RecurrencePattern.Monthly, entity.RecurrencePattern); Assert.AreEqual(true, entity.UseEndDate); Assert.AreEqual(false, entity.MonthlyUseOrdinalDay); Assert.AreEqual(1, entity.MonthlyDay); Assert.AreEqual(WeekDayType.None, entity.WeeklyDays); Assert.AreEqual(OrdinalNumber.Second, entity.YearlyOrdinalNumber); } [Test] public async Task TestUpdateTaskRecurringInfo() { var remoteName = await UploadFileToStorageAsync("sample.mpp"); var response = await TasksApi.GetTaskRecurringInfoAsync(new GetTaskRecurringInfoRequest { Name = remoteName, Folder = this.DataFolder, TaskUid = 6 }); Assert.AreEqual((int)HttpStatusCode.OK, response.Code); Assert.IsNotNull(response.RecurringInfo); var recurringInfo = response.RecurringInfo; recurringInfo.Occurrences = 10; var putResponse = await TasksApi.PutTaskRecurringInfoAsync(new PutTaskRecurringInfoRequest { Name = remoteName, Folder = this.DataFolder, TaskUid = 6, RecurringInfo = recurringInfo }); Assert.AreEqual((int)HttpStatusCode.OK, putResponse.Code); response = await TasksApi.GetTaskRecurringInfoAsync(new GetTaskRecurringInfoRequest { Name = remoteName, Folder = this.DataFolder, TaskUid = 6 }); Assert.AreEqual((int)HttpStatusCode.OK, response.Code); Assert.IsNotNull(response.RecurringInfo); var entity = response.RecurringInfo; Assert.AreEqual(10, (int)entity.Occurrences); Assert.AreEqual(RecurrencePattern.Monthly, entity.RecurrencePattern); Assert.AreEqual(true, entity.UseEndDate); Assert.AreEqual(false, entity.MonthlyUseOrdinalDay); Assert.AreEqual(1, entity.MonthlyDay); Assert.AreEqual(WeekDayType.None, entity.WeeklyDays); Assert.AreEqual(OrdinalNumber.Second, entity.YearlyOrdinalNumber); } [Test] public async Task TestAddRecurringTask() { var remoteName = await UploadFileToStorageAsync("sample.mpp"); RecurringInfo recurringInfo = new RecurringInfo { RecurrencePattern = RecurrencePattern.Weekly, Occurrences = 4, WeeklyRepetitions = 3, WeeklyDays = WeekDayType.Thursday | WeekDayType.Wednesday, StartDate = new DateTime(2018, 1, 1, 8, 0, 0), EndDate = new DateTime(2018, 12, 31), UseEndDate = true }; var response = await TasksApi.PostTaskRecurringInfoAsync(new PostTaskRecurringInfoRequest { Name = remoteName, Folder = this.DataFolder, ParentTaskUid = 0, RecurringInfo = recurringInfo, TaskName = "New recurring task", CalendarName = "Standard" }); Assert.AreEqual((int)HttpStatusCode.Created, response.Code); Assert.IsNotNull(response.TaskItem); var getTaskResponse = await TasksApi.GetTaskAsync( new GetTaskRequest { Name = remoteName, Folder = this.DataFolder, TaskUid = response.TaskItem.Uid }); Assert.AreEqual((int)HttpStatusCode.OK, getTaskResponse.Code); Assert.AreEqual(18, getTaskResponse.Task.SubtasksUids.Count); var lastTaskUid = getTaskResponse.Task.SubtasksUids.Max(); getTaskResponse = await TasksApi.GetTaskAsync( new GetTaskRequest { Name = remoteName, Folder = this.DataFolder, TaskUid = lastTaskUid.Value }); Assert.AreEqual(new DateTime(2018, 12, 27, 8, 0, 0), getTaskResponse.Task.Start); } } }
48.928144
119
0.488312
[ "MIT" ]
aspose-tasks-cloud/aspose-tasks-cloud-dotnet
Aspose.Tasks.Cloud.Sdk.Tests/Tasks/TestRecurringInfo.cs
8,173
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface ISecurityBaselineStateSummaryRequest. /// </summary> public partial interface ISecurityBaselineStateSummaryRequest : IBaseRequest { /// <summary> /// Creates the specified SecurityBaselineStateSummary using POST. /// </summary> /// <param name="securityBaselineStateSummaryToCreate">The SecurityBaselineStateSummary to create.</param> /// <returns>The created SecurityBaselineStateSummary.</returns> System.Threading.Tasks.Task<SecurityBaselineStateSummary> CreateAsync(SecurityBaselineStateSummary securityBaselineStateSummaryToCreate); /// <summary> /// Creates the specified SecurityBaselineStateSummary using POST. /// </summary> /// <param name="securityBaselineStateSummaryToCreate">The SecurityBaselineStateSummary to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created SecurityBaselineStateSummary.</returns> System.Threading.Tasks.Task<SecurityBaselineStateSummary> CreateAsync(SecurityBaselineStateSummary securityBaselineStateSummaryToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified SecurityBaselineStateSummary. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified SecurityBaselineStateSummary. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified SecurityBaselineStateSummary. /// </summary> /// <returns>The SecurityBaselineStateSummary.</returns> System.Threading.Tasks.Task<SecurityBaselineStateSummary> GetAsync(); /// <summary> /// Gets the specified SecurityBaselineStateSummary. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The SecurityBaselineStateSummary.</returns> System.Threading.Tasks.Task<SecurityBaselineStateSummary> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified SecurityBaselineStateSummary using PATCH. /// </summary> /// <param name="securityBaselineStateSummaryToUpdate">The SecurityBaselineStateSummary to update.</param> /// <returns>The updated SecurityBaselineStateSummary.</returns> System.Threading.Tasks.Task<SecurityBaselineStateSummary> UpdateAsync(SecurityBaselineStateSummary securityBaselineStateSummaryToUpdate); /// <summary> /// Updates the specified SecurityBaselineStateSummary using PATCH. /// </summary> /// <param name="securityBaselineStateSummaryToUpdate">The SecurityBaselineStateSummary to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated SecurityBaselineStateSummary.</returns> System.Threading.Tasks.Task<SecurityBaselineStateSummary> UpdateAsync(SecurityBaselineStateSummary securityBaselineStateSummaryToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> ISecurityBaselineStateSummaryRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> ISecurityBaselineStateSummaryRequest Expand(Expression<Func<SecurityBaselineStateSummary, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> ISecurityBaselineStateSummaryRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> ISecurityBaselineStateSummaryRequest Select(Expression<Func<SecurityBaselineStateSummary, object>> selectExpression); } }
52.592593
182
0.677641
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/ISecurityBaselineStateSummaryRequest.cs
5,680
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloud9-2017-09-23.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.Cloud9 { /// <summary> /// Configuration for accessing Amazon Cloud9 service /// </summary> public partial class AmazonCloud9Config : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.1.26"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonCloud9Config() { this.AuthenticationServiceName = "cloud9"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "cloud9"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2017-09-23"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
25.8
104
0.582849
[ "Apache-2.0" ]
nechemiaseif/aws-sdk-net
sdk/src/Services/Cloud9/Generated/AmazonCloud9Config.cs
2,064
C#
/* * Copyright 2019-2021 Andrey Pokidov <andrey.pokidov@gmail.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. */ using System; /* * Author: Andrey Pokidov * Date: 30 Aug 2019 */ namespace Geometry.Stereometry { public struct Ray3 { public Vector3 BasicPoint; private Vector3 direction; private bool valid; public Ray3(Vector3 startPoint, Vector3 direction) { this.BasicPoint = startPoint; this.direction = direction; this.valid = this.direction.Normalize(); } public Ray3(Ray3 line) { this.BasicPoint = line.BasicPoint; this.direction = line.direction; this.valid = line.valid; } public Vector3 Direction { get { return direction; } set { this.direction = value; this.valid = this.direction.Normalize(); } } public bool IsValid() { return this.valid; } public Vector3 PointAt(double position) { return new Vector3(this.BasicPoint.x + direction.x * position, this.BasicPoint.y + direction.y * position, this.BasicPoint.z + direction.z * position); } public LineSegment3 Segment(double positionA, double positionB) { return new LineSegment3(this.PointAt(positionA), this.PointAt(positionB)); } public Ray3F ToFloat() { return new Ray3F(this.BasicPoint.ToFloat(), this.direction.ToFloat()); } } }
26.47561
163
0.593275
[ "Apache-2.0" ]
Morgend/Geometry.Net
src/Geometry/Stereometry/Ray3.cs
2,173
C#
using System; using System.Collections.ObjectModel; namespace Count4U.Model.ProcessC4U { public class Ports : ObservableCollection<Port> { public static Ports FromEnumerable(System.Collections.Generic.IEnumerable<Port> List) { Ports ports = new Ports(); foreach (Port item in List) { ports.Add(item); } return ports; } public Port CurrentItem { get; set; } public System.EventHandler CurrentChanged { get; set; } public long TotalCount { get; set; } } }
21.423077
87
0.624776
[ "MIT" ]
parad74/Count4U.Service.5
src/Count4U.Model.ServiceContract/ProcessC4U/Port/Ports.cs
559
C#
using System.Linq; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using RabbitMQ.Client.Core.DependencyInjection.Configuration; using RabbitMQ.Client.Core.DependencyInjection.Exceptions; using RabbitMQ.Client.Core.DependencyInjection.InternalExtensions; using RabbitMQ.Client.Core.DependencyInjection.Models; using RabbitMQ.Client.Core.DependencyInjection.Services; using RabbitMQ.Client.Core.DependencyInjection.Services.Interfaces; namespace RabbitMQ.Client.Core.DependencyInjection { /// <summary> /// DI extensions for batch message handlers. /// </summary> public static class BatchMessageHandlerDependencyInjectionExtensions { /// <summary> /// Add batch message handler. /// </summary> /// <typeparam name="TBatchMessageHandler">Batch message handler type.</typeparam> /// <param name="services">Service collection.</param> /// <param name="configuration">RabbitMq configuration section.</param> /// <returns>Service collection.</returns> public static IServiceCollection AddBatchMessageHandler<TBatchMessageHandler>(this IServiceCollection services, IConfiguration configuration) where TBatchMessageHandler : BaseBatchMessageHandler { CheckIfBatchMessageHandlerAlreadyConfigured<TBatchMessageHandler>(services); services.TryAddSingleton<IRabbitMqConnectionFactory, RabbitMqConnectionFactory>(); var configurationInstance = RabbitMqServiceOptionsDependencyInjectionExtensions.GetRabbitMqServiceOptionsInstance(configuration); services.ConfigureBatchConsumerConnectionOptions<TBatchMessageHandler>(configurationInstance); services.AddHostedService<TBatchMessageHandler>(); return services; } /// <summary> /// Add batch message handler. /// </summary> /// <typeparam name="TBatchMessageHandler">Batch message handler type.</typeparam> /// <param name="services">Service collection.</param> /// <param name="configuration">RabbitMq configuration <see cref="RabbitMqServiceOptions"/>.</param> /// <returns>Service collection.</returns> public static IServiceCollection AddBatchMessageHandler<TBatchMessageHandler>(this IServiceCollection services, RabbitMqServiceOptions configuration) where TBatchMessageHandler : BaseBatchMessageHandler { CheckIfBatchMessageHandlerAlreadyConfigured<TBatchMessageHandler>(services); services.TryAddSingleton<IRabbitMqConnectionFactory, RabbitMqConnectionFactory>(); services.ConfigureBatchConsumerConnectionOptions<TBatchMessageHandler>(configuration); services.AddHostedService<TBatchMessageHandler>(); return services; } private static IServiceCollection ConfigureBatchConsumerConnectionOptions<TBatchMessageHandler>(this IServiceCollection services, RabbitMqServiceOptions serviceOptions) where TBatchMessageHandler : BaseBatchMessageHandler { var options = new BatchConsumerConnectionOptions { Type = typeof(TBatchMessageHandler), ServiceOptions = serviceOptions }; var serviceDescriptor = new ServiceDescriptor(typeof(BatchConsumerConnectionOptions), options); services.Add(serviceDescriptor); return services; } private static void CheckIfBatchMessageHandlerAlreadyConfigured<TBatchMessageHandler>(this IServiceCollection services) { var descriptor = services.FirstOrDefault(x => x.ImplementationType == typeof(TBatchMessageHandler)); if (descriptor != null) { throw new BatchMessageHandlerAlreadyConfiguredException(typeof(TBatchMessageHandler), $"A batch message handler of type {typeof(TBatchMessageHandler)} has already been configured."); } } } }
53.552632
198
0.72629
[ "MIT" ]
ualehosaini/RabbitMQ.Client.Core.DependencyInjection
src/RabbitMQ.Client.Core.DependencyInjection/BatchMessageHandlerDependencyInjectionExtensions.cs
4,070
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace ChromeRemoteSharp.DomStorageDomain { public partial class DomStorageDomain { /// <summary> /// /// <see cref="https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-removeDOMStorageItem"/> /// </summary> /// <param name="storageId"></param> /// <param name="key"></param> /// <returns></returns> public async Task<JObject> RemoveDOMStorageItemAsync(string storageId, string key) { return await CommandAsync("removeDOMStorageItem", new KeyValuePair<string, object>("storageId", storageId), new KeyValuePair<string, object>("key", key) ); } } }
31.666667
119
0.617544
[ "MIT" ]
jefersonsv/ChromeRemoteSharp
src/ChromeRemoteSharp/DomStorageDomain/RemoveDOMStorageItemAsync.cs
855
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using Microsoft.Rest; using Xunit.Abstractions; namespace Fluent.Tests.Common { /// <summary> /// This class allows to output http requests and responses to console for tests. To use, add following code as test class constructor: /// /// public TestClass(ITestOutputHelper output) /// { /// TestHelper.TestLogger = output; /// ServiceClientTracing.IsEnabled = true; /// ServiceClientTracing.AddTracingInterceptor(new XunitTracingInterceptor(output)); /// } /// </summary> public class XunitTracingInterceptor : IServiceClientTracingInterceptor { private ITestOutputHelper _logger; public XunitTracingInterceptor(ITestOutputHelper output) { _logger = output; } public void Configuration(string source, string name, string value) { } public void EnterMethod(string invocationId, object instance, string method, IDictionary<string, object> parameters) { } public void ExitMethod(string invocationId, object returnValue) { } public void Information(string message) { _logger.WriteLine("INFO: " + message); } public void ReceiveResponse(string invocationId, HttpResponseMessage response) { string requestAsString = (response == null ? string.Empty : response.AsFormattedString()); _logger.WriteLine(string.Format(CultureInfo.InvariantCulture, "invocationId: {0}\r\nresponse: {1}", invocationId, requestAsString)); } public void SendRequest(string invocationId, HttpRequestMessage request) { string requestAsString = (request == null ? string.Empty : request.AsFormattedString()); _logger.WriteLine(string.Format(CultureInfo.InvariantCulture, "invocationId: {0}\r\nrequest: {1}", invocationId, requestAsString)); } public void TraceError(string invocationId, Exception exception) { _logger.WriteLine("ERROR: invocationId: " + invocationId, exception); } } }
34.753623
139
0.660967
[ "MIT" ]
AntoineGa/azure-libraries-for-net
Tests/Fluent.Tests/Common/XunitTracingInterceptor.cs
2,398
C#
using UnityEngine; using System.Collections; using DrForgetful; public class PlayerNoJumpMission : Mission { public PlayerNoJumpMission() { eventType = "playerJump"; missionTime = 3; } public override string GetDescription() { return "Don't jump for " + missionTime.ToString() + " seconds!"; } public override bool Success () { if(!active) return false; if(succeeded) return true; if(count < 1 && OverTime()) { succeeded = true; return true; } else { return false; } } public override bool Fail() { if(!active) return false; if(succeeded) return false; else return (count > 0); } }
13.708333
66
0.641337
[ "MIT" ]
Sartoon/unity-missions
Mission System/PlatformerExamples/PlayerNoJumpMission.cs
660
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Marketplace.Models.Api20210601 { using Microsoft.Azure.PowerShell.Cmdlets.Marketplace.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="QueryRequestApprovalProperties" /> /// </summary> public partial class QueryRequestApprovalPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="QueryRequestApprovalProperties" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="QueryRequestApprovalProperties" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Marketplace.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Marketplace.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="QueryRequestApprovalProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="QueryRequestApprovalProperties" />.</param> /// <returns> /// an instance of <see cref="QueryRequestApprovalProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Marketplace.Models.Api20210601.IQueryRequestApprovalProperties ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Marketplace.Models.Api20210601.IQueryRequestApprovalProperties).IsAssignableFrom(type)) { return sourceValue; } try { return QueryRequestApprovalProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return QueryRequestApprovalProperties.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return QueryRequestApprovalProperties.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
52.979592
253
0.599255
[ "MIT" ]
Agazoth/azure-powershell
src/Marketplace/Marketplace.Autorest/generated/api/Models/Api20210601/QueryRequestApprovalProperties.TypeConverter.cs
7,642
C#
//Copyright 2019 Volodymyr Podshyvalov // //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.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfHandler.UI.Controls.Logon { /// <summary> /// Interaction logic for RegistrationPanel.xaml /// </summary> public partial class RegistrationPanel : UserControl { public static readonly DependencyProperty ContinueCallbackProperty = DependencyProperty.Register( "ContinueCallback", typeof(Action<object>), typeof(RegistrationPanel)); public static readonly DependencyProperty BackCallbackProperty = DependencyProperty.Register( "BackCallback", typeof(Action<object>), typeof(RegistrationPanel)); #region Properties /// <summary> /// Method that will has been calling during click on button. /// </summary> public Action<object> ContinueCallback { get { return (Action<object>)this.GetValue(ContinueCallbackProperty); } set { this.SetValue(ContinueCallbackProperty, value); } } /// <summary> /// Method that will has been calling during click on button. /// </summary> public Action<object> BackCallback { get { return (Action<object>)this.GetValue(BackCallbackProperty); } set { this.SetValue(BackCallbackProperty, value); } } /// <summary> /// Margine of scalable panel. /// </summary> public Thickness RegFormMargin { get { return new Thickness(0, 0, 0, ActualHeight / 2 - regPanel_FormBlock.ActualHeight / 2); } } /// <summary> /// Auto-scalable form width. /// </summary> public double RegFormWidth { get { return Math.Min(Math.Max(150, ActualWidth - 20), 400); } } /// <summary> /// Current login value in the field. /// </summary> public string Login { get { return regLoginField.Text; } set { regLoginField.Text = value; } } /// <summary> /// Current password value in the field. /// </summary> public string Password { get { return regPasswordField.Text; } set { regPasswordField.Text = value; } } /// <summary> /// Current password's confirmation value in the field. /// </summary> public string PasswordConfirmation { get { return regPasswordField2.Text; } set { regPasswordField2.Text = value; } } /// <summary> /// Current first name value in the field. /// </summary> public string FirstName { get { return regFNameField.Text; } set { regFNameField.Text = value; } } /// <summary> /// Current first name value in the field. /// </summary> public string MiddleName { get { return regMNameField.Text; } set { regMNameField.Text = value; } } /// <summary> /// Current first name value in the field. /// </summary> public string LastName { get { return regLNameField.Text; } set { regLNameField.Text = value; } } /// <summary> /// Does "password not match" error label is enabled. /// </summary> public bool PasswordNotMatchErrorLabel { get { return regPanel_error_lPNM.Visibility == Visibility.Visible; } set { regPanel_error_lPNM.Visibility = value ? Visibility.Visible : Visibility.Collapsed; } } /// <summary> /// Does "fiill all field" error label is enabled. /// </summary> public bool FillAllFieldErrorLabel { get { return regPanel_error_lFAF.Visibility == Visibility.Visible; } set { regPanel_error_lFAF.Visibility = value ? Visibility.Visible : Visibility.Collapsed; } } /// <summary> /// Error message tha twould displayed at UI's label. /// </summary> public string ErrorMessage { set { // Hide message if null. if (value == null) { regPanel_error_server.Visibility = Visibility.Collapsed; return; } // Show message. regPanel_error_server.Visibility = Visibility.Visible; regPanel_error_server.Content = value; } } /// <summary> /// Check if passwords is the same and not null. /// </summary> public bool IsPasswordsTheSame { get { if (regPasswordField.Text == null || regPasswordField2.Text == null) { return false; } return string.Equals(regPasswordField.Text, regPasswordField2.Text); } } #endregion #region Constructor\desctructor public RegistrationPanel() { #region WPF Init InitializeComponent(); DataContext = this; // Subscribe on events SizeChanged += MainWindow_SizeChanged; // Subscribe delegate on buttons. regBack.ClickCallback += BackCallbackHandler; regContinue.ClickCallback += ContinueCallbackHandler; #endregion } ~RegistrationPanel() { // Unsubscribe from events. SizeChanged -= MainWindow_SizeChanged; // Unsubscribe delegate from buttons. try { regBack.ClickCallback -= BackCallbackHandler; } catch { }; try { regContinue.ClickCallback -= ContinueCallbackHandler; } catch { }; } #endregion /// <summary> /// Clear all data filled to form. /// </summary> public void Clear() { Login = ""; Password = ""; PasswordConfirmation = ""; FirstName = ""; MiddleName = ""; LastName = ""; PasswordNotMatchErrorLabel = false; FillAllFieldErrorLabel = false; ErrorMessage = null; } #region Callbacks /// <summary> /// Callback that will has been calling when widow size will be changed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e) { // Update size of control panel. BindingOperations.GetBindingExpression(regPanel_FormBlock, MarginProperty).UpdateTarget(); // Update size of control panel. BindingOperations.GetBindingExpression(regPanel_FormBlock, WidthProperty).UpdateTarget(); } /// <summary> /// Callback that will caling when panel will loaded. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LogonPanel_Loaded(object sender, RoutedEventArgs e) { // Call recomputing of size. MainWindow_SizeChanged(sender, null); } /// <summary> /// Callback to continue button. /// </summary> /// <param name="sender"></param> private void ContinueCallbackHandler(object sender) { ContinueCallback?.Invoke(sender); } /// <summary> /// Callback to back button. /// </summary> /// <param name="sender"></param> private void BackCallbackHandler(object sender) { BackCallback?.Invoke(sender); } #endregion } }
31.318021
105
0.559179
[ "Apache-2.0" ]
ElbyFross/datum-point
Frameworks/WpfHandler/UI/Controls/Logon/RegistrationPanel.xaml.cs
8,865
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 Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class InstantiateArgumentExceptionsCorrectlyTests : DiagnosticAnalyzerTestBase { private static readonly string s_noArguments = SystemRuntimeAnalyzersResources.InstantiateArgumentExceptionsCorrectlyMessageNoArguments; private static readonly string s_incorrectMessage = SystemRuntimeAnalyzersResources.InstantiateArgumentExceptionsCorrectlyMessageIncorrectMessage; private static readonly string s_incorrectParameterName = SystemRuntimeAnalyzersResources.InstantiateArgumentExceptionsCorrectlyMessageIncorrectParameterName; protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new InstantiateArgumentExceptionsCorrectlyAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new InstantiateArgumentExceptionsCorrectlyAnalyzer(); } [Fact] public void ArgumentException_NoArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentException(); } }", GetCSharpExpectedResult(6, 31, s_noArguments, "ArgumentException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException() End Sub End Class", GetBasicExpectedResult(4, 31, s_noArguments, "ArgumentException")); } [Fact] public void ArgumentException_EmptyParameterNameArgument_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "", "paramName", "ArgumentNullException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException("""") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", "", "paramName", "ArgumentNullException")); } [Fact] public void ArgumentNullException_SpaceParameterArgument_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException("" ""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", " ", "paramName", "ArgumentNullException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException("" "") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", " ", "paramName", "ArgumentNullException")); } [Fact] public void ArgumentNullException_NameofNonParameter_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { var foo = new object(); throw new System.ArgumentNullException(nameof(foo)); } }", GetCSharpExpectedResult(7, 31, s_incorrectParameterName, "Test", "foo", "paramName", "ArgumentNullException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Dim foo As New Object() Throw New System.ArgumentNullException(NameOf(foo)) End Sub End Class", GetBasicExpectedResult(5, 31, s_incorrectParameterName, "Test", "foo", "paramName", "ArgumentNullException")); } [Fact] public void ArgumentException_ParameterNameAsMessage_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first""); } }", GetCSharpExpectedResult(6, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first"") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentException")); } [Fact] public void ArgumentException_ReversedArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first"", ""first is incorrect""); } }", GetCSharpExpectedResult(6, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentException"), GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "first is incorrect", "paramName", "ArgumentException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first"", ""first is incorrect"") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentException"), GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", "first is incorrect", "paramName", "ArgumentException")); } [Fact] public void ArgumentNullException_NoArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(); } }", GetCSharpExpectedResult(6, 31, s_noArguments, "ArgumentNullException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException() End Sub End Class", GetBasicExpectedResult(4, 31, s_noArguments, "ArgumentNullException")); } [Fact] public void ArgumentNullException_MessageAsParameterName_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first is null""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "first is null", "paramName", "ArgumentNullException")); } [Fact] public void ArgumentNullException_ReversedArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first is null"", ""first""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "first is null", "paramName", "ArgumentNullException"), GetCSharpExpectedResult(6, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentNullException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(""first is null"", ""first"") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", "first is null", "paramName", "ArgumentNullException"), GetBasicExpectedResult(4, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentNullException")); } [Fact] public void ArgumentOutOfRangeException_NoArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(); } }", GetCSharpExpectedResult(6, 31, s_noArguments, "ArgumentOutOfRangeException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException() End Sub End Class", GetBasicExpectedResult(4, 31, s_noArguments, "ArgumentOutOfRangeException")); } [Fact] public void ArgumentOutOfRangeException_MessageAsParameterName_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first is out of range""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "first is out of range", "paramName", "ArgumentOutOfRangeException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException(""first is out of range"") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", "first is out of range", "paramName", "ArgumentOutOfRangeException")); } [Fact] public void ArgumentOutOfRangeException_ReversedArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first is out of range"", ""first""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "first is out of range", "paramName", "ArgumentOutOfRangeException"), GetCSharpExpectedResult(6, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentOutOfRangeException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException(""first is out of range"", ""first"") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", "first is out of range", "paramName", "ArgumentOutOfRangeException"), GetBasicExpectedResult(4, 31, s_incorrectMessage, "Test", "first", "message", "ArgumentOutOfRangeException")); } [Fact] public void DuplicateWaitObjectException_NoArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(); } }", GetCSharpExpectedResult(6, 31, s_noArguments, "DuplicateWaitObjectException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException() End Sub End Class", GetBasicExpectedResult(4, 31, s_noArguments, "DuplicateWaitObjectException")); } [Fact] public void DuplicateWaitObjectException_MessageAsParameterName_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first is duplicate""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "first is duplicate", "parameterName", "DuplicateWaitObjectException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first is duplicate"") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", "first is duplicate", "parameterName", "DuplicateWaitObjectException")); } [Fact] public void DuplicateWaitObjectException_ReversedArguments_Warns() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first is duplicate"", ""first""); } }", GetCSharpExpectedResult(6, 31, s_incorrectParameterName, "Test", "first is duplicate", "parameterName", "DuplicateWaitObjectException"), GetCSharpExpectedResult(6, 31, s_incorrectMessage, "Test", "first", "message", "DuplicateWaitObjectException")); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first is duplicate"", ""first"") End Sub End Class", GetBasicExpectedResult(4, 31, s_incorrectParameterName, "Test", "first is duplicate", "parameterName", "DuplicateWaitObjectException"), GetBasicExpectedResult(4, 31, s_incorrectMessage, "Test", "first", "message", "DuplicateWaitObjectException")); } [Fact] public void ArgumentException_CorrectMessage_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first is incorrect""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first is incorrect"") End Sub End Class"); } [Fact] public void ArgumentException_CorrectMessageAndParameterName_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentException(""first is incorrect"", ""first""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentException(""first is incorrect"", ""first"") End Sub End Class"); } [Fact] public void ArgumentNullException_CorrectParameterName_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(""first"") End Sub End Class"); } [Fact] public void ArgumentNullException_NameofParameter_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(nameof(first)); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(NameOf(first)) End Sub End Class"); } [Fact] public void ArgumentNull_CorrectParameterNameAndMessage_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentNullException(""first"", ""first is null""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentNullException(""first"", ""first is null"") End Sub End Class"); } [Fact] public void ArgumentOutOfRangeException_CorrectParameterName_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.ArgumentOutOfRangeException(""first"") End Sub End Class"); } [Fact] public void ArgumentOutOfRangeException_CorrectParameterNameAndMessage_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.ArgumentOutOfRangeException(""first"", ""first is out of range""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first"", ""first is out of range"") End Sub End Class"); } [Fact] public void DuplicateWaitObjectException_CorrectParameterName_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first"") End Sub End Class"); } [Fact] public void DuplicateWaitObjectException_CorrectParameterNameAndMessage_DoesNotWarn() { VerifyCSharp(@" public class Class { public void Test(string first) { throw new System.DuplicateWaitObjectException(""first"", ""first is duplicate""); } }"); VerifyBasic(@" Public Class [MyClass] Public Sub Test(first As String) Throw New System.DuplicateWaitObjectException(""first"", ""first is duplicate"") End Sub End Class"); } private static DiagnosticResult GetCSharpExpectedResult(int line, int column, string format, params string[] args) { string message = string.Format(format, args); return GetCSharpResultAt(line, column, InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicExpectedResult(int line, int column, string format, params string[] args) { string message = string.Format(format, args); return GetBasicResultAt(line, column, InstantiateArgumentExceptionsCorrectlyAnalyzer.RuleId, message); } } }
39.690217
166
0.514537
[ "Apache-2.0" ]
RikkiGibson/roslyn-analyzers
src/Microsoft.NetCore.Analyzers/UnitTests/Runtime/InstantiateArgumentExceptionsCorrectlyTests.cs
21,909
C#
namespace Byteology.GuardClauses { /// <summary> /// Provides an extension point for guarding an argument. /// </summary> /// <typeparam name="T">The type of the guarded argument</typeparam> public interface IGuardClause<out T> { /// <summary> /// Gets the guarded argument. /// </summary> public T Argument { get; } /// <summary> /// Gets the name of the guarded argument. /// </summary> public string ArgumentName { get; } } }
27.1
73
0.546125
[ "MIT" ]
Byteology/guard-clauses
Byteology.GuardClauses/IGuardClause.cs
544
C#
using DataSync; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using UnityEngine; namespace LabDataCollector { public sealed class DataCollector : ILabDataManager { private bool _sendToServer = false; public bool IsClientRunning { get; private set; } private bool _isClientInit = false; private static DataSyncClient _client; private string _saveDataPath; private LabDataScope Scope { get; set; } private Func<string> _userId; private SimpleApplicationLifecycle _applicationLifecycle; private string labDataLogPath => Application.dataPath + "/TestData"; private string _localSaveDataTimeLayout; private ConcurrentQueue<LabDataBase> _dataQueue; private Thread _writeThread; private Dictionary<Type, LabDataWriter> _dataWriterDic; public Action<LabDataBase> GetDataAction { get; set; } static DataCollector() { Instance=new DataCollector(); } private DataCollector() { } public static DataCollector Instance { get; } = null; /// <summary> /// 传入UserID初始化LabDataCollect /// </summary> /// <param name="userId"></param> /// <param name="send2Server"></param> public void LabDataCollectInit(Func<string> userId) { if (_isClientInit) { return; } #region 初始化本地存储 _localSaveDataTimeLayout = LabTools.GetConfig<LabDataConfig>().LocalSaveDataTimeLayout; _userId = userId; _saveDataPath = Application.dataPath + "/Output"; LabTools.CreatSaveDataFolder(_saveDataPath); var userStr = _userId.Invoke().PadLeft(2, '0'); _saveDataPath = string.Join("_", _saveDataPath + "/" + DateTime.Now.ToString(_localSaveDataTimeLayout), userStr); _saveDataPath = LabTools.CreatSaveDataFolder(_saveDataPath); #endregion #region 初始化上传服务 var options = new DataSyncClientOptions() { EndpointAddress = "http://localhost:4000/api/data", ProjectId = LabTools.GetConfig<LabDataConfig>().ProjectId, LogFilePath = labDataLogPath + "/ log.txt" }; //Docker options.EndpointAddress = "http://localhost/api/data"; //server _sendToServer = LabTools.GetConfig<LabDataConfig>().SendToServer; options.EndpointAddress = LabTools.GetConfig<LabDataConfig>().ServerPath; if (!Directory.Exists(labDataLogPath + "/TestStore")) { Directory.CreateDirectory(labDataLogPath + "/TestStore"); } _applicationLifecycle = new SimpleApplicationLifecycle(); _client = new DataSyncClient(new UnityApplicationFolderProvider(labDataLogPath + "/TestStore"), _applicationLifecycle, options, _userId); _client.Init(); _isClientInit = true; StartUpload(); #endregion Application.wantsToQuit += () => !IsClientRunning; _dataWriterDic = new Dictionary<Type, LabDataWriter>(); _dataQueue = new ConcurrentQueue<LabDataBase>(); _writeThread = new Thread(Queue2Send); _writeThread.Start(); } public async void LabDataDispose() { await Task.Run(() => { while(_dataQueue.Count > 0) { Thread.Sleep(100); } }); foreach (var item in _dataWriterDic) { item.Value.WriterDispose(); } GetDataAction = null; Debug.LogError("LabDataDispose"); StopUpload(); _isClientInit = false; } /// <summary> /// 传输数据 /// </summary> public void SendData(LabDataBase data) { _dataQueue.Enqueue(data); GetDataAction?.Invoke(data); } private void Queue2Send() { while (IsClientRunning) { var dataList = new List<LabDataBase>(); while (_dataQueue.TryDequeue(out var resultData)) { dataList.Add(resultData); } foreach (var d in dataList) { DoOnce(d); } } } private void DoOnce(LabDataBase data) { if (!_isClientInit) { Debug.LogError("LabData未初始化"); return; } DataWriterFunc(data); if (_sendToServer) { Scope.Send(data); } } private void DataWriterFunc(LabDataBase data) { var type = data.GetType(); if (!_dataWriterDic.ContainsKey(type)) { string dataPath = _saveDataPath + "/"+_userId.Invoke().PadLeft(2, '0')+"_"+data.GetType().Name + ".json"; LabTools.CreatData(dataPath); _dataWriterDic.Add(type, new LabDataWriter(dataPath)); } _dataWriterDic[type].WriteData(data); } private void StartUpload() { if (IsClientRunning) { return; } Debug.Log("开始"); _applicationLifecycle.OnStarted(EventArgs.Empty); Scope = _client.CreateNewScope(); Scope.StartScope(); IsClientRunning = true; } private void StopUpload() { if (!IsClientRunning) { return; } Debug.Log("停止"); Scope.StopScope(); Scope.Dispose(); _applicationLifecycle.OnStopping(ApplicationStoppingEventArgs.Empty); IsClientRunning = false; } } public class LabDataWriter { private readonly FileStream _fs; private readonly StreamWriter _sw; public LabDataWriter(string path) { _fs = new FileStream(path, FileMode.Append, FileAccess.Write); _sw = new StreamWriter(_fs); } public void WriteData(LabDataBase data) { _sw.WriteLine(data.ToJson()); } public void WriterDispose() { _sw.Flush(); _fs.Close(); } } }
28.285714
125
0.534165
[ "MIT" ]
Wulabalabo/LabDataCollector
LabDataCollector/Assets/LabDataCollector/Scripts/DataCollector.cs
6,796
C#
// *********************************************************************************** // Created by zbw911 // 创建于:2012年12月18日 10:44 // // 修改于:2013年02月18日 18:24 // 文件名:CheckSQL.cs // // 如果有更好的建议或意见请邮件至zbw911#gmail.com // *********************************************************************************** using System; using System.Text.RegularExpressions; namespace Dev.DBUtility { /// <summary> /// /// </summary> public class CheckSQL { // 从数据层去对付SQL注入就是一件很2B的事情,如果这样的话,现在暂时先这样吧,随后我们将重构这种方案, add by zbw911 2012-11-12 /// <summary> /// /// </summary> private static string keyword_level0 = "declare|exec|execute|sysdatabases|database|dbid|db_name|user_name|shutdown|drop|truncate|master|cmdshell|col_name|syscolumns|xtype|object_id|sysobjects"; private static readonly string keyword_level1 = keyword_level0 + "|" + "%20|--|proc|xp_|hkey_|char(0x|selects|fromf|wherew|deleted|updateu|inserti|'|"; private static readonly string[] keywords = keyword_level1.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries); /// <summary> /// 对SQL语句进行注入检测 /// </summary> /// <param name="sql"></param> /// <param name="notallowstr"></param> /// <returns></returns> public static int CheckSQLText(string sql, out string notallowstr) { notallowstr = ""; if (string.IsNullOrEmpty(sql)) { return 1; } sql = sql.ToLower(); if (keywords != null && keywords.Length > 0) { for (int i = 0; i < keywords.Length; i++) { string curkey = keywords[i]; // ""; if (sql.IndexOf(curkey) >= 0) //说明sql不合法 { notallowstr = keywords[i]; return -1; } } } return 1; } /// <summary> /// /// </summary> /// <param name="sqls"></param> /// <param name="notallowstr"></param> /// <returns></returns> public static int CheckSQLText(string[] sqls, out string notallowstr) { notallowstr = ""; foreach (var sql in sqls) { if (CheckSQLText(sql, out notallowstr) == -1) return -1; } return 1; } internal static int CheckSQLText(QueryParameterCollection commandParameters, out string notallow) { notallow = ""; if (commandParameters == null) return 1; foreach (var item in commandParameters) { var parameter = item as QueryParameter; if (parameter == null) continue; if (CheckSQLText(parameter.Value.ToString(), out notallow) == -1) return -1; } return 1; } } }
30.731481
167
0.437481
[ "MIT" ]
zbw911/DevLib.AdoDataAcess
Framework/DataAcess/dev.DBUtility/Helper/CheckSQL.cs
3,499
C#
using System; using System.Windows.Input; using Cradiator.Views; namespace Cradiator.Commands { public class ShowSettingsCommand : ICommand { readonly ICradiatorView _view; readonly ISettingsWindow _settingsWindow; public ShowSettingsCommand(ICradiatorView view, ISettingsWindow settingsWindow) { _view = view; _settingsWindow = settingsWindow; } public bool CanExecute(object parameter) { return _view != null; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _settingsWindow.ShowDialog(); } } }
19.3
81
0.758204
[ "MIT" ]
PandaWood/Cradiator
src/Cradiator/Commands/ShowSettingsCommand.cs
579
C#
using System; using System.Runtime.InteropServices; using System.Text; namespace SPExplorer.UI.Auth { public static class CookieReader { /// <summary> /// Enables the retrieval of cookies that are marked as "HTTPOnly". /// Do not use this flag if you expose a scriptable interface, /// because this has security implications. It is imperative that /// you use this flag only if you can guarantee that you will never /// expose the cookie to third-party code by way of an /// extensibility mechanism you provide. /// Version: Requires Internet Explorer 8.0 or later. /// </summary> private const int INTERNET_COOKIE_HTTPONLY = 0x00002000; /// <summary> /// Returns cookie contents as a string /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetCookie(string url) { int size = 512; StringBuilder sb = new StringBuilder(size); if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)) { if (size < 0) { return null; } sb = new StringBuilder(size); if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)) { return null; } } return sb.ToString(); } [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetGetCookieEx( string url, string cookieName, StringBuilder cookieData, ref int size, int flags, IntPtr pReserved); } }
30.163934
105
0.548913
[ "MIT" ]
xsolon/spexplorer
SpExplorer.UI.Auth/SpExplorer.UI.Auth/CookieReader.cs
1,842
C#
#region using System.Collections; using System.Collections.Generic; using dnlib.DotNet.MD; #endregion namespace dnlib.DotNet.Writer { /// <summary> /// MD table interface /// </summary> public interface IMDTable { /// <summary> /// Gets the table type /// </summary> Table Table { get; } /// <summary> /// <c>true</c> if the table is empty /// </summary> bool IsEmpty { get; } /// <summary> /// Gets the number of rows in this table /// </summary> int Rows { get; } /// <summary> /// Gets/sets a value indicating whether it's sorted /// </summary> bool IsSorted { get; set; } /// <summary> /// <c>true</c> if <see cref="SetReadOnly()" /> has been called /// </summary> bool IsReadOnly { get; } /// <summary> /// Gets/sets the <see cref="TableInfo" /> /// </summary> TableInfo TableInfo { get; set; } /// <summary> /// Called when the table can't be modified any more /// </summary> void SetReadOnly(); /// <summary> /// Gets a raw row /// </summary> /// <param name="rid">Row ID</param> /// <returns>The raw row</returns> IRawRow Get(uint rid); /// <summary> /// Gets all raw rows /// </summary> IEnumerable<IRawRow> GetRawRows(); } /// <summary> /// Creates rows in a table. Rows can optionally be shared to create a compact table. /// </summary> /// <typeparam name="T">The raw row type</typeparam> public sealed class MDTable<T> : IMDTable, IEnumerable<T> where T : IRawRow { private readonly List<T> cached; private readonly Dictionary<T, uint> cachedDict; /// <summary> /// Constructor /// </summary> /// <param name="table">The table type</param> /// <param name="equalityComparer">Equality comparer</param> public MDTable(Table table, IEqualityComparer<T> equalityComparer) { Table = table; cachedDict = new Dictionary<T, uint>(equalityComparer); cached = new List<T>(); } /// <summary> /// Gets the value with rid <paramref name="rid" /> /// </summary> /// <param name="rid">The row ID</param> public T this[uint rid] => cached[(int) rid - 1]; /// <inheritdoc /> public IEnumerator<T> GetEnumerator() { return cached.GetEnumerator(); } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <inheritdoc /> public Table Table { get; } /// <inheritdoc /> public bool IsEmpty => cached.Count == 0; /// <inheritdoc /> public int Rows => cached.Count; /// <inheritdoc /> public bool IsSorted { get; set; } /// <inheritdoc /> public bool IsReadOnly { get; private set; } /// <inheritdoc /> public TableInfo TableInfo { get; set; } /// <inheritdoc /> public IRawRow Get(uint rid) { return this[rid]; } /// <inheritdoc /> public void SetReadOnly() { IsReadOnly = true; } /// <inheritdoc /> public IEnumerable<IRawRow> GetRawRows() { foreach(var rawRow in cached) yield return rawRow; } /// <summary> /// Adds a row. If the row already exists, returns a rid to the existing one, else /// it's created and a new rid is returned. /// </summary> /// <param name="row">The row. It's now owned by us and must NOT be modified by the caller.</param> /// <returns>The RID (row ID) of the row</returns> public uint Add(T row) { if(IsReadOnly) throw new ModuleWriterException(string.Format("Trying to modify table {0} after it's been set to read-only", Table)); uint rid; if(cachedDict.TryGetValue(row, out rid)) return rid; return Create(row); } /// <summary> /// Creates a new row even if this row already exists. /// </summary> /// <param name="row">The row. It's now owned by us and must NOT be modified by the caller.</param> /// <returns>The RID (row ID) of the row</returns> public uint Create(T row) { if(IsReadOnly) throw new ModuleWriterException(string.Format("Trying to modify table {0} after it's been set to read-only", Table)); var rid = (uint) cached.Count + 1; if(!cachedDict.ContainsKey(row)) cachedDict[row] = rid; cached.Add(row); return rid; } /// <summary> /// Re-adds all added rows. Should be called if rows have been modified after being /// inserted. /// </summary> public void ReAddRows() { if(IsReadOnly) throw new ModuleWriterException(string.Format("Trying to modify table {0} after it's been set to read-only", Table)); cachedDict.Clear(); for(var i = 0; i < cached.Count; i++) { var rid = (uint) i + 1; var row = cached[i]; if(!cachedDict.ContainsKey(row)) cachedDict[row] = rid; } } /// <summary> /// Reset the table. /// </summary> public void Reset() { if(IsReadOnly) throw new ModuleWriterException(string.Format("Trying to modify table {0} after it's been set to read-only", Table)); cachedDict.Clear(); cached.Clear(); } } }
27.055085
133
0.479092
[ "MIT" ]
Dekryptor/KoiVM-Virtualization
dnlib/src/DotNet/Writer/MDTable.cs
6,387
C#
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\shared\ksmedia.h(370,1) using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE { } }
25.545455
88
0.725979
[ "MIT" ]
Steph55/DirectN
DirectN/DirectN/Generated/KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE.cs
283
C#
// Copyright (C) 2014 dot42 // // Original filename: HashSet.cs // // 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 System.Collections.Generic { public class HashSet<T> { private readonly Java.Util.HashSet<T> hset; /// <summary> /// Default ctor /// </summary> public HashSet() { hset = new Java.Util.HashSet<T>(); } /// <summary> /// Default ctor /// </summary> public HashSet(IEnumerable<T> source) { hset = new Java.Util.HashSet<T>(); foreach (var item in source) { hset.Add(item); } } /// <summary> /// Default ctor /// </summary> public HashSet(IEqualityComparer<T> comparer) { hset = new Java.Util.HashSet<T>(); } /// <summary> /// Default ctor /// </summary> public HashSet(IEnumerable<T> source, IEqualityComparer<T> comparer) { hset = new Java.Util.HashSet<T>(); foreach (var item in source) { hset.Add(item); } } /// <summary> /// Add the given item to this set. /// </summary> public bool Add(T item) { return hset.Add(item); } /// <summary> /// Remove all items /// </summary> public void Clear() { hset.Clear(); } /// <summary> /// Does this set contain the given item? /// </summary> public bool Contains(T item) { return hset.Contains(item); } /// <summary> /// Remove the given item from this set. /// </summary> public bool Remove(T item) { return hset.Remove(item); } } }
24.845361
76
0.515768
[ "Apache-2.0" ]
Dot42Xna/master
System/Collections/Generic/HashSet.cs
2,410
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Physics; using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// A simple line pointer for drawing lines from the input source origin to the current pointer position. /// </summary> public class LinePointer : BaseControllerPointer { [Range(1, 50)] [SerializeField] [Tooltip("This setting has a high performance cost. Values above 20 are not recommended.")] protected int LineCastResolution = 10; [SerializeField] protected Gradient LineColorSelected = new Gradient(); [SerializeField] protected Gradient LineColorValid = new Gradient(); [SerializeField] protected Gradient LineColorInvalid = new Gradient(); [SerializeField] protected Gradient LineColorNoTarget = new Gradient(); [SerializeField] protected Gradient LineColorLockFocus = new Gradient(); [SerializeField] private BaseMixedRealityLineDataProvider lineBase; /// <summary> /// The Line Data Provider driving this pointer. /// </summary> public BaseMixedRealityLineDataProvider LineBase => lineBase; [SerializeField] [Tooltip("If no line renderers are specified, this array will be auto-populated on startup.")] private BaseMixedRealityLineRenderer[] lineRenderers; /// <summary> /// The current line renderers that this pointer is utilizing. /// </summary> /// <remarks> /// If no line renderers are specified, this array will be auto-populated on startup. /// </remarks> public BaseMixedRealityLineRenderer[] LineRenderers { get { return lineRenderers; } set { lineRenderers = value; } } private void CheckInitialization() { if (lineBase == null) { lineBase = GetComponent<BaseMixedRealityLineDataProvider>(); } if (lineBase == null) { Debug.LogError($"No Mixed Reality Line Data Provider found on {gameObject.name}. Did you forget to add a Line Data provider?"); } if (lineBase != null && (lineRenderers == null || lineRenderers.Length == 0)) { lineRenderers = lineBase.GetComponentsInChildren<BaseMixedRealityLineRenderer>(); } if (lineRenderers == null || lineRenderers.Length == 0) { Debug.LogError($"No Mixed Reality Line Renderers found on {gameObject.name}. Did you forget to add a Mixed Reality Line Renderer?"); } } #region MonoBehaviour Implementation protected virtual void OnValidate() { CheckInitialization(); } protected override void OnEnable() { base.OnEnable(); CheckInitialization(); } protected override void OnDisable() { base.OnDisable(); foreach (BaseMixedRealityLineRenderer lineRenderer in lineRenderers) { lineRenderer.enabled = false; } } #endregion MonoBehaviour Implementation #region IMixedRealityPointer Implementation /// <inheritdoc /> public override void OnPreSceneQuery() { Debug.Assert(lineBase != null); lineBase.UpdateMatrix(); // Set our first and last points if (IsFocusLocked && Result?.Details != null) { // Make the final point 'stick' to the target at the distance of the target SetLinePoints(Position, Result.Details.Point, Result.Details.RayDistance); } else { SetLinePoints(Position, Position + Rotation * Vector3.forward * DefaultPointerExtent, DefaultPointerExtent); } // Make sure our array will hold if (Rays == null || Rays.Length != LineCastResolution) { Rays = new RayStep[LineCastResolution]; } float stepSize = 1f / Rays.Length; Vector3 lastPoint = lineBase.GetUnClampedPoint(0f); for (int i = 0; i < Rays.Length; i++) { Vector3 currentPoint = lineBase.GetUnClampedPoint(stepSize * (i + 1)); Rays[i].UpdateRayStep(ref lastPoint, ref currentPoint); lastPoint = currentPoint; } } /// <inheritdoc /> public override void OnPostSceneQuery() { Gradient lineColor = LineColorNoTarget; if (!IsActive) { lineBase.enabled = false; BaseCursor?.SetVisibility(false); return; } lineBase.enabled = true; BaseCursor?.SetVisibility(true); // The distance the ray travels through the world before it hits something. Measured in world-units (as opposed to normalized distance). float clearWorldLength; // Used to ensure the line doesn't extend beyond the cursor float cursorOffsetWorldLength = (BaseCursor != null) ? BaseCursor.SurfaceCursorDistance : 0; // If we hit something if (Result?.CurrentPointerTarget != null) { clearWorldLength = Result.Details.RayDistance; lineColor = LineColorValid; } else { clearWorldLength = DefaultPointerExtent; lineColor = IsSelectPressed ? LineColorSelected : LineColorNoTarget; } if (IsFocusLocked) { lineColor = LineColorLockFocus; } int maxClampLineSteps = LineCastResolution; foreach (BaseMixedRealityLineRenderer lineRenderer in lineRenderers) { // Renderers are enabled by default if line is enabled lineRenderer.enabled = true; maxClampLineSteps = Mathf.Max(maxClampLineSteps, lineRenderer.LineStepCount); lineRenderer.LineColor = lineColor; } // If focus is locked, we're sticking to the target // So don't clamp the world length if (IsFocusLocked) { float cursorOffsetLocalLength = LineBase.GetNormalizedLengthFromWorldLength(cursorOffsetWorldLength); LineBase.LineEndClamp = 1 - cursorOffsetLocalLength; } else { // Otherwise clamp the line end by the clear distance float clearLocalLength = lineBase.GetNormalizedLengthFromWorldLength(clearWorldLength - cursorOffsetWorldLength, maxClampLineSteps); lineBase.LineEndClamp = clearLocalLength; } } protected virtual void SetLinePoints(Vector3 startPoint, Vector3 endPoint, float distance) { lineBase.FirstPoint = startPoint; lineBase.LastPoint = endPoint; } public override bool IsInteractionEnabled => // If IsTracked is not true, then we don't have position data yet (or have stale data), // so remain disabled until we know where to appear (not just at the origin). IsFocusLocked || (IsTracked && Controller.IsInPointingPose && base.IsInteractionEnabled); #endregion IMixedRealityPointer Implementation } }
35.334842
148
0.589704
[ "MIT" ]
Bhaskers-Blu-Org2/GalaxyExplorer
Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/Pointers/LinePointer.cs
7,811
C#
/** * Copyright 2015 Canada Health Infoway, 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Common.Comt_mt001101ca { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Datatype.Lang; using Ca.Infoway.Messagebuilder.Model; using System.Collections.Generic; /** * <summary>Business Name: Referenced Record</summary> * * <p>As a request, refers to the event to be acted upon or * which has been acted upon.</p><p>As a response, may be used * to indicate the identifier assigned to a created object.</p> * <p>References an existing event record by identifier.</p> */ [Hl7PartTypeMappingAttribute(new string[] {"COMT_MT001101CA.ActRequest"})] public class ReferencedRecord : MessagePartBean { private SET<II, Identifier> id; public ReferencedRecord() { this.id = new SETImpl<II, Identifier>(typeof(IIImpl)); } /** * <summary>Business Name: Record Ids</summary> * * <remarks>Relationship: COMT_MT001101CA.ActRequest.id * Conformance/Cardinality: MANDATORY (1-2) <p>Allows the event * record to be uniquely referenced and is therefore * mandatory.</p> <p>The identifier assigned by the central * system (EHR) to the Event record being referred to.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"id"})] public ICollection<Identifier> Id { get { return this.id.RawSet(); } } } }
40.822581
84
0.659423
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03_imm/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_imm/Common/Comt_mt001101ca/ReferencedRecord.cs
2,531
C#
using static System.Console; namespace MethodChainingDemo.ChainingDemo { public class SoftwareDeveloper { public SoftwareDeveloper GathersRequirements() { WriteLine("Software Develper Gathers Requirements."); return this; } public SoftwareDeveloper WritesCode() { WriteLine("Software Develper Writes Code."); return this; } public SoftwareDeveloper WriteUnitTests() { WriteLine("Software Develper Writes Unit Tests."); return this; } public SoftwareDeveloper DeploysCodeToProduction() { WriteLine("Software Develper Deploys Code To Production."); return this; } } }
21.081081
71
0.584615
[ "MIT" ]
vishipayyallore/speaker_series_csharp_dotnetcode
Day5/MethodChainingDemo/MethodChainingDemo/ChainingDemo/SoftwareDeveloper.cs
782
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Linq.Expressions; using ExpressionEvaluator; using ExpressionEvaluator.Transformer; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Framework; namespace ExpressionEvaulatorTests.Transformer { public class ParanthesizedExpressionTransformerTests { [Test] public void TestParanthesis() { var tree = CSharpSyntaxTree.ParseText("(5)", CSharpParseOptions.Default.WithKind(SourceCodeKind.Script)); ParenthesizedExpressionSyntax parenthesizedSyntax = tree .GetRoot() .DescendantNodes() .OfType<ParenthesizedExpressionSyntax>() .First(); Context context = new Context(); Expression cExp = ParenthesizedExpressionTransformer.INSTANCE.ToExpression(context, parenthesizedSyntax); Assert.AreEqual(((ConstantExpression)cExp).Value, 5); Assert.AreEqual(cExp.Type, typeof(int)); } } }
36.666667
117
0.720856
[ "Apache-2.0" ]
sriksun/ExpressionEvaluator
ExpressionEvaulatorTests/Transformer/ParanthesizedExpressionTransformerTests.cs
1,872
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using System.IO; namespace DiscountAPI.Infrasturcture.Context { public abstract class DesignTimeDbContextFactory<TContext> : IDesignTimeDbContextFactory<TContext> where TContext : DbContext { protected abstract TContext CreateNewInstance(DbContextOptions<TContext> options); public TContext CreateDbContext(string[] args) { DbContextOptionsBuilder<TContext> builder = new DbContextOptionsBuilder<TContext>(); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../DiscountAPI.API")) .AddJsonFile("appsettings.json") .Build(); builder.UseSqlServer(configuration.GetConnectionString("SqlConStr")); return CreateNewInstance(builder.Options); } } }
40.958333
102
0.711089
[ "MIT" ]
efeonier/DiscountAPI
DiscountAPI.Infrasturcture/Context/DesignTimeDbContextFactory.cs
983
C#
/*! * (c) 2016-2018 EntIT Software LLC, a Micro Focus company * * 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 MicroFocus.Adm.Octane.Api.Core.Entities; using MicroFocus.Adm.Octane.VisualStudio.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace MicroFocus.Adm.Octane.VisualStudio.Tests.Utilities.Entity { /// <summary> /// Utility class for managing <see cref="Task"/> /// </summary> public static class TaskUtilities { /// <summary> /// Create a new task entity /// </summary> public static Task CreateTask(WorkItem parent, string customName = null) { var name = customName ?? "Task_" + Guid.NewGuid(); var task = new Task { Name = name, Story = parent }; task.SetValue(CommonFields.Owner, BaseOctanePluginTest.User); var createdTask = BaseOctanePluginTest.EntityService.Create(BaseOctanePluginTest.WorkspaceContext, task, new[] { "name", Task.STORY_FIELD }); Assert.AreEqual(name, createdTask.Name, "Newly created task doesn't have the expected name"); Assert.IsFalse(string.IsNullOrEmpty(createdTask.Id), "Newly created task should have a valid ID"); return createdTask; } } }
37.346939
153
0.67377
[ "Apache-2.0" ]
MicroFocus/octane-visual-studio-plugin
octane-visual-studio-plugin-tests/Utilities/Entity/TaskUtilities.cs
1,832
C#
using CsvHelper; using Raven.Client; using Raven.Client.Document; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using TwinCitiesCodeCamp.Common; using TwinCitiesCodeCamp.Models; namespace TwinCitiesCodeCamp.Controllers { public class FilesController : RavenController { [HttpGet] [Authorize(Roles = "Admin")] public async Task<ActionResult> GetTalkSubmissionsCsv(string eventId) { var pendingTalks = await DbSession.Query<Talk>() .Where(t => t.EventId == eventId) .Skip(0) .Take(1000) // domain-limited, generally will have under 100 .ToListAsync(); using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) using (var csv = new CsvWriter(writer)) { csv.WriteRecords(pendingTalks); return File(stream.ToArray(), "text/csv", $"tccc-talk-submissions-{DateTime.UtcNow.ToShortDateString()}.csv"); } } /// <summary> /// Gets a CORS-safe picture url for a talk. If the talk has a PictureUrl pointing to a CORS-enabled image, that image is used. /// If the image points to a non-CORS enabled image, that image is downloaded on the server and streamed back to the user. /// </summary> /// <remarks>This is ugly and does too many things. It's temporary until we move to Raven 4, at which point we'll just use attachments.</remarks> /// <param name="talkId"></param> /// <returns></returns> [HttpGet] public async Task<ActionResult> GetTalkProfileImage(string talkId) { var talk = await DbSession.LoadAsync<Talk>(talkId); if (talk != null && !string.IsNullOrEmpty(talk.PictureUrl)) { return Redirect(talk.PictureUrl); } return UnknownSpeaker(); } public ActionResult GetTempProfilePic(string talkId) { var fileName = talkId.Replace('/', '-') + ".jpg"; return File(Server.MapPath($"~/App_Data/{fileName}"), "image/jpg"); } public ActionResult UnknownSpeaker() { return Redirect("/content/images/unknown-speaker.jpg"); } } }
35.728571
153
0.611755
[ "MIT" ]
JudahGabriel/twincitiescodecamp
TwinCitiesCodeCamp/Controllers/FilesController.cs
2,503
C#
#region license //MIT License //Copyright(c) 2013-2020 Andreas Hübner //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. #endregion using Interlook.Monads; using System; using System.Collections.Generic; namespace Interlook.Configuration { /// <summary> /// Interface for objects that build <see cref="IParsingResultsDictionary"/> instances. /// Supports adding of actual key/value data or errors. /// </summary> public interface IParsingResultsBuilder { /// <summary> /// Adds the specified key/value data. /// </summary> /// <param name="kvp">The key/value pair.</param> /// <param name="exceptionTextPrefixFactory">An optional function, that will return a prefix for a potential error message.</param> /// <returns>Just <see cref="Unit"/>, which is the functional equivalent to <c>void</c></returns> Unit Add(KeyValuePair<string, string> kvp, Func<string> exceptionTextPrefixFactory = null); /// <summary> /// Adds the specified key/value data. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="exceptionTextPrefixFactory">An optional function, that will return a prefix for a potential error message.</param> /// <returns>Just <see cref="Unit"/>, which is the functional equivalent to <c>void</c></returns> Unit Add(string key, string value, Func<string> exceptionTextPrefixFactory = null); Unit ErrorArgumentRequiresValue(string key, string errorMessage = null); Unit ErrorArgumentAlreadyDefined(string key, string errorMessage = null); Unit ErrorArgumentUnknown(string key, string errorMessage = null); Unit ErrorInvalidParsing(string site, string errorMessage); Unit Error(Exception error); IParsingResultsDictionary GetResults(); } }
43.268657
139
0.71197
[ "MIT" ]
tetrodoxin/Interlook.Configuration
src/Interlook.Configuration/IParsingResultsBuilder.cs
2,902
C#
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; //This Main function should not be run on an active database, it will cause inconsistencies in the data. //These functions are examples on how to run the Database Controller Class namespace Database_Controller { class Database_Control { static void Main(string[] args) { Database_Controller Session = new Database_Controller(); MySqlConnection connection = Session.Input_Form(); Boolean create = Session.Create_Usr(connection, "Bob", "rab313222"); Boolean create2 = Session.Create_Usr(connection, "ablivion", "rab313222"); Console.Out.WriteLine(create); Console.Out.WriteLine(create2); int log1 = Session.Login(connection, "ablivion", "rab313222"); int log2 = Session.Login(connection, "bob", "rab313222"); int log3 = Session.Login(connection, "roger", "lolololrab313222"); Console.Out.WriteLine(log1); Console.Out.WriteLine(log2); Console.Out.WriteLine(log3); Console.Out.Write("Say something cool: "); string say = Console.In.ReadLine(); Session.insert_chat(connection, "ablivion", say, 717); List<string> list = Session.chatroom_recall(connection, 717); foreach (string s in list) { Console.Out.WriteLine(s); } List<string> go = Session.playerchat_recall(connection, "ablivion"); foreach (string s in list) { Console.Out.WriteLine(s); } string [] users = {"ablivion", "rogera24", "bob", "robert", "joejoe", "steve"}; int game_id = Session.create_game(connection, users, "blahgah"); Console.Out.WriteLine(game_id); int message_id = Session.message_save(connection, "This is not a drill! Woop Woop!", 12); Console.Out.WriteLine(message_id); connection.Close(); } } }
31.536232
104
0.612132
[ "Artistic-2.0" ]
rogera24/Multi_Agent_Models
School Work/Capstone_Database_Controller/Main.cs
2,178
C#
# CS_ARCH_X86, CS_MODE_32, CS_OPT_SYNTAX_ATT 0x0f,0x0f,0xca,0xbf = pavgusb %mm2, %mm1 0x0f,0x0f,0x5c,0x16,0x09,0xbf = pavgusb 9(%esi, %edx), %mm3 0x0f,0x0f,0xca,0x1d = pf2id %mm2, %mm1 0x0f,0x0f,0x5c,0x16,0x09,0x1d = pf2id 9(%esi, %edx), %mm3 0x0f,0x0f,0xca,0xae = pfacc %mm2, %mm1 0x0f,0x0f,0xca,0x9e = pfadd %mm2, %mm1 0x0f,0x0f,0xca,0xb0 = pfcmpeq %mm2, %mm1 0x0f,0x0f,0xca,0x90 = pfcmpge %mm2, %mm1 0x0f,0x0f,0xca,0xa0 = pfcmpgt %mm2, %mm1 0x0f,0x0f,0xca,0xa4 = pfmax %mm2, %mm1 0x0f,0x0f,0xca,0x94 = pfmin %mm2, %mm1 0x0f,0x0f,0xca,0xb4 = pfmul %mm2, %mm1 0x0f,0x0f,0xca,0x96 = pfrcp %mm2, %mm1 0x0f,0x0f,0xca,0xa6 = pfrcpit1 %mm2, %mm1 0x0f,0x0f,0xca,0xb6 = pfrcpit2 %mm2, %mm1 0x0f,0x0f,0xca,0xa7 = pfrsqit1 %mm2, %mm1 0x0f,0x0f,0xca,0x97 = pfrsqrt %mm2, %mm1 0x0f,0x0f,0xca,0x9a = pfsub %mm2, %mm1 0x0f,0x0f,0xca,0xaa = pfsubr %mm2, %mm1 0x0f,0x0f,0xca,0x0d = pi2fd %mm2, %mm1 0x0f,0x0f,0xca,0xb7 = pmulhrw %mm2, %mm1 0x0f,0x0e = femms 0x0f,0x0d,0x00 = prefetch (%eax) 0x0f,0x0f,0xca,0x1c = pf2iw %mm2, %mm1 0x0f,0x0f,0xca,0x0c = pi2fw %mm2, %mm1 0x0f,0x0f,0xca,0x8a = pfnacc %mm2, %mm1 0x0f,0x0f,0xca,0x8e = pfpnacc %mm2, %mm1 0x0f,0x0f,0xca,0xbb = pswapd %mm2, %mm1
39.233333
59
0.703483
[ "BSD-3-Clause" ]
FlyGoat/capstone
suite/MC/X86/3DNow.s.cs
1,177
C#
namespace demo { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.reportViewer1 = new Microsoft.Reporting.WinForms.ReportViewer(); this.userControl11 = new WindowsFormsControlLibrary1.UserControl1(); this.axShockwaveFlash1 = new AxShockwaveFlashObjects.AxShockwaveFlash(); ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).BeginInit(); this.SuspendLayout(); // // reportViewer1 // this.reportViewer1.Location = new System.Drawing.Point(286, 201); this.reportViewer1.Name = "reportViewer1"; this.reportViewer1.Size = new System.Drawing.Size(400, 250); this.reportViewer1.TabIndex = 0; // // userControl11 // this.userControl11.Location = new System.Drawing.Point(230, 12); this.userControl11.Name = "userControl11"; this.userControl11.Size = new System.Drawing.Size(456, 170); this.userControl11.TabIndex = 1; // // axShockwaveFlash1 // this.axShockwaveFlash1.Enabled = true; this.axShockwaveFlash1.Location = new System.Drawing.Point(12, 12); this.axShockwaveFlash1.Name = "axShockwaveFlash1"; this.axShockwaveFlash1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axShockwaveFlash1.OcxState"))); this.axShockwaveFlash1.Size = new System.Drawing.Size(192, 192); this.axShockwaveFlash1.TabIndex = 2; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(698, 463); this.Controls.Add(this.axShockwaveFlash1); this.Controls.Add(this.userControl11); this.Controls.Add(this.reportViewer1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).EndInit(); this.ResumeLayout(false); } #endregion private Microsoft.Reporting.WinForms.ReportViewer reportViewer1; private WindowsFormsControlLibrary1.UserControl1 userControl11; private AxShockwaveFlashObjects.AxShockwaveFlash axShockwaveFlash1; } }
41.388235
137
0.608584
[ "MIT", "Unlicense" ]
NuLL3rr0r/tutorials-in-my-class
C#/FlashIntegration/demo/Form1.Designer.cs
3,520
C#
namespace SapphireDb.Command { public class CollectionCommandBase : CommandBase { public string CollectionName { get; set; } public string ContextName { get; set; } = "default"; } }
23.444444
60
0.649289
[ "MIT" ]
greenapp-debug/SapphireDb
SapphireDb/Command/CollectionCommandBase.cs
213
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using NuGet.Frameworks; namespace Snap.Core; internal static class SnapConstants { public static readonly string SnapAppLibraryName = "Snap.App"; public static readonly string SnapDllFilename = "Snap.dll"; public static string SnapAppDllFilename => $"{SnapAppLibraryName}.dll"; public static string SetupNupkgFilename = "Setup.nupkg"; public const string Sha256EmptyFileChecksum = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; public static readonly string SnapUniqueTargetPathFolderName = BuildSnapNuspecUniqueFolderName(); public static readonly string NuspecTargetFrameworkMoniker = NuGetFramework.AnyFramework.Framework; public static readonly string NuspecRootTargetPath = $"lib/{NuspecTargetFrameworkMoniker}"; public static readonly string NuspecAssetsTargetPath = $"{NuspecRootTargetPath}/{SnapUniqueTargetPathFolderName}"; public const string ReleasesFilename = "Snap.Releases"; static string BuildSnapNuspecUniqueFolderName() { var guidStr = typeof(SnapConstants).Assembly.GetCustomAttribute<GuidAttribute>()?.Value; Guid.TryParse(guidStr, out var assemblyGuid); if (assemblyGuid == Guid.Empty) { throw new Exception("Fatal error! Assembly guid is empty"); } return assemblyGuid.ToString("N"); } }
43.363636
118
0.758211
[ "MIT" ]
fintermobilityas/snapx
src/Snap/Core/SnapConstants.cs
1,431
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.Identity.Web { internal static class OidcConstants { public const string AdditionalClaims = "claims"; public const string ScopeOfflineAccess = "offline_access"; public const string ScopeProfile = "profile"; public const string ScopeOpenId = "openid"; } }
31.923077
66
0.703614
[ "MIT" ]
Azure/ace-luna
src/Microsoft.Identity.Web/OidcConstants.cs
415
C#
/* ======================================================================== * Copyright (c) 2019 <vmarvin@gmail.com>. All rights reserved. * * OPC Foundation MIT License 1.00 * * 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. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text.RegularExpressions; namespace nprch { /// <summary>Коллекция вспомогательных функций</summary> class Utils { /// <summary>Конвертирует длинный идентификатор в bytestream</summary> public static byte[] get_octet_id(ulong id) { return BitConverter.GetBytes(id).Take(5).ToArray(); } /// <summary>Вычисляет длинный идентификатор параметра</summary> public static ulong get_long_id(int card_id, short param_no) { return (ulong)card_id + ((ulong)param_no << 32); // вычисляем длинный идентификатор параметра } /// <summary>Конвертирует bytestream в длинный идентификатор параметра</summary> public static ulong parse_long_id(byte[] octets) { int card_id; short param_no; return parse_octet_id(octets, out card_id, out param_no); } /// <summary>Конвертирует bytestream в длинный идентификатор параметра</summary> public static ulong parse_octet_id(byte[] octets, out int card_id, out short param_no) { card_id = BitConverter.ToInt32(octets, 0); param_no = octets[4]; return get_long_id(card_id, param_no); } /// <summary>Конвертирует bytestream в длинный идентификатор параметра</summary> public static ulong parse_octet_id(byte[] octets) { int card_id; short param_no; card_id = BitConverter.ToInt32(octets, 0); param_no = octets[4]; return get_long_id(card_id, param_no); } /// <summary>Конвертирует длинный идентификатор параметра в марку и параметр</summary> public static void parse_long_id(ulong id, out int card_id, out short param_no) { param_no = (short)(id >> 32); card_id = (int)(id - ((ulong)param_no << 32)); } /// <summary>Преобразует перечисление в коллекцию для программной обработки</summary> public static Dictionary<int, string> GetEnumList<T>() { Type enumType = typeof(T); if (!enumType.IsEnum) throw new Exception("Type parameter should be of enum type"); return Enum.GetValues(enumType).Cast<int>().ToDictionary(v => v, v => Enum.GetName(enumType, v)); } /// <summary>Ожидание подтверждения пользователем</summary> public static void UserWait() { Console.Error.Write("<press any key>"); Console.ReadKey(); } /// <summary>Извлекает из паттерна набор параметров</summary> /// <param name="pattern">Описание структуры строки выходных данных</param> /// <returns>Набор параметров</returns> public static Collection<string> parse_pattern(string pattern) { Collection<string> _parameters = new Collection<string>(); foreach (string __str in Regex.Split(pattern, @"[;:]+")) { if (Regex.IsMatch(__str, @"^[$][A-z]+[$]$")) { if (!_parameters.Contains(__str.Trim('$'))) _parameters.Add(__str.Trim('$')); } } return _parameters; } } }
40.186992
110
0.605098
[ "MIT" ]
vmarvin/FRQR
Utils.cs
5,443
C#
using System; using System.Collections.Generic; using System.Text; namespace Doublel.DynamicQueryBuilder.Sort { public enum QuerySortDirection { ASC, DESC } }
14.538462
42
0.68254
[ "Apache-2.0" ]
Olymo/Doublel.QueryableBuilder
src/Sort/QuerySortDirection.cs
191
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ImageSwitcher : MonoBehaviour { public Material Mat; public Texture[] Textures; private int Index; public SteamVR_TrackedController Controller; // Use this for initialization void Start () { Controller.MenuButtonClicked += (sender, args) => { Next(); }; } void Next() { Index = (Index+1)%Textures.Length; Mat.mainTexture = Textures[Index]; } }
18.52
53
0.717063
[ "MIT" ]
cdv-skelex/skelex
skelex/Assets/scripts/ImageSwitcher.cs
465
C#
using Microsoft.Xna.Framework; using System.Collections.Generic; using System.Runtime.Serialization; namespace C3DE.Components { /// <summary> /// A component responible to manage transform operations (translation, rotation and scaling). /// </summary> [DataContract] public class Transform : Component { internal Matrix _worldMatrix; private Vector3 _localRotation; private Vector3 _localPosition; private Vector3 _localScale; private Transform _parent; private Transform _root; private bool _dirty; protected List<Transform> _transforms; public Transform Root { get => _root; internal set { _root = value; } } public Transform Parent { get => _parent; set { if (_parent != null) _parent.Transforms.Remove(this); _parent = value; if (_parent != null) _parent.Transforms.Add(this); } } public List<Transform> Transforms { get { return _transforms; } protected set { _transforms = value; } } public Vector3 Position { get { UpdateWorldMatrix(); return _worldMatrix.Translation; } set { UpdateWorldMatrix(); _localPosition = Vector3.Transform(value, Matrix.Invert(_worldMatrix)); } } [DataMember] public Vector3 LocalPosition { get { return _localPosition; } set { _localPosition = value; } } public Vector3 Rotation { get { UpdateWorldMatrix(); var rotation = Quaternion.Identity; _worldMatrix.ExtractRotation(ref rotation); return rotation.ToEuler(); } set { var result = Quaternion.Euler(value) * Quaternion.Inverse(_parent.Quaternion); _localRotation = result.ToEuler(); } } public Matrix RotationMatrix => Matrix.CreateFromYawPitchRoll(_localRotation.Y, _localRotation.X, _localRotation.Z); public Quaternion Quaternion { get { var rotation = Rotation; return Quaternion.Euler(rotation); } } public Quaternion LocalQuaternion => Quaternion.Euler(_localRotation); [DataMember] public Vector3 LocalRotation { get { return _localRotation; } set { _localRotation = value; } } [DataMember] public Vector3 LocalScale { get { return _localScale; } set { _localScale = value; } } public Matrix WorldMatrix => _worldMatrix; public Vector3 Forward => _worldMatrix.Forward; public Vector3 Backward => _worldMatrix.Backward; public Vector3 Right => _worldMatrix.Right; public Vector3 Left => _worldMatrix.Left; public Vector3 Up => Vector3.Normalize(Position + Vector3.Transform(Vector3.Up, _worldMatrix)); public Transform() : base() { _localPosition = Vector3.Zero; _localRotation = Vector3.Zero; _localScale = Vector3.One; _parent = null; _root = null; _transforms = new List<Transform>(); _dirty = false; _worldMatrix = Matrix.Identity; } public void Translate(float x, float y, float z) { _localPosition.X += x; _localPosition.Y += y; _localPosition.Z += z; } public void Translate(ref Vector3 translation) { Translate(translation.X, translation.Y, translation.Z); } public void Translate(Vector3 translation) { Translate(ref translation); } public void Rotate(float rx, float ry, float rz) { _localRotation.X += rx; _localRotation.Y += ry; _localRotation.Z += rz; } public void Rotate(ref Vector3 rotation) { Rotate(rotation.X, rotation.Y, rotation.Z); } public void Rotate(Vector3 rotation) { Rotate(ref rotation); } public void SetLocalPosition(float? x, float? y, float? z) { _localPosition.X = x.HasValue ? x.Value : _localPosition.X; _localPosition.Y = y.HasValue ? y.Value : _localPosition.Y; _localPosition.Z = z.HasValue ? z.Value : _localPosition.Z; } public void SetLocalPosition(Vector3 position) { _localPosition.X = position.X; _localPosition.Y = position.Y; _localPosition.Z = position.Z; } public void SetLocalRotation(float? x, float? y, float? z) { _localRotation.X = x.HasValue ? x.Value : _localRotation.X; _localRotation.Y = y.HasValue ? y.Value : _localRotation.Y; _localRotation.Z = z.HasValue ? z.Value : _localRotation.Z; } public void SetLocalRotation(Matrix matrix) { var quaternion = Quaternion.CreateFromRotationMatrix(matrix); var rotation = quaternion.ToEuler(); SetLocalRotation(rotation.X, rotation.Y, rotation.Z); } public void SetLocalScale(float? x, float? y, float? z) { _localScale.X = x.HasValue ? x.Value : _localScale.X; _localScale.Y = y.HasValue ? y.Value : _localScale.Y; _localScale.Z = z.HasValue ? z.Value : _localScale.Z; } public override void Update() { if (_gameObject.IsStatic && !_dirty) return; UpdateWorldMatrix(); _dirty = false; } public void UpdateWorldMatrix() { _worldMatrix = Matrix.Identity; _worldMatrix *= Matrix.CreateScale(_localScale); _worldMatrix *= Matrix.CreateFromYawPitchRoll(_localRotation.Y, _localRotation.X, _localRotation.Z); _worldMatrix *= Matrix.CreateTranslation(_localPosition); if (_parent != null) _worldMatrix *= _parent._worldMatrix; } public Vector3 TransformVector(Vector3 direction) { UpdateWorldMatrix(); return Vector3.Transform(direction, _worldMatrix); } public override object Clone() { var tr = new Transform(); tr._parent = Parent; tr._root = _root; tr._gameObject = _gameObject; foreach (var t in _transforms) tr._transforms.Add(t); tr._localPosition = _localPosition; tr._localRotation = _localRotation; tr._localScale = _localScale; tr._dirty = true; return tr; } } }
29.056452
124
0.539134
[ "MIT" ]
demonixis/C3DE
C3DE/Components/Transform.cs
7,208
C#