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
namespace TextUml.Models { using System; public class DocumentRead : DocumentEdit { public int Id { get; set; } public bool Owned { get; set; } public bool Shared { get; set; } public bool Editable { get; set; } public DateTime? CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } } }
19.368421
48
0.570652
[ "MIT" ]
marufsiddiqui/textuml-dotnet
source/TextUml/Models/DocumentRead.cs
370
C#
// <copyright file="TokenEntity.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace ListSearch.Models { using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; /// <summary> /// Represents Token entity in storage. /// </summary> public class TokenEntity : TableEntity // TODO: remove this and change to key vault. { /// <summary> /// Gets or sets access token /// </summary> [JsonProperty("AccessToken")] public string AccessToken { get; set; } /// <summary> /// Gets or sets refresh token /// </summary> [JsonProperty("RefreshToken")] public string RefreshToken { get; set; } } }
27.962963
88
0.603974
[ "MIT" ]
OfficeDev/microsoft-teams-apps-list-search
Source/Microsoft.Teams.Apps.ListSearch/Models/TokenEntity.cs
757
C#
using XSharp; using static XSharp.XSRegisters; namespace Cosmos.IL2CPU.X86.IL { [OpCode(ILOpCode.Code.Dup)] public class Dup : ILOp { public Dup(XSharp.Assembler.Assembler aAsmblr) : base(aAsmblr) { } public override void Execute(Il2cpuMethodInfo aMethod, ILOpCode aOpCode) { var xStackContent = aOpCode.StackPopTypes[0]; var xStackContentSize = SizeOfType(xStackContent); var StackSize = (int)((xStackContentSize / 4) + (xStackContentSize % 4 == 0 ? 0 : 1)); for (int i = StackSize; i > 0; i--) { XS.Push(ESP, true, (StackSize - 1) * 4); //new CPUx86.Push { DestinationReg = CPUx86.RegistersEnum.ESP, DestinationIsIndirect = true, DestinationDisplacement = (int)((StackSize - 1) * 4) }; } } } }
29.233333
162
0.576967
[ "BSD-3-Clause" ]
xccoreco/IL2CPU
source/Cosmos.IL2CPU/IL/Dup.cs
877
C#
namespace OrchardCore.Email.Workflows.ViewModels { public class EmailTaskViewModel { public string AuthorExpression { get; set; } public string SenderExpression { get; set; } public string ReplyToExpression { get; set; } public string CcExpression { get; set; } public string BccExpression { get; set; } public string RecipientsExpression { get; set; } public string SubjectExpression { get; set; } public string Body { get; set; } public string BodyText { get; set; } public bool IsBodyHtml { get; set; } public bool IsBodyText { get; set; } } }
23.464286
56
0.624049
[ "BSD-3-Clause" ]
CityofSantaMonica/OrchardCore
src/OrchardCore.Modules/OrchardCore.Email/Workflows/ViewModels/EmailTaskViewModel.cs
657
C#
// <auto-generated /> using System; using Core.Database; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Core.Migrations { [DbContext(typeof(SqlServerContext))] [Migration("20200426215219_M2")] partial class M2 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.3") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Core.Models.Cart", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId") .IsUnique(); b.ToTable("Cart"); }); modelBuilder.Entity("Core.Models.CartItem", b => { b.Property<Guid>("CartId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("ProductId") .HasColumnType("uniqueidentifier"); b.Property<int>("Quantity") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.HasKey("CartId", "ProductId"); b.HasIndex("ProductId"); b.ToTable("CartItems"); }); modelBuilder.Entity("Core.Models.Category", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(50)") .HasMaxLength(50); b.HasKey("Id"); b.ToTable("Category"); }); modelBuilder.Entity("Core.Models.Order", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("OrderDate") .HasColumnType("datetime2"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Order"); }); modelBuilder.Entity("Core.Models.OrderItem", b => { b.Property<Guid>("OrderId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("ProductId") .HasColumnType("uniqueidentifier"); b.Property<int>("Quantity") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.HasKey("OrderId", "ProductId"); b.HasIndex("ProductId"); b.ToTable("OrderItems"); }); modelBuilder.Entity("Core.Models.Product", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("CategoryId") .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("ImagePath") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100); b.Property<double>("Price") .HasColumnType("float"); b.Property<string>("SpecificationFilePath") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.ToTable("Product"); }); modelBuilder.Entity("Core.Models.User", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(50)") .HasMaxLength(50); b.HasKey("Id"); b.ToTable("User"); }); modelBuilder.Entity("Core.Models.Cart", b => { b.HasOne("Core.Models.User", "User") .WithOne("Cart") .HasForeignKey("Core.Models.Cart", "UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Core.Models.CartItem", b => { b.HasOne("Core.Models.Cart", "Cart") .WithMany("CartItems") .HasForeignKey("CartId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Core.Models.Product", "Product") .WithMany("CartItems") .HasForeignKey("ProductId"); }); modelBuilder.Entity("Core.Models.Order", b => { b.HasOne("Core.Models.User", "User") .WithMany("Orders") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Core.Models.OrderItem", b => { b.HasOne("Core.Models.Order", "Order") .WithMany("OrderItems") .HasForeignKey("OrderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Core.Models.Product", "Product") .WithMany("OrderItems") .HasForeignKey("ProductId"); }); modelBuilder.Entity("Core.Models.Product", b => { b.HasOne("Core.Models.Category", null) .WithMany("Products") .HasForeignKey("CategoryId"); }); #pragma warning restore 612, 618 } } }
33.99115
117
0.432179
[ "MIT" ]
IP-Projects/E-Shop_Prototype
E-Shop_Prototype/Core/Migrations/20200426215219_M2.Designer.cs
7,684
C#
using System; using CryptoApisLibrary.DataTypes; using CryptoApisLibrary.ResponseTypes.Blockchains; namespace CryptoApisSnippets.Samples.Blockchains { partial class BlockchainSnippets { public void CreateConfirmedTransactionBtc() { var url = "http://www.mocky.io/v2/5b0d4b5f3100006e009d55f5"; var transactionHash = "9bba7c4a8121f4bf9819ea481f4abd5e501db40815e23a70dfcb9e99eb9ba05e"; var confirmationCount = 6; var manager = new CryptoManager(ApiKey); var response = manager.Blockchains.WebhookNotification. CreateConfirmedTransaction<CreateBtcConfirmedTransactionWebHookResponse>( NetworkCoin.BtcMainNet, url, transactionHash, confirmationCount); Console.WriteLine(string.IsNullOrEmpty(response.ErrorMessage) ? "CreateConfirmedTransactionBtc executed successfully, " + $"HookId is \"{response.Hook.Id}\"" : $"CreateConfirmedTransactionBtc error: {response.ErrorMessage}"); } } }
37.692308
95
0.752041
[ "MIT" ]
Crypto-APIs/.NET-Library
CryptoApisSnippets/Samples/Blockchains/WebhookNotifications/CreateConfirmedTransactionBtc.cs
982
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Effekseer.swig; using Effekseer.Utl; namespace Effekseer.GUI { class GUIManagerCallback : swig.GUIManagerCallback { void HandleAction() { } public override void Resized(int x, int y) { if(x > 0 && y > 0) { Manager.Native.ResizeWindow(x, y); Manager.WindowSize.X = x; Manager.WindowSize.Y = y; } Manager.resizedCount = 5; Manager.actualWidth = x; } public override void Focused() { Core.Reload(); } public override void Droped() { var path = GetPath(); var handle = false; Manager.Controls.Lock(); foreach (var c in Manager.Controls.Internal.OfType<Control>()) { c.DispatchDropped(path, ref handle); } Manager.Controls.Unlock(); if(!handle) { Commands.Open(this.GetPath()); } } public override bool Closing() { if (Manager.IgnoreDisposingDialogBox) return true; if (!Core.IsChanged) return true; var dialog = new Dialog.SaveOnDisposing( () => { Manager.IgnoreDisposingDialogBox = true; Manager.NativeManager.Close(); }); return false; } public override void Iconify(int f) { base.Iconify(f); } public override void DpiChanged(float f) { Manager.UpdateFont(); } public override bool ClickLink(string path) { try { System.Diagnostics.Process.Start(path); } catch { return false; } return true; } } public class Manager { class ManagerIOCallback : swig.IOCallback { public override void OnFileChanged(StaticFileType fileType, string path) { var ext = System.IO.Path.GetExtension(path).ToLower(); if(ext == ".efkmat") { Core.UpdateResourcePaths(path); Viewer.IsRequiredToReload = true; } } } public static swig.GUIManager NativeManager; public static swig.Native Native; public static swig.MainWindow MainWindow; public static swig.IO IO; static ManagerIOCallback ioCallback; static GUIManagerCallback guiManagerCallback; static int nextID = 10; static bool isFontSizeDirtied = true; public static Viewer Viewer; internal static Network Network; internal static swig.Vec2 WindowSize = new swig.Vec2(1280, 720); internal static bool DoesChangeColorOnChangedValue = true; public static float TextOffsetY {get; private set;} public static float DpiScale { get { return NativeManager.GetDpiScale(); } } public static bool IsWindowFrameless { get; private set; } static int resetCount = 0; internal static int resizedCount = 0; internal static int actualWidth = 1; /// <summary> /// if this flag is true, a dialog box on disposing is not shown /// </summary> internal static bool IgnoreDisposingDialogBox = false; /// <summary> /// /// </summary> /// <remarks> /// This order is important for dock panel. /// </remarks> static Type[] dockTypes = { typeof(Dock.ViewerController), typeof(Dock.NodeTreeView), typeof(Dock.CommonValues), typeof(Dock.LocationValues), typeof(Dock.LocationAbsValues), typeof(Dock.GenerationLocationValues), typeof(Dock.RotationValues), typeof(Dock.ScaleValues), typeof(Dock.DepthValues), typeof(Dock.RendererCommonValues), typeof(Dock.RendererValues), typeof(Dock.SoundValues), typeof(Dock.FCurves), typeof(Dock.ViewPoint), typeof(Dock.Recorder), typeof(Dock.Option), typeof(Dock.Environement), typeof(Dock.GlobalValues), typeof(Dock.BehaviorValues), typeof(Dock.Culling), typeof(Dock.Network), typeof(Dock.FileViewer), typeof(Dock.Dynamic), typeof(Dock.AdvancedRenderCommonValues), typeof(Dock.AdvancedRenderCommonValues2), }; static Dock.DockManager dockManager = null; static Dock.EffectViwer effectViewer = null; static Dock.DockPanel[] panels = new Dock.DockPanel[0]; public static bool IsDockMode() { return dockManager != null; } internal static Utils.DelayedList<IRemovableControl> Controls = new Utils.DelayedList<IRemovableControl>(); public static bool Initialize(int width, int height, swig.DeviceType deviceType) { var appDirectory = Manager.GetEntryDirectory(); swig.MainWindowState state = new swig.MainWindowState(); if (System.Environment.OSVersion.Platform == PlatformID.Win32NT) { IsWindowFrameless = true; } // TODO : refactor var windowConfig = new Configs.WindowConfig(); if(windowConfig.Load(System.IO.Path.Combine(appDirectory, "config.Dock.xml"))) { state.PosX = windowConfig.WindowPosX; state.PosY = windowConfig.WindowPosY; state.Width = windowConfig.WindowWidth; state.Height = windowConfig.WindowHeight; state.IsMaximumMode = windowConfig.WindowIsMaximumMode; } else { state.PosX = -10000; // nodata state.Width = 1280; state.Height = 720; windowConfig = null; } state.IsFrameless = IsWindowFrameless; if (!swig.MainWindow.Initialize("Effekseer", state, false, deviceType == swig.DeviceType.OpenGL)) { return false; } MainWindow = swig.MainWindow.GetInstance(); swig.IO.Initialize(1000); IO = swig.IO.GetInstance(); ioCallback = new ManagerIOCallback(); IO.AddCallback(ioCallback); Core.OnFileLoaded += (string path) => { #if DEBUG Console.WriteLine("OnFileLoaded : " + path); #endif var f = IO.LoadIPCFile(path); if(f == null) { f = IO.LoadFile(path); } // TODO : refactor it // Permission error if(f != null && f.GetSize() == 0) { var message = MultiLanguageTextProvider.GetText("PermissionError_File"); if (swig.GUIManager.IsMacOSX()) { message += "\n"; message += MultiLanguageTextProvider.GetText("PermissionError_File_Mac"); } message = string.Format(message, System.IO.Path.GetFileName(path)); throw new FileLoadPermissionException(message); } if (f == null) return null; byte[] ret = new byte[f.GetSize()]; System.Runtime.InteropServices.Marshal.Copy(f.GetData(), ret, 0, ret.Length); f.Dispose(); return ret; }; ThumbnailManager.Initialize(); var mgr = new swig.GUIManager(); if (mgr.Initialize(MainWindow, deviceType)) { } else { mgr.Dispose(); mgr = null; return false; } Native = new swig.Native(); Viewer = new Viewer(Native); if (!Viewer.ShowViewer(mgr.GetNativeHandle(), state.Width, state.Height, deviceType)) { mgr.Dispose(); mgr = null; return false; } mgr.InitializeGUI(Native); NativeManager = mgr; Images.Load(GUI.Manager.Native); guiManagerCallback = new GUIManagerCallback(); NativeManager.SetCallback(guiManagerCallback); panels = new Dock.DockPanel[dockTypes.Length]; // Load font UpdateFont(); // Load window icon NativeManager.SetWindowIcon(System.IO.Path.Combine(appDirectory, "resources/icon.png")); // Load config RecentFiles.LoadRecentConfig(); Shortcuts.LoadShortcuts(); Commands.Register(); // Add controls var mainMenu = new GUI.Menu.MainMenu(); GUI.Manager.AddControl(mainMenu); dockManager = new GUI.Dock.DockManager(); GUI.Manager.AddControl(dockManager); // Default effectViewer = new Dock.EffectViwer(); if (dockManager != null) { dockManager.Controls.Add(effectViewer); } else { AddControl(effectViewer); } if (LoadWindowConfig(System.IO.Path.Combine(appDirectory, "config.Dock.xml"))) { } else { ResetWindow(); } TextOffsetY = (NativeManager.GetTextLineHeightWithSpacing() - NativeManager.GetTextLineHeight()) / 2; Network = new Network(Native); Network.Load(); Command.CommandManager.Changed += OnChanged; Core.EffectBehavior.Location.X.OnChanged += OnChanged; Core.EffectBehavior.Location.Y.OnChanged += OnChanged; Core.EffectBehavior.Location.Z.OnChanged += OnChanged; Core.EffectBehavior.Rotation.X.OnChanged += OnChanged; Core.EffectBehavior.Rotation.Y.OnChanged += OnChanged; Core.EffectBehavior.Rotation.Z.OnChanged += OnChanged; Core.EffectBehavior.Scale.X.OnChanged += OnChanged; Core.EffectBehavior.Scale.Y.OnChanged += OnChanged; Core.EffectBehavior.Scale.Z.OnChanged += OnChanged; Core.EffectBehavior.LocationVelocity.X.OnChanged += OnChanged; Core.EffectBehavior.LocationVelocity.Y.OnChanged += OnChanged; Core.EffectBehavior.LocationVelocity.Z.OnChanged += OnChanged; Core.EffectBehavior.RotationVelocity.X.OnChanged += OnChanged; Core.EffectBehavior.RotationVelocity.Y.OnChanged += OnChanged; Core.EffectBehavior.RotationVelocity.Z.OnChanged += OnChanged; Core.EffectBehavior.ScaleVelocity.X.OnChanged += OnChanged; Core.EffectBehavior.ScaleVelocity.Y.OnChanged += OnChanged; Core.EffectBehavior.ScaleVelocity.Z.OnChanged += OnChanged; Core.EffectBehavior.RemovedTime.Infinite.OnChanged += OnChanged; Core.EffectBehavior.RemovedTime.Value.OnChanged += OnChanged; Core.EffectBehavior.TargetLocation.X.OnChanged += OnChanged; Core.EffectBehavior.TargetLocation.Y.OnChanged += OnChanged; Core.EffectBehavior.TargetLocation.Z.OnChanged += OnChanged; Core.EffectBehavior.CountX.OnChanged += OnChanged; Core.EffectBehavior.CountY.OnChanged += OnChanged; Core.EffectBehavior.CountZ.OnChanged += OnChanged; Core.EffectBehavior.Distance.OnChanged += OnChanged; Core.EffectBehavior.TimeSpan.OnChanged += OnChanged; Core.EffectBehavior.ColorAll.R.OnChanged += OnChanged; Core.EffectBehavior.ColorAll.G.OnChanged += OnChanged; Core.EffectBehavior.ColorAll.B.OnChanged += OnChanged; Core.EffectBehavior.ColorAll.A.OnChanged += OnChanged; Core.EffectBehavior.PlaybackSpeed.OnChanged += OnChanged; Core.Option.Magnification.OnChanged += OnChanged; Core.Option.IsGridShown.OnChanged += OnChanged; Core.Option.GridLength.OnChanged += OnChanged; Core.Option.GridColor.R.OnChanged += OnChanged; Core.Option.GridColor.G.OnChanged += OnChanged; Core.Option.GridColor.B.OnChanged += OnChanged; Core.Option.GridColor.A.OnChanged += OnChanged; Core.Option.FPS.OnChanged += OnChanged; Core.Option.DistortionType.OnChanged += OnChanged; Core.Option.Coordinate.OnChanged += OnChanged; Core.Environment.Background.BackgroundColor.R.OnChanged += OnChanged; Core.Environment.Background.BackgroundColor.G.OnChanged += OnChanged; Core.Environment.Background.BackgroundColor.B.OnChanged += OnChanged; Core.Environment.Background.BackgroundColor.A.OnChanged += OnChanged; Core.Environment.Background.BackgroundImage.OnChanged += OnChanged; Core.Culling.IsShown.OnChanged += OnChanged; Core.Culling.Type.OnChanged += OnChanged; Core.Culling.Sphere.Location.X.OnChanged += OnChanged; Core.Culling.Sphere.Location.Y.OnChanged += OnChanged; Core.Culling.Sphere.Location.Z.OnChanged += OnChanged; Core.Culling.Sphere.Radius.OnChanged += OnChanged; Core.OnAfterLoad += new EventHandler(Core_OnAfterLoad); Core.OnAfterNew += new EventHandler(Core_OnAfterNew); Core.OnReload += new EventHandler(Core_OnReload); // Set imgui path var entryDirectory = GetEntryDirectory(); swig.GUIManager.SetIniFilename(entryDirectory + "/imgui.ini"); // check files if(!System.IO.File.Exists(System.IO.Path.Combine(appDirectory, "resources/fonts/GenShinGothic-Monospace-Bold.ttf"))) { ErrorUtils.ThrowFileNotfound(); } if (!System.IO.File.Exists(System.IO.Path.Combine(appDirectory, "resources/icons/MenuIcons.png"))) { ErrorUtils.ThrowFileNotfound(); } return true; } public static void Terminate() { var entryDirectory = GetEntryDirectory(); System.IO.Directory.SetCurrentDirectory(entryDirectory); SaveWindowConfig(entryDirectory + "/config.Dock.xml"); foreach (var p in panels) { if(p != null) { p.DispatchDisposed(); } } if (effectViewer != null) { effectViewer.DispatchDisposed(); } Network.Save(); Shortcuts.SeveShortcuts(); RecentFiles.SaveRecentConfig(); Viewer.HideViewer(); NativeManager.SetCallback(null); NativeManager.Terminate(); Images.Unload(); swig.MainWindow.Terminate(); MainWindow.Dispose(); MainWindow = null; ThumbnailManager.Terminate(); swig.IO.Terminate(); IO.Dispose(); IO = null; } public static void UpdateFont() { isFontSizeDirtied = true; } public static void AddControl(IRemovableControl control) { Controls.Add(control); } static swig.Vec2 mousePos_pre; static bool isFirstUpdate = true; protected static int LEFT_SHIFT = 340; protected static int RIGHT_SHIFT = 344; protected static int LEFT_CONTROL = 341; protected static int RIGHT_CONTROL = 345; protected static int LEFT_ALT = 342; protected static int RIGHT_ALT = 346; protected static int LEFT_SUPER = 343; protected static int RIGHT_SUPER = 347; struct ViewportControllerResult { public bool Rotate; public bool Slide; public bool Zoom; } static ViewportControllerResult ControllViewport() { bool isLeftPressed = NativeManager.GetMouseButton(0) > 0; bool isRightPressed = NativeManager.GetMouseButton(1) > 0; bool isWheelPressed = NativeManager.GetMouseButton(2) > 0; bool isShiftPressed = Manager.NativeManager.IsKeyDown(LEFT_SHIFT) || Manager.NativeManager.IsKeyDown(RIGHT_SHIFT); bool isCtrlPressed = Manager.NativeManager.IsKeyDown(LEFT_CONTROL) || Manager.NativeManager.IsKeyDown(RIGHT_CONTROL); bool isAltPressed = Manager.NativeManager.IsKeyDown(LEFT_ALT) || Manager.NativeManager.IsKeyDown(RIGHT_ALT); bool isSuperPressed = Manager.NativeManager.IsKeyDown(LEFT_SUPER) || Manager.NativeManager.IsKeyDown(RIGHT_SUPER); bool isSlidePressed = false; bool isZoomPressed = false; bool isRotatePressed = false; switch (Core.Option.MouseMappingType.Value) { case Data.MouseMappingType.Effekseer: isSlidePressed = isWheelPressed || (isRightPressed && isShiftPressed); isZoomPressed = isRightPressed && isCtrlPressed; isRotatePressed = isRightPressed; break; case Data.MouseMappingType.Blender: isSlidePressed = isWheelPressed && isShiftPressed; isZoomPressed = isWheelPressed && isCtrlPressed; isRotatePressed = isWheelPressed; break; case Data.MouseMappingType.Maya: isSlidePressed = isWheelPressed && isAltPressed; isZoomPressed = isRightPressed && isAltPressed; isRotatePressed = isLeftPressed && isAltPressed; break; case Data.MouseMappingType.Unity: isSlidePressed = isRightPressed; isZoomPressed = false; isRotatePressed = isWheelPressed; break; } ViewportControllerResult result; result.Rotate = isRotatePressed; result.Zoom = isZoomPressed; result.Slide = isSlidePressed; return result; } public static void Update() { if (isFontSizeDirtied) { NativeManager.InvalidateFont(); var appDirectory = Manager.GetEntryDirectory(); var type = Core.Option.Font.Value; NativeManager.ClearAllFonts(); if (type == Data.FontType.Normal) { NativeManager.AddFontFromFileTTF(System.IO.Path.Combine(appDirectory, MultiLanguageTextProvider.GetText("Font_Normal")), Core.Option.FontSize.Value); } else if (type == Data.FontType.Bold) { NativeManager.AddFontFromFileTTF(System.IO.Path.Combine(appDirectory, MultiLanguageTextProvider.GetText("Font_Bold")), Core.Option.FontSize.Value); } NativeManager.AddFontFromAtlasImage(System.IO.Path.Combine(appDirectory, "resources/icons/MenuIcons.png"), 0xec00, 24, 24, 16, 16); isFontSizeDirtied = false; } // Reset IO.Update(); Shortcuts.Update(); Network.Update(); var handle = false; if(!handle) { if (!NativeManager.IsAnyItemActive()) { Shortcuts.ProcessCmdKey(ref handle); } } var mousePos = NativeManager.GetMousePosition(); if (isFirstUpdate) { mousePos_pre = mousePos; } if((effectViewer == null && !NativeManager.IsAnyWindowHovered()) || (effectViewer != null && effectViewer.IsHovered)) { var result = ControllViewport(); if (result.Slide) { var dx = mousePos.X - mousePos_pre.X; var dy = mousePos.Y - mousePos_pre.Y; if (Core.Option.ViewerMode.Value == Data.OptionValues.ViewMode._3D) { Viewer.Slide(dx / 30.0f, dy / 30.0f); } else if (Core.Option.ViewerMode.Value == Data.OptionValues.ViewMode._2D) { Viewer.Slide(dx / 16.0f, dy / 16.0f); } } else if (NativeManager.GetMouseWheel() != 0) { Viewer.Zoom(NativeManager.GetMouseWheel()); } else if (result.Zoom) { var dx = mousePos.X - mousePos_pre.X; var dy = mousePos.Y - mousePos_pre.Y; Viewer.Zoom(-dy * 0.25f); } else if (result.Rotate) { var dx = mousePos.X - mousePos_pre.X; var dy = mousePos.Y - mousePos_pre.Y; if (Core.Option.ViewerMode.Value == Data.OptionValues.ViewMode._3D) { Viewer.Rotate(dx, dy); } else if (Core.Option.ViewerMode.Value == Data.OptionValues.ViewMode._2D) { Viewer.Slide(dx / 16.0f, dy / 16.0f); } } } mousePos_pre = mousePos; Viewer.UpdateViewer(); Native.UpdateWindow(); Native.ClearWindow(50, 50, 50, 0); //if(effectViewer == null) //{ // Native.RenderWindow(); //} NativeManager.ResetGUI(); if (resetCount < 0) { resetCount++; if (resetCount == 0) { ResetWindowActually(); } } if(resizedCount > 0) { resizedCount--; } Controls.Lock(); foreach (var c in Controls.Internal) { c.Update(); } foreach(var _ in Controls.Internal) { if (!_.ShouldBeRemoved) continue; var dp = _ as Dock.DockPanel; if(dp != null) { dp.DispatchDisposed(); } } foreach (var _ in Controls.Internal) { if (!_.ShouldBeRemoved) continue; Controls.Remove(_); } Controls.Unlock(); for (int i = 0; i < dockTypes.Length; i++) { if (panels[i] != null && panels[i].ShouldBeRemoved) { panels[i] = null; } } NativeManager.RenderGUI(resizedCount == 0); Native.Present(); NativeManager.Present(); isFirstUpdate = false; // TODO more smart // When minimized, suppress CPU activity if (actualWidth == 0) { System.Threading.Thread.Sleep(16); } } public static void ResetWindow() { effectViewer?.Close(); effectViewer = null; for (int i = 0; i < panels.Length; i++) { panels[i]?.Close(); } resetCount = -5; } static void ResetWindowActually() { if (effectViewer == null) { effectViewer = new Dock.EffectViwer(); if (dockManager != null) { dockManager.Controls.Add(effectViewer); } } var viewerController = SelectOrShowWindow(typeof(Dock.ViewerController), null); var nodeTreeView = SelectOrShowWindow(typeof(Dock.NodeTreeView), null); var commonValues = SelectOrShowWindow(typeof(Dock.CommonValues), null); var locationValues = SelectOrShowWindow(typeof(Dock.LocationValues), null); var rotationValues = SelectOrShowWindow(typeof(Dock.RotationValues), null); var scaleValues = SelectOrShowWindow(typeof(Dock.ScaleValues), null); var rendererCommonValues = SelectOrShowWindow(typeof(Dock.RendererCommonValues), null); var rendererValues = SelectOrShowWindow(typeof(Dock.RendererValues), null); uint windowId = NativeManager.BeginDockLayout(); uint dockLeftID = 0, dockRightID = 0; NativeManager.DockSplitNode(windowId, DockSplitDir.Left, 0.65f, ref dockLeftID, ref dockRightID); uint dockLeftTop = 0, dockLeftBottom = 0; NativeManager.DockSplitNode(dockLeftID, DockSplitDir.Top, 0.85f, ref dockLeftTop, ref dockLeftBottom); uint dockRightTop = 0, dockRightBottom = 0; NativeManager.DockSplitNode(dockRightID, DockSplitDir.Top, 0.6f, ref dockRightTop, ref dockRightBottom); NativeManager.DockSetNodeFlags(dockLeftTop, DockNodeFlags.HiddenTabBar); NativeManager.DockSetNodeFlags(dockLeftBottom, DockNodeFlags.HiddenTabBar); NativeManager.DockSetWindow(dockLeftTop, effectViewer.WindowID); NativeManager.DockSetWindow(dockLeftBottom, viewerController.WindowID); NativeManager.DockSetWindow(dockRightTop, commonValues.WindowID); NativeManager.DockSetWindow(dockRightTop, locationValues.WindowID); NativeManager.DockSetWindow(dockRightTop, rotationValues.WindowID); NativeManager.DockSetWindow(dockRightTop, scaleValues.WindowID); NativeManager.DockSetWindow(dockRightTop, rendererValues.WindowID); NativeManager.DockSetWindow(dockRightTop, rendererCommonValues.WindowID); NativeManager.DockSetWindow(dockRightBottom, nodeTreeView.WindowID); NativeManager.EndDockLayout(); } internal static Dock.DockPanel GetWindow(Type t) { foreach(var panel in panels) { if (panel != null && panel.GetType() == t) return panel; } return null; } internal static Dock.DockPanel SelectOrShowWindow(Type t, swig.Vec2 defaultSize = null, bool resetRect = false) { for(int i = 0; i < dockTypes.Length; i++) { if (dockTypes[i] != t) continue; if (panels[i] != null) { panels[i].SetFocus(); return panels[i]; } else { if(defaultSize == null) { defaultSize = new swig.Vec2(); } panels[i] = (Dock.DockPanel)t.GetConstructor(Type.EmptyTypes).Invoke(null); panels[i].InitialDockSize = defaultSize; panels[i].IsInitialized = -1; panels[i].ResetSize = resetRect; if (dockManager != null) { dockManager.Controls.Add(panels[i]); } else { AddControl(panels[i]); } return panels[i]; } } return null; } /// <summary> /// get a scale based on font size for margin, etc. /// </summary> /// <returns></returns> public static float GetUIScaleBasedOnFontSize() { return Core.Option.FontSize.Value / 16.0f * DpiScale; } static void Core_OnAfterLoad(object sender, EventArgs e) { Viewer.StopViewer(); if (Network.SendOnLoad) { Network.Send(); } } static void Core_OnAfterNew(object sender, EventArgs e) { Viewer.StopViewer(); } static void Core_OnReload(object sender, EventArgs e) { Viewer.Reload(true); } static void OnChanged(object sender, EventArgs e) { Viewer.IsChanged = true; if (Network.SendOnEdit) { Network.Send(); } } /// <summary> /// TODO refactor /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool LoadWindowConfig(string path) { if (!System.IO.File.Exists(path)) return false; try { var doc = new System.Xml.XmlDocument(); doc.Load(path); if (doc.ChildNodes.Count != 2) return false; if (doc.ChildNodes[1].Name != "Root") return false; var windowWidth = doc["Root"]["WindowWidth"]?.GetTextAsInt() ?? 1280; var windowHeight = doc["Root"]["WindowHeight"]?.GetTextAsInt() ?? 720; var docks = doc["Root"]["Docks"]; if (docks != null) { for (int i = 0; i < docks.ChildNodes.Count; i++) { var panel = docks.ChildNodes[i]; var type = dockTypes.FirstOrDefault(_ => _.ToString() == panel.Name); if (type != null) { SelectOrShowWindow(type); } } } } catch { return false; } return true; } /// <summary> /// TODO refactor /// </summary> /// <param name="path"></param> public static void SaveWindowConfig(string path) { var size = Manager.NativeManager.GetSize(); var state = MainWindow.GetState(); if (state.Width <= 0 || state.Height <= 0) return; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement project_root = doc.CreateElement("Root"); project_root.AppendChild(doc.CreateTextElement("WindowWidth", state.Width.ToString())); project_root.AppendChild(doc.CreateTextElement("WindowHeight", state.Height.ToString())); project_root.AppendChild(doc.CreateTextElement("WindowPosX", state.PosX.ToString())); project_root.AppendChild(doc.CreateTextElement("WindowPosY", state.PosY.ToString())); project_root.AppendChild(doc.CreateTextElement("WindowIsMaximumMode", state.IsMaximumMode ? "1" : "0")); System.Xml.XmlElement docks = doc.CreateElement("Docks"); foreach(var panel in panels) { if(panel != null) { docks.AppendChild(doc.CreateTextElement(panel.GetType().ToString(), "Open")); } } project_root.AppendChild(docks); doc.AppendChild(project_root); var dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(dec, project_root); doc.Save(path); } /// <summary> /// Get unique id in this aplication. /// </summary> /// <returns></returns> public static int GetUniqueID() { nextID++; return nextID; } /// <summary> /// Get a directory where this application is located. /// </summary> /// <returns></returns> public static string GetEntryDirectory() { var myAssembly = System.Reflection.Assembly.GetEntryAssembly(); string path = myAssembly.Location; var dir = System.IO.Path.GetDirectoryName(path); // for mkbundle if (dir == string.Empty) { dir = System.IO.Path.GetDirectoryName( System.IO.Path.GetFullPath( Environment.GetCommandLineArgs()[0])); } return dir; } } }
25.562124
154
0.686919
[ "Apache-2.0", "BSD-3-Clause" ]
NumAniCloud/Effekseer
Dev/Editor/Effekseer/GUI/Manager.cs
25,511
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Iotcloud.V20180614.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class MultiDevicesInfo : AbstractModel { /// <summary> /// 设备名 /// </summary> [JsonProperty("DeviceName")] public string DeviceName{ get; set; } /// <summary> /// 对称加密密钥,base64 编码,采用对称加密时返回该参数 /// </summary> [JsonProperty("DevicePsk")] public string DevicePsk{ get; set; } /// <summary> /// 设备证书,采用非对称加密时返回该参数 /// </summary> [JsonProperty("DeviceCert")] public string DeviceCert{ get; set; } /// <summary> /// 设备私钥,采用非对称加密时返回该参数,腾讯云为用户缓存起来,其生命周期与任务生命周期一致 /// </summary> [JsonProperty("DevicePrivateKey")] public string DevicePrivateKey{ get; set; } /// <summary> /// 错误码 /// </summary> [JsonProperty("Result")] public ulong? Result{ get; set; } /// <summary> /// 错误信息 /// </summary> [JsonProperty("ErrMsg")] public string ErrMsg{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "DeviceName", this.DeviceName); this.SetParamSimple(map, prefix + "DevicePsk", this.DevicePsk); this.SetParamSimple(map, prefix + "DeviceCert", this.DeviceCert); this.SetParamSimple(map, prefix + "DevicePrivateKey", this.DevicePrivateKey); this.SetParamSimple(map, prefix + "Result", this.Result); this.SetParamSimple(map, prefix + "ErrMsg", this.ErrMsg); } } }
31.063291
89
0.605949
[ "Apache-2.0" ]
Darkfaker/tencentcloud-sdk-dotnet
TencentCloud/Iotcloud/V20180614/Models/MultiDevicesInfo.cs
2,664
C#
using Models.Contracts; using Services.Services; using Services.Services.Contracts; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using Tournaments.Contracts; using Tournaments.Models; namespace Tournaments.Services { public class SponsorService : ISponsorService { private readonly ITournamentsRepository<Sponsor> sponsorRepository; public SponsorService(ITournamentsRepository<Sponsor> sponsorRepository) { this.sponsorRepository = sponsorRepository; } public IEnumerable<Sponsor> GetSponsors() { return this.sponsorRepository.All(); } public IEnumerable<Sponsor> GetSponsorById(int id) { if (id < 0) { throw new ArgumentException("Invalid id"); } return this.sponsorRepository.All().Where(t => t.Id == id).ToList(); // TODO TO LIST? } //public IEnumerable<Tournament> GetSponsoredTournaments(int tournamentId) //{ // if (tournamentId < 0) // { // throw new ArgumentException("Invalid tournamentId"); // } // return this.sponsorRepository.Tournaments.Where(t=>t.id).ToList(); //} //public IEnumerable<Team> GetSponsoredTeams(int teamId) //{ // if (teamId < 0) // { // throw new ArgumentException("Invalid teamId"); // } // return this.sponsorRepository.Teams.Where(t=>t.id).ToList(); //} public int UpdateSponsor(Sponsor sponsor) { if (sponsor == null) { throw new ArgumentException("Sponsor cannot be null."); } this.sponsorRepository.Update(sponsor); return 1; } public int InsertSponsor(Sponsor sponsor) { if (sponsor == null) { throw new ArgumentException("Sponsor cannot be null."); } this.sponsorRepository.Add(sponsor); return 1; } public int DeleteSponsor(int sponsorId) { if (sponsorId < 0) { throw new ArgumentException("Invalid sponsorId"); } Sponsor sponsor = this.sponsorRepository.GetById(sponsorId); this.sponsorRepository.Delete(sponsor); return 1; } public IEnumerable<Sponsor> GetAllSponsorsSortedById() { return this.sponsorRepository.All(); // TODO OrderBy<Team>(t=>t.Id); } //public int AddSponsoredTeam(Team team) //team id //{ // if (team == null) // { // throw new ArgumentException("Team cannot be null."); // } // this.sponsorRepository.Teams.Add(team); //return 1; //} //public int AddSponsoredTournament(Tournament tournament) //tournament name //{ // if (tournament == null) // { // throw new ArgumentException("Tournament cannot be null."); // } // this.sponsorRepository.Tournaments.Add(tournament); //return 1; //} } }
27.865546
97
0.547045
[ "MIT" ]
kalostoykov/Tournaments
Services/Services/SponsorService.cs
3,318
C#
namespace CSharpWebServer.Server.Controllers { using System; using CSharpWebServer.Server.Http; [AttributeUsage(AttributeTargets.Method)] public abstract class HttpMethodAttribute : Attribute { public HttpMethod HttpMethod { get; } protected HttpMethodAttribute(HttpMethod method) => this.HttpMethod = method; } }
24.6
57
0.699187
[ "MIT" ]
Berat-Dzhevdetov/CSharp-Web-Server
CSharpWebServer/CSharpWebServer.Server/Controllers/HttpMethodAttribute.cs
371
C#
using System.Threading; using System.Threading.Tasks; using CompanyName.MyMeetings.Modules.Meetings.Application.Configuration.Commands; using CompanyName.MyMeetings.Modules.Meetings.Domain.MeetingGroups; using MediatR; namespace CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroups.SetMeetingGroupExpirationDate { internal class SetMeetingGroupExpirationDateCommandHandler : ICommandHandler<SetMeetingGroupExpirationDateCommand> { private readonly IMeetingGroupRepository _meetingGroupRepository; internal SetMeetingGroupExpirationDateCommandHandler(IMeetingGroupRepository meetingGroupRepository) { _meetingGroupRepository = meetingGroupRepository; } public async Task<Unit> Handle(SetMeetingGroupExpirationDateCommand request, CancellationToken cancellationToken) { var meetingGroup = await _meetingGroupRepository.GetByIdAsync(new MeetingGroupId(request.MeetingGroupId)); meetingGroup.SetExpirationDate(request.DateTo); return Unit.Value; } } }
40.074074
121
0.784658
[ "MIT" ]
Ahmetcanb/modular-monolith-with-ddd
src/Modules/Meetings/Application/MeetingGroups/SetMeetingGroupExpirationDate/SetMeetingGroupExpirationDateCommandHandler.cs
1,084
C#
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // ┃ FILE: ValueConverters.cs // ┃ PROJECT: Utility.WPF // ┃ SOLUTION: Utility.NET // ┃ CREATED: 2015-12-25 @ 1:05 AM // ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // ┃ AUTHOR: Jonathan Ruisi // ┃ EMAIL: JonathanRuisi@gmail.com // ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // ┃ GIT REPO: https://github.com/jonathanruisi/Utility.NET // ┃ LICENSE: https://github.com/jonathanruisi/Utility.NET/blob/master/LICENSE // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ using System; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Data; using System.Windows.Media; using JLR.Utility.NETFramework; using JLR.Utility.NETFramework.Color; namespace JLR.Utility.WPF { #region Boolean Converters public class NullToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value != null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } public class PositiveIntegerToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value is int && (int)value >= 1; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value is bool && (bool)value ? 1 : 0; } } public class IntegerRangeToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is int)) throw new ArgumentException("Value must be an integer", nameof(value)); if (!(parameter is DiscreteRange<int>)) throw new ArgumentException("Parameter must be a Range<int>", nameof(value)); var intValue = (int)value; var intRange = (DiscreteRange<int>)parameter; return intValue >= intRange.Minimum && intValue <= intRange.Maximum; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } public class EnumToBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(parameter); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(true) ? parameter : Binding.DoNothing; } } public class BoolNegationConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool) return !(bool)value; throw new ArgumentException("Value must be bool", nameof(value)); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool) return !(bool)value; throw new ArgumentException("Value must be bool", nameof(value)); } } public class BooleanMultiConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { return values.OfType<bool>().All(value => value); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } #endregion #region Numeric Converters public class NumericInverseConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { dynamic n = value; return 1M / n; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { dynamic n = value; return 1M / n; } } #endregion #region Text Converters public class PercentageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is double val) return val * 100.0; throw new ArgumentException("Expected a double precision floating point value"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string valueString) { if (valueString.Contains("%")) valueString = valueString.Remove(valueString.IndexOf('%'), 1); if (double.TryParse(valueString, out var result)) return result / 100.0; } throw new ArgumentException("Expected a string containing a double precision floating point value"); } } public class DegreeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is double) return value; throw new ArgumentException("Expected a double precision floating point value"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string valueString) { if (valueString.Contains("°")) valueString = valueString.Remove(valueString.IndexOf('°'), 1); if (double.TryParse(valueString, out var result)) return result; } throw new ArgumentException("Expected a string containing a double precision floating point value"); } } #endregion #region Visibility Converters public class NullToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var visibility = parameter as Visibility? ?? Visibility.Collapsed; return value == null ? visibility : Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } public class BoolToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var visibility = parameter as Visibility? ?? Visibility.Collapsed; return (bool)value ? Visibility.Visible : visibility; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } public class BoolToVisibilityMultiConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var visibility = parameter as Visibility? ?? Visibility.Collapsed; return values.OfType<bool>().All(value => value) ? Visibility.Visible : visibility; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } public class IntegerToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int) { if (parameter is string) { var args = (parameter as string).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (args.Length != 3) throw new ArgumentException( "Invalid parameter string (must contain three comma separated arguments", nameof(parameter)); var number = Int32.Parse(args[1]); if (args[2].ToUpper() != "HIDDEN" && args[2].ToUpper() != "COLLAPSED") throw new ArgumentException("Unrecognized visibility state", nameof(parameter)); switch (args[0]) { case "=": if ((int)value == number) return Visibility.Visible; break; case "!=": if ((int)value != number) return Visibility.Visible; break; case "<": if ((int)value < number) return Visibility.Visible; break; case ">": if ((int)value > number) return Visibility.Visible; break; case "<=": if ((int)value <= number) return Visibility.Visible; break; case ">=": if ((int)value >= number) return Visibility.Visible; break; default: throw new ArgumentException("Unrecognized comparison argument", nameof(parameter)); } return args[2] == "HIDDEN" ? Visibility.Hidden : Visibility.Collapsed; } return (int)value > 0; } throw new ArgumentException("Value must be an integer", nameof(value)); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } #endregion #region ColorSpace Converters public class ColorSpaceToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var colorSpaceString = value as string; if (colorSpaceString != null) return colorSpaceString == "CMYK" || colorSpaceString == "RGBA" ? Visibility.Visible : Visibility.Collapsed; throw new ArgumentException("Expected a string value"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } public class ColorSpaceToVisibilityMultiConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var colorSpaceString = values[0] as string; if (colorSpaceString != null && values[1] is bool) { var isChecked = (bool)values[1]; return (colorSpaceString == "CMYK" || colorSpaceString == "RGBA") && isChecked ? Visibility.Visible : Visibility.Collapsed; } throw new ArgumentException("Expected a string value and a bool value"); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } public class ColorSpaceToSolidColorBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is ColorSpace colorSpace) return new SolidColorBrush(colorSpace.ToSystemWindowsMediaColor()); if (value is string str) return new SolidColorBrush(ColorSpace.Parse(str).ToSystemWindowsMediaColor()); throw new ArgumentException("Unable to convert specified object to SolidColorBrush"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is SolidColorBrush brush) { var result = brush.Color.ToColorSpaceRgba(); if (targetType == typeof(string)) return result.ToString(); return result; } throw new ArgumentException("Unable to convert specified object to ColorSpace"); } } public class ColorSpaceToOverlaySolidColorBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ColorSpace colorSpace; switch (value) { case ColorSpace cs: colorSpace = cs; break; case string str: colorSpace = ColorSpace.Parse(str); break; default: throw new ArgumentException("Unable to convert specified object to SolidColorBrush"); } return new SolidColorBrush(colorSpace.GetAutoDarkenOrLighten().ToSystemWindowsMediaColor()); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new InvalidOperationException(); } } #endregion }
31.295699
112
0.694039
[ "MIT" ]
jonathanruisi/Utility.NET
Utility.WPF/ValueConverters.cs
12,462
C#
using FallballConnectorDotNet.Models; using FallballConnectorDotNet.Models.Aps; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace FallballConnectorDotNet.Controllers { [Produces("application/json")] [Route("/connector/tenant")] public class TenantController : Controller { private readonly Setting _setting; public TenantController(ILogger<TenantController> logger, IConfiguration config) { _setting = new Setting { Logger = logger, Config = config }; } [HttpPost] public IActionResult Create([FromBody] OaTenant oaTenant) { if (oaTenant == null) return BadRequest(); // Call Models var tenantId = Tenant.Create(_setting, Request, oaTenant); return CreatedAtRoute( "Root", null, new {tenantId} ); } [HttpPut("{id}")] public IActionResult Update(string id, [FromBody] OaTenant oaTenant) { if (oaTenant == null) return BadRequest(); Tenant.Update(_setting, Request, oaTenant); return Ok(); } [HttpDelete("{id}")] public IActionResult Delete(string id) { if (id == null) return BadRequest(); Tenant.Delete(_setting, Request, id); return Ok(); } [HttpGet("{id}")] public IActionResult GetUsage(string id) { if (id == null) return BadRequest(); var usage = Tenant.GetUsage(_setting, Request, id); return new ObjectResult( new { DISKSPACE = new {usage = usage.ContainsKey("DISKSPACE")? usage["DISKSPACE"] : 0}, USERS = new {usage = usage.ContainsKey("USERS")? usage["USERS"] : 0}, DEVICES = new {usage = usage.ContainsKey("DEVICES")? usage["DEVICES"] : 0}, } ); } [HttpGet("{id}/adminlogin")] public IActionResult AdminLogin(string id) { if (id == null) return BadRequest(); // Call Models var url = Tenant.GetAdminLogin(_setting, Request, id); return new ObjectResult( new { redirectUrl = url } ); } [HttpPut("{id}/disable")] public IActionResult DisableSubscription(string id) { return Ok(); } [HttpPut("{id}/enable")] public IActionResult EnableSubscription(string id) { return Ok(); } [HttpPost("{id}/users")] public IActionResult NotificationUserCreated(string id) { return Ok(); } [HttpDelete("{id}/users/{userid}")] public IActionResult NotificationUserDeleted(string id, string userid) { return Ok(); } [HttpPost("{id}/onUsersChange")] public IActionResult NotificationUserChanged(string id) { return Ok(); } } }
27.077519
102
0.486115
[ "Apache-2.0" ]
pkhodos/testapsconnector2
Controllers/TenantController.cs
3,493
C#
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Runtime.Serialization; namespace Quartz { /// <summary> /// An exception that is thrown to indicate that there is a misconfiguration of /// the <see cref="ISchedulerFactory" />- or one of the components it /// configures. /// </summary> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class SchedulerConfigException : SchedulerException { /// <summary> /// Create a <see cref="JobPersistenceException" /> with the given message. /// </summary> public SchedulerConfigException(string msg) : base(msg) { } /// <summary> /// Create a <see cref="JobPersistenceException" /> with the given message /// and cause. /// </summary> public SchedulerConfigException(string msg, Exception cause) : base(msg, cause) { } /// <summary> /// Initializes a new instance of the <see cref="SchedulerConfigException"/> class. /// </summary> /// <param name="info">The <see cref="T:SerializationInfo"></see> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"></see> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"></see> is zero (0). </exception> /// <exception cref="T:System.ArgumentNullException">The info parameter is null. </exception> public SchedulerConfigException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
38.83871
182
0.700997
[ "Apache-2.0" ]
1508553303/quartznet
src/Quartz/SchedulerConfigException.cs
2,408
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("T12")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("T12")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1cf97204-39c7-48bb-98bf-ca8f3cec1c7f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.27027
84
0.741842
[ "MIT" ]
nmilushev/Programming-Fundamentals-Sept-2017
progFundHomeworkCondStatements/T12/Properties/AssemblyInfo.cs
1,382
C#
using System.Web.Mvc; namespace ScriptRepository.Controllers { public class RepoController : Controller { public ActionResult Index() { return View(); } } }
17.166667
44
0.587379
[ "MIT" ]
yimlu/script-repo
ScriptRepository/Controllers/RepoController.cs
208
C#
using System; namespace Zadanie2 { public abstract class MySingleton1<T> where T : class, new() { private static T _instance; public static T GetInstance() { if (_instance == null) _instance = new T(); return _instance; } } public class MySingleton1A : MySingleton1<MySingleton1A> { } public class MySingleton1B : MySingleton1<MySingleton1B> { } public class MySingleton2 { private static MySingleton2 _instance; public virtual MySingleton2 GetInstance() { if (_instance == null) _instance = new MySingleton2(); return _instance; } } public class MySingleton2A : MySingleton2 { private static MySingleton2A _instance; public static MySingleton2A GetInstance() { if (_instance == null) _instance = new MySingleton2A(); return _instance; } } }
23.090909
64
0.562008
[ "MIT" ]
MaciejMilanski/DesignPatterns
Singleton/Singleton/Zadanie2.cs
1,018
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using Microsoft.Languages.Core.Text; using Microsoft.R.Core.Parser; namespace Microsoft.R.Editor.Validation.Errors { public class ValidationErrorCollection : List<IValidationError> { public void Add(ITextRange range, string message, ErrorLocation location) { Add(new ValidationError(range, message, location)); } } }
36.2
91
0.745856
[ "MIT" ]
Bhaskers-Blu-Org2/RTVS
src/R/Editor/Impl/Validation/Errors/ValidationErrorCollection.cs
545
C#
using System; namespace DailyRoutine { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.3125
69
0.604096
[ "MIT" ]
bsogulcan/DailyRoutine
aspnet-core/DailyRoutine/WeatherForecast.cs
293
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0022:Use expression body for methods", Justification = "Prefer keeping unit tests in Arrange-Act-Assert form.", Scope = "namespaceanddescendants", Target = "~N:CuteSVTests")] [assembly: SuppressMessage("Style", "IDE0017:Simplify object initialization", Justification = "Prefer keeping unit tests in Arrange-Act-Assert form.", Scope = "namespaceanddescendants", Target = "~N:CuteSVTests")] [assembly: SuppressMessage("Performance", "CA1814:Prefer jagged arrays over multidimensional", Justification = "Parquet requires multidimensional arrays.", Scope = "namespaceanddescendants", Target = "~N:CuteSVTests")]
57.842105
99
0.66424
[ "MIT" ]
mxashlynn/CuteSV
CuteSVTests/GlobalSuppressions.cs
1,099
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using System.Text.Json; using Kanka.NET.models; namespace Kanka.NET.Tests { [TestClass] public class SessionTests { private string _token = "", _response = ""; private KankaAPI _client; [TestInitialize] public void Setup() { // get the testing key from the file _token = System.IO.File.ReadAllText(@".\config\testingkey.txt"); _response = System.IO.File.ReadAllText(@".\config\exampleResponse.txt"); _client = new(_token); } [TestMethod] public async Task TestGetProfile() { var prof = await _client.GetProfile(); Assert.IsNotNull(prof); Assert.IsTrue(prof.Data?.Name?.Equals("DocSchlock")); } [TestMethod] public async Task TestGetAllCampaigns() { var campaigns = await _client.GetCampaigns(); Assert.IsNotNull(campaigns); } [TestMethod] public void DeserializeTest() { var obj = JsonSerializer.Deserialize<KankaResponse<Profile>>(_response); Assert.IsNotNull(obj); } } }
27.217391
84
0.585463
[ "MIT" ]
DocSchlock/Kanka.NET
Kanka.NET.Tests/SessionTests.cs
1,252
C#
using Avalonia.ReactiveUI; using LapisItemEditor.ViewModels; using Avalonia.Markup.Xaml; using ReactiveUI; using LapisItemEditor.ViewModels.Main; namespace LapisItemEditor.Views { public class MainView : ReactiveUserControl<MainViewModel> { public MainView() { this.WhenActivated(disposables => { }); AvaloniaXamlLoader.Load(this); } } }
23.411765
62
0.68593
[ "MIT" ]
MajestyOTBR/LapisItemEditor
LapisItemEditor/Views/Main/MainView.axaml.cs
398
C#
using System.Collections.Generic; namespace Fizz.UI { using Extentions; public interface IFizzHypercasualInputDataProvider { List<string> GetAllTags (); List<string> GetAllPhrases (string tag); List<string> GetAllStickers (string tag); FizzHypercasualPhraseDataItem GetPhrase (string id); FizzHypercasualStickerDataItem GetSticker (string id); List<string> GetRecentPhrases (); List<string> GetRecentStickers (); void AddPhraseToRecent (string id); void AddStickerToRecent (string id); } }
26.5
62
0.682676
[ "MIT" ]
FizzCorp/Hyper-Casual-Chat
Assets/FizzUI/Scripts/Extentions/Data/IFizzHypercasualInputDataProvider.cs
585
C#
namespace Application.Providers { public interface IConfigurationProvider { public string GetConfiguration(string key); } }
18.125
51
0.710345
[ "MIT" ]
TiagosCz/DotNepWebAppTemplate
src/WebApi/Application/Providers/IConfigurationProvider.cs
147
C#
namespace Microsoft.AspNet.OData.Routing { using Microsoft.AspNet.OData.Extensions; using Microsoft.AspNet.OData.Routing.Conventions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Versioning; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.OData.Edm; using System; using System.Collections.Generic; using System.Linq; using static System.StringComparison; /// <summary> /// Represents the <see cref="IODataRoutingConvention">OData routing convention</see> for versioned service and metadata documents. /// </summary> [CLSCompliant( false )] public class VersionedMetadataRoutingConvention : IODataRoutingConvention { /// <summary> /// Selects the controller for OData requests. /// </summary> /// <param name="odataPath">The OData path.</param> /// <param name="request">The request.</param> /// <returns>The name of the selected controller or <c>null</c> if the request isn't handled by this convention.</returns> protected virtual string? SelectController( ODataPath odataPath, HttpRequest request ) { if ( odataPath == null ) { throw new ArgumentNullException( nameof( odataPath ) ); } if ( request == null ) { throw new ArgumentNullException( nameof( request ) ); } if ( odataPath.PathTemplate != "~" && odataPath.PathTemplate != "~/$metadata" ) { return null; } var context = request.HttpContext; var feature = context.ApiVersioningFeature(); string? apiVersion; try { apiVersion = feature.RawRequestedApiVersion; } catch ( AmbiguousApiVersionException ) { // the appropriate response will be handled by policy return "VersionedMetadata"; } // the service document and metadata endpoints are special, but they are not neutral. if the client doesn't // specify a version, they may not know to. assume a default version by policy, but it's always allowed. // a client might also send an OPTIONS request to determine which versions are available (ex: tooling) if ( string.IsNullOrEmpty( apiVersion ) ) { var modelSelector = request.GetRequestContainer().GetRequiredService<IEdmModelSelector>(); var versionSelector = context.RequestServices.GetRequiredService<IApiVersionSelector>(); var model = new ApiVersionModel( modelSelector.ApiVersions, Enumerable.Empty<ApiVersion>() ); feature.RequestedApiVersion = versionSelector.SelectVersion( request, model ); } return "VersionedMetadata"; } /// <summary> /// Selects the action for OData requests. /// </summary> /// <param name="routeContext">The route context.</param> /// <returns>The name of the selected action or <c>null</c> if the request isn't handled by this convention.</returns> /// <remarks>The matching <see cref="IEnumerable{T}">sequence</see> of <see cref="ControllerActionDescriptor">actions</see> /// or <c>null</c> if no actions match the convention.</remarks> public virtual IEnumerable<ControllerActionDescriptor>? SelectAction( RouteContext routeContext ) { if ( routeContext == null ) { throw new ArgumentNullException( nameof( routeContext ) ); } const IEnumerable<ControllerActionDescriptor>? NoActions = default; var httpContext = routeContext.HttpContext; var odataPath = httpContext.ODataFeature().Path; var request = httpContext.Request; var controller = SelectController( odataPath, request ); if ( controller == null ) { return NoActions; } var actionCollectionProvider = httpContext.RequestServices.GetRequiredService<IActionDescriptorCollectionProvider>(); var actions = actionCollectionProvider.ActionDescriptors.Items; if ( odataPath.PathTemplate == "~" ) { return SelectActions( actions, controller, nameof( VersionedMetadataController.GetServiceDocument ) ); } if ( odataPath.PathTemplate != "~/$metadata" ) { return NoActions; } var method = request.Method; if ( method.Equals( "GET", OrdinalIgnoreCase ) ) { return SelectActions( actions, controller, nameof( VersionedMetadataController.GetMetadata ) ); } else if ( method.Equals( "OPTIONS", OrdinalIgnoreCase ) ) { return SelectActions( actions, controller, nameof( VersionedMetadataController.GetOptions ) ); } return NoActions; } static IEnumerable<ControllerActionDescriptor> SelectActions( IReadOnlyList<ActionDescriptor> actions, string controllerName, string actionName ) { for ( var i = 0; i < actions.Count; i++ ) { if ( actions[i] is ControllerActionDescriptor action ) { if ( action.ControllerName == controllerName && action.ActionName == actionName ) { yield return action; } } } } } }
40.782313
135
0.5995
[ "MIT" ]
Microsoft/aspnet-api-versioning
src/Microsoft.AspNetCore.OData.Versioning/AspNet.OData/Routing/VersionedMetadataRoutingConvention.cs
5,997
C#
using System; using System.Threading; using System.Threading.Tasks; using Elsa.Models; using Elsa.Services.Models; using NodaTime; namespace Elsa.Services.Workflows { public class WorkflowFactory : IWorkflowFactory { private readonly IClock _clock; private readonly IIdGenerator _idGenerator; public WorkflowFactory(IClock clock, IIdGenerator idGenerator) { _clock = clock; _idGenerator = idGenerator; } public Task<WorkflowInstance> InstantiateAsync( IWorkflowBlueprint workflowBlueprint, string? correlationId = default, string? contextId = default, string? tenantId = default, CancellationToken cancellationToken = default) { var workflowInstance = new WorkflowInstance { Id = _idGenerator.Generate(), DefinitionId = workflowBlueprint.Id, TenantId = tenantId ?? workflowBlueprint.TenantId, Version = workflowBlueprint.Version, WorkflowStatus = WorkflowStatus.Idle, CorrelationId = correlationId ?? Guid.NewGuid().ToString("N"), ContextId = contextId, CreatedAt = _clock.GetCurrentInstant(), Variables = new Variables(workflowBlueprint.Variables), ContextType = workflowBlueprint.ContextOptions?.ContextType?.GetContextTypeName() }; return Task.FromResult(workflowInstance); } } }
34.533333
97
0.621622
[ "MIT" ]
Blazi-Commerce/elsa-core
src/core/Elsa.Core/Services/Workflows/WorkflowFactory.cs
1,554
C#
using JetBrains.Annotations; namespace ITGlobal.CommandLine.Parsing { /// <summary> /// Extension method for <see cref="CliCommand"/> /// </summary> [PublicAPI] public static class CliCommandExtensions { /// <summary> /// Add a command line named string option /// </summary> [NotNull] public static CliOption<string> Option( [NotNull] this CliCommand command, [NotNull] string longName, string helpText = null, bool hidden = false ) { return command.Option<string>(longName, helpText, hidden); } /// <summary> /// Add a command line named string option /// </summary> [NotNull] public static CliOption<string> Option( [NotNull] this CliCommand command, char shortName, string longName = null, string helpText = null, bool hidden = false ) { return command.Option<string>(shortName, longName, helpText, hidden); } /// <summary> /// Add a command line repeatable named string option /// </summary> [NotNull] public static CliRepeatableOption<string> RepeatableOption( [NotNull] this CliCommand command, [NotNull] string longName, string helpText = null, bool hidden = false ) { return command.RepeatableOption<string>(longName, helpText, hidden); } /// <summary> /// Add a command line repeatable named string option /// </summary> [NotNull] public static CliRepeatableOption<string> RepeatableOption( [NotNull] this CliCommand command, char shortName, string longName = null, string helpText = null, bool hidden = false ) { return command.RepeatableOption<string>(shortName, longName, helpText, hidden); } /// <summary> /// Add a command line positional string argument /// </summary> [NotNull] public static CliArgument<string> Argument( [NotNull] this CliCommand command, [NotNull] string displayName, string helpText = null, bool hidden = false ) { return command.Argument<string>(displayName, helpText, hidden); } /// <summary> /// Add a command line repeatable positional string argument /// </summary> [NotNull] public static CliRepeatableArgument<string> RepeatableArgument( [NotNull] this CliCommand command, [NotNull] string displayName, string helpText = null, bool hidden = false ) { return command.RepeatableArgument<string>(displayName, helpText, hidden); } } }
30.969072
91
0.546272
[ "MIT" ]
ITGlobal/CLI
src/CLI.Parser/CliCommandExtensions.cs
3,004
C#
using System; using System.Collections.Generic; using System.Text; namespace DCore.Entities { public class AbilityResult { public int Damage { get; set; } public int Healing { get; set; } //...effects } interface IAbility { AbilityResult CastToDamage(); } public class Abilities { private Dictionary<Type,IAbility> _abilities; public Abilities() { _abilities = new Dictionary<Type, IAbility>(); } public Abilities AddAbility<T>(T ability) { var body = (IAbility) ability; _abilities.Add(typeof(T),body); return this; } public AbilityResult CastAbility<T>() { if (_abilities.ContainsKey(typeof(T))) { return _abilities[typeof(T)].CastToDamage(); } return new AbilityResult() { Damage = 0, Healing = 0 }; } } }
20.66
60
0.508228
[ "Apache-2.0" ]
Dewyer/D-DJustice
D-DCore/D-DCore/Entities/Abilities.cs
1,035
C#
/* * Copyright(c) 2021 Samsung Electronics Co., Ltd. * * 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 Tizen.NUI { internal static partial class Interop { internal static partial class Rectangle { [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_Rectangle__SWIG_0")] public static extern global::System.IntPtr NewRectangle(); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_Rectangle__SWIG_1")] public static extern global::System.IntPtr NewRectangle(int jarg1, int jarg2, int jarg3, int jarg4); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_Rectangle__SWIG_2")] public static extern global::System.IntPtr NewRectangle(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Assign")] public static extern global::System.IntPtr Assign(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Set")] public static extern void Set(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2, int jarg3, int jarg4, int jarg5); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_IsEmpty")] public static extern bool IsEmpty(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Left")] public static extern int Left(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Right")] public static extern int Right(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Top")] public static extern int Top(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Bottom")] public static extern int Bottom(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Area")] public static extern int Area(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Intersects")] public static extern bool Intersects(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_Contains")] public static extern bool Contains(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_x_set")] public static extern void XSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_x_get")] public static extern int XGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_left_set")] public static extern void LeftSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_left_get")] public static extern int LeftGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_y_set")] public static extern void YSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_y_get")] public static extern int YGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_right_set")] public static extern void RightSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_right_get")] public static extern int RightGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_width_set")] public static extern void WidthSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_width_get")] public static extern int WidthGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_bottom_set")] public static extern void BottomSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_bottom_get")] public static extern int BottomGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_height_set")] public static extern void HeightSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_height_get")] public static extern int HeightGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_top_set")] public static extern void TopSet(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Rectangle_top_get")] public static extern int TopGet(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_Rectangle")] public static extern void DeleteRectangle(global::System.Runtime.InteropServices.HandleRef jarg1); } } }
69.215517
174
0.750405
[ "Apache-2.0", "MIT" ]
AchoWang/TizenFX
src/Tizen.NUI/src/internal/Interop/Interop.Rectangle.cs
8,031
C#
//****************************************** // Copyright (C) 2014-2015 Charles Nurse * // * // Licensed under MIT License * // (see included LICENSE) * // * // ***************************************** namespace FamilyTreeProject.Dnn.Common { public enum OwnerType { Module, User } }
25.117647
45
0.316159
[ "MIT" ]
cnurse/FamilyTreeProject.Dnn
src/FamilyTreeProject.Dnn/Common/OwnerType.cs
429
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.WebJobs.Script.Grpc.Messages; using Microsoft.Azure.WebJobs.Script.Workers.Rpc; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.Azure.WebJobs.Script.Grpc { public static class GrpcServiceCollectionsExtensions { public static IServiceCollection AddGrpc(this IServiceCollection services) { services.AddSingleton<IRpcWorkerChannelFactory, GrpcWorkerChannelFactory>(); services.AddSingleton<FunctionRpc.FunctionRpcBase, FunctionRpcService>(); services.AddSingleton<IRpcServer, GrpcServer>(); return services; } } }
37.666667
95
0.742099
[ "Apache-2.0", "MIT" ]
ConnectionMaster/azure-functions-host
src/WebJobs.Script.Grpc/GrpcServiceCollectionsExtensions.cs
793
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 disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IFieldReferenceExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void FieldReference_Attribute() { string source = @" using System.Diagnostics; class C { private const string field = nameof(field); [/*<bind>*/Conditional(field)/*</bind>*/] void M() { } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: 'Conditional(field)') Children(1): IFieldReferenceOperation: System.String C.field (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""field"") (Syntax: 'field') Instance Receiver: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AttributeSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReferenceExpression_OutVar_Script() { string source = @" public void M2(out int i ) { i = 0; } M2(out /*<bind>*/int i/*</bind>*/); "; string expectedOperationTree = @" IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i') IFieldReferenceOperation: System.Int32 Script.i (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<DeclarationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Script); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReferenceExpression_DeconstructionDeclaration_Script() { string source = @" /*<bind>*/(int i1, int i2)/*</bind>*/ = (1, 2); "; string expectedOperationTree = @" ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, int i2)') NaturalType: (System.Int32 i1, System.Int32 i2) Elements(2): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1') IFieldReferenceOperation: System.Int32 Script.i1 (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i2') IFieldReferenceOperation: System.Int32 Script.i2 (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Script); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReferenceExpression_InferenceOutVar_Script() { string source = @" public void M2(out int i ) { i = 0; } M2(out /*<bind>*/var i/*</bind>*/); "; string expectedOperationTree = @" IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') IFieldReferenceOperation: System.Int32 Script.i (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<DeclarationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Script); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReferenceExpression_InferenceDeconstructionDeclaration_Script() { string source = @" /*<bind>*/(var i1, var i2)/*</bind>*/ = (1, 2); "; string expectedOperationTree = @" ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(var i1, var i2)') NaturalType: (System.Int32 i1, System.Int32 i2) Elements(2): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i1') IFieldReferenceOperation: System.Int32 Script.i1 (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i2') IFieldReferenceOperation: System.Int32 Script.i2 (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Script); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReferenceExpression_InferenceDeconstructionDeclaration_AlternateSyntax_Script() { string source = @" /*<bind>*/var (i1, i2)/*</bind>*/ = (1, 2); "; string expectedOperationTree = @" IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2)') ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)') NaturalType: (System.Int32 i1, System.Int32 i2) Elements(2): IFieldReferenceOperation: System.Int32 Script.i1 (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i1') IFieldReferenceOperation: System.Int32 Script.i2 (IsDeclaration: True) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Script, IsImplicit) (Syntax: 'i2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<DeclarationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Script); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")] [Fact] public void IFieldReferenceExpression_ImplicitThis() { string source = @" class C { int i; void M() { /*<bind>*/i/*</bind>*/ = 1; i++; } } "; string expectedOperationTree = @" IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'i') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")] [Fact] public void IFieldReferenceExpression_ExplicitThis() { string source = @" class C { int i; void M() { /*<bind>*/this.i/*</bind>*/ = 1; i++; } } "; string expectedOperationTree = @" IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'this.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<MemberAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(7582, "https://github.com/dotnet/roslyn/issues/7582")] [Fact] public void IFieldReferenceExpression_base() { string source = @" class C { protected int i; } class B : C { void M() { /*<bind>*/base.i/*</bind>*/ = 1; i++; } } "; string expectedOperationTree = @" IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'base.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'base') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<MemberAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReferenceExpression_IndexingFixed_Unmovable() { string source = @" unsafe struct S1 { public fixed int field[10]; } unsafe class C { void M() { S1 s = default; /*<bind>*/ s.field[3] = 1; /*</bind>*/ } } "; string expectedOperationTree = @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 's.field[3] = 1') Left: IOperation: (OperationKind.None, Type: null) (Syntax: 's.field[3]') Children(2): IFieldReferenceOperation: System.Int32* S1.field (OperationKind.FieldReference, Type: System.Int32*) (Syntax: 's.field') Instance Receiver: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: S1) (Syntax: 's') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReferenceExpression_IndexingFixed_Movable() { string source = @" unsafe struct S1 { public fixed int field[10]; } unsafe class C { S1 s = default; void M() { /*<bind>*/ s.field[3] = 1; /*</bind>*/ } } "; string expectedOperationTree = @" ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 's.field[3] = 1') Left: IOperation: (OperationKind.None, Type: null) (Syntax: 's.field[3]') Children(2): IFieldReferenceOperation: System.Int32* S1.field (OperationKind.FieldReference, Type: System.Int32*) (Syntax: 's.field') Instance Receiver: IFieldReferenceOperation: S1 C.s (OperationKind.FieldReference, Type: S1) (Syntax: 's') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 's') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReference_StaticFieldWithInstanceReceiver() { string source = @" class C { static int i; public static void M() { var c = new C(); var i1 = /*<bind>*/c.i/*</bind>*/; } } "; string expectedOperationTree = @" IFieldReferenceOperation: System.Int32 C.i (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'c.i') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0176: Member 'C.i' cannot be accessed with an instance reference; qualify it with a type name instead // var i1 = /*<bind>*/c.i/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.i").WithArguments("C.i").WithLocation(9, 28), // CS0649: Field 'C.i' is never assigned to, and will always have its default value 0 // static int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("C.i", "0").WithLocation(4, 16) }; VerifyOperationTreeAndDiagnosticsForTest<MemberAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReference_StaticFieldInObjectInitializer_NoInstance() { string source = @" class C { static int i1; public static void Main() { var c = new C { /*<bind>*/i1/*</bind>*/ = 1 }; } } "; string expectedOperationTree = @" IFieldReferenceOperation: System.Int32 C.i1 (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'i1') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1914: Static field or property 'C.i1' cannot be assigned in an object initializer // var c = new C { /*<bind>*/i1/*</bind>*/ = 1 }; Diagnostic(ErrorCode.ERR_StaticMemberInObjectInitializer, "i1").WithArguments("C.i1").WithLocation(7, 35), // CS0414: The field 'C.i1' is assigned but its value is never used // static int i1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i1").WithArguments("C.i1").WithLocation(4, 16) }; VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReference_StaticField() { string source = @" class C { static int i; public static void M() { var i1 = /*<bind>*/C.i/*</bind>*/; } } "; string expectedOperationTree = @" IFieldReferenceOperation: System.Int32 C.i (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'C.i') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0649: Field 'C.i' is never assigned to, and will always have its default value 0 // static int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("C.i", "0").WithLocation(4, 16) }; VerifyOperationTreeAndDiagnosticsForTest<MemberAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IFieldReference_InstanceField_InvalidAccessOffOfClass() { string source = @" class C { int i; public static void M() { var i1 = /*<bind>*/C.i/*</bind>*/; } } "; string expectedOperationTree = @" IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'C.i') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0120: An object reference is required for the non-static field, method, or property 'C.i' // var i1 = /*<bind>*/C.i/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.i").WithArguments("C.i").WithLocation(8, 28), // CS0649: Field 'C.i' is never assigned to, and will always have its default value 0 // int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("C.i", "0").WithLocation(4, 9) }; VerifyOperationTreeAndDiagnosticsForTest<MemberAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FieldReference_NoControlFlow() { // Verify mix of field references with implicit/explicit/null instance in lvalue/rvalue contexts. string source = @" class C { int i; static int j; void M(C c) /*<bind>*/{ i = C.j; j = this.i + c.i; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = C.j;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = C.j') Left: IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'i') Right: IFieldReferenceOperation: System.Int32 C.j (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'C.j') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = this.i + c.i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = this.i + c.i') Left: IFieldReferenceOperation: System.Int32 C.j (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'j') Instance Receiver: null Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'this.i + c.i') Left: IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'this.i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Right: IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.i') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FieldReference_ControlFlowInReceiver() { string source = @" class C { public int i = 0; void M(C c1, C c2, int p) /*<bind>*/{ p = (c1 ?? c2).i; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = (c1 ?? c2).i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'p = (c1 ?? c2).i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IFieldReferenceOperation: System.Int32 C.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(c1 ?? c2).i') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void FieldReference_ControlFlowInReceiver_StaticField() { string source = @" class C { public static int i = 0; void M(C c1, C c2, int p1, int p2) /*<bind>*/{ p1 = c1.i; p2 = (c1 ?? c2).i; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p1 = c1.i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'p1 = c1.i') Left: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') Right: IFieldReferenceOperation: System.Int32 C.i (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'c1.i') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p2 = (c1 ?? c2).i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'p2 = (c1 ?? c2).i') Left: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p2') Right: IFieldReferenceOperation: System.Int32 C.i (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: '(c1 ?? c2).i') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,14): error CS0176: Member 'C.i' cannot be accessed with an instance reference; qualify it with a type name instead // p1 = c1.i; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c1.i").WithArguments("C.i").WithLocation(7, 14), // file.cs(8,14): error CS0176: Member 'C.i' cannot be accessed with an instance reference; qualify it with a type name instead // p2 = (c1 ?? c2).i; Diagnostic(ErrorCode.ERR_ObjectProhibited, "(c1 ?? c2).i").WithArguments("C.i").WithLocation(8, 14) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] [WorkItem(38195, "https://github.com/dotnet/roslyn/issues/38195")] [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.NullableReferenceTypes)] public void NullableFieldReference() { var program = @" class C<T> { private C<T> _field; public static void M(C<T> p) { _ = p._field; } }"; var compWithoutNullable = CreateCompilation(program); var compWithNullable = CreateCompilation(program, options: WithNullableEnable()); testCore(compWithoutNullable); testCore(compWithNullable); static void testCore(CSharpCompilation comp) { var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(); var classSym = (INamedTypeSymbol)model.GetDeclaredSymbol(classDecl); var fieldSym = classSym.GetMembers("_field").Single(); var methodDecl = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var methodBlockOperation = model.GetOperation(methodDecl); var fieldReferenceOperation = methodBlockOperation.Descendants().OfType<IFieldReferenceOperation>().Single(); Assert.True(fieldSym.Equals(fieldReferenceOperation.Field)); Assert.Equal(fieldSym.GetHashCode(), fieldReferenceOperation.Field.GetHashCode()); } } } }
41.372549
181
0.645836
[ "MIT" ]
333fred/roslyn
src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IFieldReferenceExpression.cs
29,542
C#
using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Phase.Translator.Haxe { public class SwitchBlock : CommentedNodeEmitBlock<SwitchStatementSyntax> { protected override void DoEmit(CancellationToken cancellationToken = new CancellationToken()) { WriteSwitch(); WriteOpenParentheses(); EmitTree(Node.Expression, cancellationToken); WriteCloseParentheses(); WriteNewLine(); BeginBlock(); bool hasDefault = false; foreach (var section in Node.Sections) { var sectionHasDefault = section.Labels.Any(l => l.Kind() == SyntaxKind.DefaultSwitchLabel); if (sectionHasDefault) { Write("default"); hasDefault = true; } else { for (var i = 0; i < section.Labels.Count; i++) { if (i == 0) Write("case "); else Write(", "); EmitterContext.IsCaseLabel = true; var label = section.Labels[i]; switch (label.Kind()) { case SyntaxKind.CaseSwitchLabel: var caseLabel = (CaseSwitchLabelSyntax) label; EmitTree(caseLabel.Value, cancellationToken); break; default: Debugger.Break(); break; } EmitterContext.IsCaseLabel = false; } } WriteColon(); WriteNewLine(); Indent(); foreach (var statement in section.Statements) { EmitTree(statement, cancellationToken); } Outdent(); } if (!hasDefault) { Write("default:"); WriteNewLine(); } EndBlock(); } } }
32.315068
107
0.441289
[ "MIT" ]
CoderLine/Phase
Phase.Translator/Haxe/Statements/SwitchBlock.cs
2,359
C#
using FreeSql.Internal; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FreeSql.Sqlite.Curd { class SqliteInsert<T1> : Internal.CommonProvider.InsertProvider<T1> where T1 : class { public SqliteInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } public override int ExecuteAffrows() => base.SplitExecuteAffrows(_batchValuesLimit > 0 ? _batchValuesLimit : 5000, _batchParameterLimit > 0 ? _batchParameterLimit : 999); public override long ExecuteIdentity() => base.SplitExecuteIdentity(_batchValuesLimit > 0 ? _batchValuesLimit : 5000, _batchParameterLimit > 0 ? _batchParameterLimit : 999); public override List<T1> ExecuteInserted() => base.SplitExecuteInserted(_batchValuesLimit > 0 ? _batchValuesLimit : 5000, _batchParameterLimit > 0 ? _batchParameterLimit : 999); protected override long RawExecuteIdentity() { var sql = this.ToSql(); if (string.IsNullOrEmpty(sql)) return 0; sql = string.Concat(sql, "; SELECT last_insert_rowid();"); var before = new Aop.CurdBeforeEventArgs(_table.Type, _table, Aop.CurdType.Insert, sql, _params); _orm.Aop.CurdBeforeHandler?.Invoke(this, before); long ret = 0; Exception exception = null; try { long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret); } catch (Exception ex) { exception = ex; throw ex; } finally { var after = new Aop.CurdAfterEventArgs(before, exception, ret); _orm.Aop.CurdAfterHandler?.Invoke(this, after); } return ret; } protected override List<T1> RawExecuteInserted() { var sql = this.ToSql(); if (string.IsNullOrEmpty(sql)) return new List<T1>(); var ret = _source.ToList(); this.RawExecuteAffrows(); return ret; } #if net40 #else public override Task<int> ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(_batchValuesLimit > 0 ? _batchValuesLimit : 5000, _batchParameterLimit > 0 ? _batchParameterLimit : 999); public override Task<long> ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(_batchValuesLimit > 0 ? _batchValuesLimit : 5000, _batchParameterLimit > 0 ? _batchParameterLimit : 999); public override Task<List<T1>> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(_batchValuesLimit > 0 ? _batchValuesLimit : 5000, _batchParameterLimit > 0 ? _batchParameterLimit : 999); async protected override Task<long> RawExecuteIdentityAsync() { var sql = this.ToSql(); if (string.IsNullOrEmpty(sql)) return 0; sql = string.Concat(sql, "; SELECT last_insert_rowid();"); var before = new Aop.CurdBeforeEventArgs(_table.Type, _table, Aop.CurdType.Insert, sql, _params); _orm.Aop.CurdBeforeHandler?.Invoke(this, before); long ret = 0; Exception exception = null; try { long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret); } catch (Exception ex) { exception = ex; throw ex; } finally { var after = new Aop.CurdAfterEventArgs(before, exception, ret); _orm.Aop.CurdAfterHandler?.Invoke(this, after); } return ret; } async protected override Task<List<T1>> RawExecuteInsertedAsync() { var sql = this.ToSql(); if (string.IsNullOrEmpty(sql)) return new List<T1>(); var ret = _source.ToList(); await this.RawExecuteAffrowsAsync(); return ret; } #endif } }
40.865385
201
0.611294
[ "MIT" ]
1051324354/FreeSql
Providers/FreeSql.Provider.Sqlite/Curd/SqliteInsert.cs
4,252
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using FairyGUI.Utils; namespace FairyGUI { public class AsyncCreationHelper { public static void CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) { Timers.inst.StartCoroutine(_CreateObject(item, callback)); } static IEnumerator _CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) { Stats.LatestObjectCreation = 0; Stats.LatestGraphicsCreation = 0; float frameTime = UIConfig.frameTimeForAsyncUIConstruction; List<DisplayListItem> itemList = new List<DisplayListItem>(); DisplayListItem di = new DisplayListItem(item, ObjectType.Component); di.childCount = CollectComponentChildren(item, itemList); itemList.Add(di); int cnt = itemList.Count; List<GObject> objectPool = new List<GObject>(cnt); GObject obj; float t = Time.realtimeSinceStartup; bool alreadyNextFrame = false; for (int i = 0; i < cnt; i++) { di = itemList[i]; if (di.packageItem != null) { obj = UIObjectFactory.NewObject(di.packageItem); obj.packageItem = di.packageItem; objectPool.Add(obj); UIPackage._constructing++; if (di.packageItem.type == PackageItemType.Component) { int poolStart = objectPool.Count - di.childCount - 1; ((GComponent)obj).ConstructFromResource(objectPool, poolStart); objectPool.RemoveRange(poolStart, di.childCount); } else { obj.ConstructFromResource(); } UIPackage._constructing--; } else { obj = UIObjectFactory.NewObject(di.type); objectPool.Add(obj); if (di.type == ObjectType.List && di.listItemCount > 0) { int poolStart = objectPool.Count - di.listItemCount - 1; for (int k = 0; k < di.listItemCount; k++) //把他们都放到pool里,这样GList在创建时就不需要创建对象了 ((GList)obj).itemPool.ReturnObject(objectPool[k + poolStart]); objectPool.RemoveRange(poolStart, di.listItemCount); } } if ((i % 5 == 0) && Time.realtimeSinceStartup - t >= frameTime) { yield return null; t = Time.realtimeSinceStartup; alreadyNextFrame = true; } } if (!alreadyNextFrame) //强制至至少下一帧才调用callback,避免调用者逻辑出错 yield return null; callback(objectPool[0]); } /// <summary> /// 收集创建目标对象所需的所有类型信息 /// </summary> /// <param name="item"></param> /// <param name="list"></param> static int CollectComponentChildren(PackageItem item, List<DisplayListItem> list) { ByteBuffer buffer = item.rawData; buffer.Seek(0, 2); int dcnt = buffer.ReadShort(); DisplayListItem di; PackageItem pi; for (int i = 0; i < dcnt; i++) { int dataLen = buffer.ReadShort(); int curPos = buffer.position; buffer.Seek(curPos, 0); ObjectType type = (ObjectType)buffer.ReadByte(); string src = buffer.ReadS(); string pkgId = buffer.ReadS(); buffer.position = curPos; if (src != null) { UIPackage pkg; if (pkgId != null) pkg = UIPackage.GetById(pkgId); else pkg = item.owner; pi = pkg != null ? pkg.GetItem(src) : null; di = new DisplayListItem(pi, type); if (pi != null && pi.type == PackageItemType.Component) di.childCount = CollectComponentChildren(pi, list); } else { di = new DisplayListItem(null, type); if (type == ObjectType.List) //list di.listItemCount = CollectListChildren(buffer, list); } list.Add(di); buffer.position = curPos + dataLen; } return dcnt; } static int CollectListChildren(ByteBuffer buffer, List<DisplayListItem> list) { buffer.Seek(buffer.position, 8); string defaultItem = buffer.ReadS(); int listItemCount = 0; int itemCount = buffer.ReadShort(); for (int i = 0; i < itemCount; i++) { int nextPos = buffer.ReadShort(); nextPos += buffer.position; string url = buffer.ReadS(); if (url == null) url = defaultItem; if (!string.IsNullOrEmpty(url)) { PackageItem pi = UIPackage.GetItemByURL(url); if (pi != null) { DisplayListItem di = new DisplayListItem(pi, pi.objectType); if (pi.type == PackageItemType.Component) di.childCount = CollectComponentChildren(pi, list); list.Add(di); listItemCount++; } } buffer.position = nextPos; } return listItemCount; } /// <summary> /// /// </summary> class DisplayListItem { public PackageItem packageItem; public ObjectType type; public int childCount; public int listItemCount; public DisplayListItem(PackageItem pi, ObjectType type) { this.packageItem = pi; this.type = type; } } } }
25.633508
94
0.625408
[ "MIT" ]
CCGame119/FairyGUI-unity-3.0.0
Examples.Unity5/Assets/Plugins/FairyGUI/Scripts/UI/AsyncCreationHelper.cs
5,020
C#
using RapidCMS.Core.Abstractions.Mediators; using RapidCMS.Core.Enums; using RapidCMS.Core.Models.EventArgs.Mediators; using Vaultr.Client.Core.Abstractions; namespace Vaultr.Client.Core.Providers { internal class DangerModeProvider : IDangerModeProvider { private readonly IMediator _mediator; public DangerModeProvider(IMediator mediator) { _mediator = mediator; } public bool IsEnabled { get; private set; } public void Disable() { IsEnabled = false; Notify(); } public void Enable() { IsEnabled = true; Notify(); } private void Notify() { _mediator.NotifyEvent( this, new CollectionRepositoryEventArgs( "vaultr::secrets", "vaultr::secrets", default, default(string), CrudType.Update)); } } }
22.456522
59
0.528558
[ "MIT" ]
ThomasBleijendaal/Vaultr
Vaultr/Vaultr.Client/Core/Providers/DangerModeProvider.cs
1,035
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using Microsoft.Owin.Host.SystemWeb; using Owin; namespace System.Web.Routing { /// <summary> /// Provides extension methods for registering OWIN applications as System.Web routes. /// </summary> public static class RouteCollectionExtensions { /// <summary> /// Registers a route for the default OWIN application. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="pathBase">The route path to map to the default OWIN application.</param> /// <returns>The created route.</returns> public static RouteBase MapOwinPath(this RouteCollection routes, string pathBase) { return Add(routes, null, new OwinRoute(pathBase, OwinApplication.Accessor)); } /// <summary> /// Registers a route for a specific OWIN application entry point. /// </summary> /// <typeparam name="TApp">The OWIN application entry point type.</typeparam> /// <param name="routes">The route collection.</param> /// <param name="pathBase">The route path to map to the given OWIN application.</param> /// <param name="app">The OWIN application entry point.</param> /// <returns>The created route.</returns> public static RouteBase MapOwinPath<TApp>(this RouteCollection routes, string pathBase, TApp app) { if (app == null) { throw new ArgumentNullException("app"); } OwinAppContext appDelegate = OwinBuilder.Build(builder => builder.Use(new Func<object, object>(_ => app))); return Add(routes, null, new OwinRoute(pathBase, () => appDelegate)); } /// <summary> /// Invokes the System.Action startup delegate to build the OWIN application /// and then registers a route for it on the given path. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="pathBase">The route path to map to the given OWIN application.</param> /// <param name="startup">A System.Action delegate invoked to build the OWIN application.</param> /// <returns>The created route.</returns> public static RouteBase MapOwinPath(this RouteCollection routes, string pathBase, Action<IAppBuilder> startup) { OwinAppContext appDelegate = OwinBuilder.Build(startup); return Add(routes, null, new OwinRoute(pathBase, () => appDelegate)); } /// <summary> /// Registers a route for the default OWIN application. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="name">The given name of the route.</param> /// <param name="pathBase">The route path to map to the default OWIN application.</param> /// <returns>The created route.</returns> public static RouteBase MapOwinPath(this RouteCollection routes, string name, string pathBase) { return Add(routes, name, new OwinRoute(pathBase, OwinApplication.Accessor)); } /// <summary> /// Registers a route for a specific OWIN application entry point. /// </summary> /// <typeparam name="TApp">The OWIN application entry point type.</typeparam> /// <param name="routes">The route collection.</param> /// <param name="name">The given name of the route.</param> /// <param name="pathBase">The route path to map to the given OWIN application.</param> /// <param name="app">The OWIN application entry point.</param> /// <returns>The created route.</returns> public static RouteBase MapOwinPath<TApp>(this RouteCollection routes, string name, string pathBase, TApp app) { if (app == null) { throw new ArgumentNullException("app"); } OwinAppContext appDelegate = OwinBuilder.Build(builder => builder.Use(new Func<object, object>(_ => app))); return Add(routes, name, new OwinRoute(pathBase, () => appDelegate)); } /// <summary> /// Invokes the System.Action startup delegate to build the OWIN application /// and then registers a route for it on the given path. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="name">The given name of the route.</param> /// <param name="pathBase">The route path to map to the given OWIN application.</param> /// <param name="startup">A System.Action delegate invoked to build the OWIN application.</param> /// <returns>The created route.</returns> public static RouteBase MapOwinPath(this RouteCollection routes, string name, string pathBase, Action<IAppBuilder> startup) { OwinAppContext appDelegate = OwinBuilder.Build(startup); return Add(routes, name, new OwinRoute(pathBase, () => appDelegate)); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeUrl, Action<IAppBuilder> startup) { return Add(routes, null, new Route(routeUrl, new OwinRouteHandler(startup))); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="defaults">The values to use if the URL does not contain all the parameters.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeUrl, RouteValueDictionary defaults, Action<IAppBuilder> startup) { return Add(routes, null, new Route(routeUrl, defaults, new OwinRouteHandler(startup))); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="defaults">The values to use if the URL does not contain all the parameters.</param> /// <param name="constraints">A regular expression that specifies valid values for a URL parameter.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeUrl, RouteValueDictionary defaults, RouteValueDictionary constraints, Action<IAppBuilder> startup) { return Add(routes, null, new Route(routeUrl, defaults, constraints, new OwinRouteHandler(startup))); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="defaults">The values to use if the URL does not contain all the parameters.</param> /// <param name="constraints">A regular expression that specifies valid values for a URL parameter.</param> /// <param name="dataTokens">Custom values that are passed to the route handler, but which are not used to determine whether the route matches a specific URL pattern. These values are passed to the route handler, where they can be used for processing the request.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeUrl, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, Action<IAppBuilder> startup) { return Add(routes, null, new Route(routeUrl, defaults, constraints, dataTokens, new OwinRouteHandler(startup))); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeName">The name of the route.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeName, string routeUrl, Action<IAppBuilder> startup) { return Add(routes, routeName, new Route(routeUrl, new OwinRouteHandler(startup))); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeName">The name of the route.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="defaults">The values to use if the URL does not contain all the parameters.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeName, string routeUrl, RouteValueDictionary defaults, Action<IAppBuilder> startup) { return Add(routes, routeName, new Route(routeUrl, defaults, new OwinRouteHandler(startup))); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeName">The name of the route.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="defaults">The values to use if the URL does not contain all the parameters.</param> /// <param name="constraints">A regular expression that specifies valid values for a URL parameter.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeName, string routeUrl, RouteValueDictionary defaults, RouteValueDictionary constraints, Action<IAppBuilder> startup) { return Add(routes, routeName, new Route(routeUrl, defaults, constraints, new OwinRouteHandler(startup))); } /// <summary> /// Provides a way to define routes for an OWIN pipeline. /// </summary> /// <param name="routes">The route collection.</param> /// <param name="routeName">The name of the route.</param> /// <param name="routeUrl">The URL pattern for the route.</param> /// <param name="defaults">The values to use if the URL does not contain all the parameters.</param> /// <param name="constraints">A regular expression that specifies valid values for a URL parameter.</param> /// <param name="dataTokens">Custom values that are passed to the route handler, but which are not used to determine whether the route matches a specific URL pattern. These values are passed to the route handler, where they can be used for processing the request.</param> /// <param name="startup">The method to initialize the pipeline that processes requests for the route.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Parameter type determined by Route class")] public static Route MapOwinRoute( this RouteCollection routes, string routeName, string routeUrl, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, Action<IAppBuilder> startup) { return Add(routes, routeName, new Route(routeUrl, defaults, constraints, dataTokens, new OwinRouteHandler(startup))); } private static T Add<T>(RouteCollection routes, string name, T item) where T : RouteBase { if (string.IsNullOrEmpty(name)) { routes.Add(item); } else { routes.Add(name, item); } return item; } } }
55.081481
279
0.641541
[ "Apache-2.0" ]
15901213541/-OAuth2.0
src/Microsoft.Owin.Host.SystemWeb/RouteCollectionExtensions.cs
14,874
C#
// Sourced from https://www.codeproject.com/Articles/159352/FolderBrowserDialogEx-A-C-customization-of-FolderB // Licenced under CPOL // // // FolderBrowserDialogEx.cs // // A replacement for the builtin System.Windows.Forms.FolderBrowserDialog class. // This one includes an edit box, and also displays the full path in the edit box. // // based on code from http://support.microsoft.com/default.aspx?scid=kb;[LN];306285 // // 20 Feb 2009 // // ======================================================================================== // Example usage: // // string _folderName = "c:\\dinoch"; // private void button1_Click(object sender, EventArgs e) // { // _folderName = (System.IO.Directory.Exists(_folderName)) ? _folderName : ""; // var dlg1 = new Ionic.Utils.FolderBrowserDialogEx // { // Description = "Select a folder for the extracted files:", // ShowNewFolderButton = true, // ShowEditBox = true, // //NewStyle = false, // SelectedPath = _folderName, // ShowFullPathInEditBox= false, // }; // dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer; // // var result = dlg1.ShowDialog(); // // if (result == DialogResult.OK) // { // _folderName = dlg1.SelectedPath; // this.label1.Text = "The folder selected was: "; // this.label2.Text = _folderName; // } // } // using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System.Windows.Forms; namespace TileIconifier.Controls.CustomFolderBrowserDialog { //[Designer("System.Windows.Forms.Design.FolderBrowserDialogDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DefaultEvent("HelpRequest"), SRDescription("DescriptionFolderBrowserDialog"), DefaultProperty("SelectedPath")] public class FolderBrowserDialogEx : System.Windows.Forms.CommonDialog { private static readonly int MAX_PATH = 260; // Fields private PInvoke.BrowseFolderCallbackProc _callback; private string _descriptionText; private Environment.SpecialFolder _rootFolder; private string _selectedPath; private bool _selectedPathNeedsCheck; private bool _showNewFolderButton; private bool _showEditBox; private bool _showBothFilesAndFolders; private bool _newStyle = true; private bool _showFullPathInEditBox = true; private bool _dontIncludeNetworkFoldersBelowDomainLevel; private int _uiFlags; private IntPtr _hwndEdit; private IntPtr _rootFolderLocation; // Events //[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler HelpRequest { add { base.HelpRequest += value; } remove { base.HelpRequest -= value; } } // ctor public FolderBrowserDialogEx() { this.Reset(); } // Factory Methods public static FolderBrowserDialogEx PrinterBrowser() { FolderBrowserDialogEx x = new FolderBrowserDialogEx(); // avoid MBRO comppiler warning when passing _rootFolderLocation as a ref: x.BecomePrinterBrowser(); return x; } public static FolderBrowserDialogEx ComputerBrowser() { FolderBrowserDialogEx x = new FolderBrowserDialogEx(); // avoid MBRO comppiler warning when passing _rootFolderLocation as a ref: x.BecomeComputerBrowser(); return x; } // Helpers private void BecomePrinterBrowser() { _uiFlags += BrowseFlags.BIF_BROWSEFORPRINTER; Description = "Select a printer:"; PInvoke.Shell32.SHGetSpecialFolderLocation(IntPtr.Zero, CSIDL.PRINTERS, ref this._rootFolderLocation); ShowNewFolderButton = false; ShowEditBox = false; } private void BecomeComputerBrowser() { _uiFlags += BrowseFlags.BIF_BROWSEFORCOMPUTER; Description = "Select a computer:"; PInvoke.Shell32.SHGetSpecialFolderLocation(IntPtr.Zero, CSIDL.NETWORK, ref this._rootFolderLocation); ShowNewFolderButton = false; ShowEditBox = false; } private class CSIDL { public const int PRINTERS = 4; public const int NETWORK = 0x12; } private class BrowseFlags { public const int BIF_DEFAULT = 0x0000; public const int BIF_BROWSEFORCOMPUTER = 0x1000; public const int BIF_BROWSEFORPRINTER = 0x2000; public const int BIF_BROWSEINCLUDEFILES = 0x4000; public const int BIF_BROWSEINCLUDEURLS = 0x0080; public const int BIF_DONTGOBELOWDOMAIN = 0x0002; public const int BIF_EDITBOX = 0x0010; public const int BIF_NEWDIALOGSTYLE = 0x0040; public const int BIF_NONEWFOLDERBUTTON = 0x0200; public const int BIF_RETURNFSANCESTORS = 0x0008; public const int BIF_RETURNONLYFSDIRS = 0x0001; public const int BIF_SHAREABLE = 0x8000; public const int BIF_STATUSTEXT = 0x0004; public const int BIF_UAHINT = 0x0100; public const int BIF_VALIDATE = 0x0020; public const int BIF_NOTRANSLATETARGETS = 0x0400; } private static class BrowseForFolderMessages { // messages FROM the folder browser public const int BFFM_INITIALIZED = 1; public const int BFFM_SELCHANGED = 2; public const int BFFM_VALIDATEFAILEDA = 3; public const int BFFM_VALIDATEFAILEDW = 4; public const int BFFM_IUNKNOWN = 5; // messages TO the folder browser public const int BFFM_SETSTATUSTEXT = 0x464; public const int BFFM_ENABLEOK = 0x465; public const int BFFM_SETSELECTIONA = 0x466; public const int BFFM_SETSELECTIONW = 0x467; } private int FolderBrowserCallback(IntPtr hwnd, int msg, IntPtr lParam, IntPtr lpData) { switch (msg) { case BrowseForFolderMessages.BFFM_INITIALIZED: if (this._selectedPath.Length != 0) { PInvoke.User32.SendMessage(new HandleRef(null, hwnd), BrowseForFolderMessages.BFFM_SETSELECTIONW, 1, this._selectedPath); if (this._showEditBox && this._showFullPathInEditBox) { // get handle to the Edit box inside the Folder Browser Dialog _hwndEdit = PInvoke.User32.FindWindowEx(new HandleRef(null, hwnd), IntPtr.Zero, "Edit", null); PInvoke.User32.SetWindowText(_hwndEdit, this._selectedPath); } } break; case BrowseForFolderMessages.BFFM_SELCHANGED: IntPtr pidl = lParam; if (pidl != IntPtr.Zero) { if (((_uiFlags & BrowseFlags.BIF_BROWSEFORPRINTER) == BrowseFlags.BIF_BROWSEFORPRINTER) || ((_uiFlags & BrowseFlags.BIF_BROWSEFORCOMPUTER) == BrowseFlags.BIF_BROWSEFORCOMPUTER)) { // we're browsing for a printer or computer, enable the OK button unconditionally. PInvoke.User32.SendMessage(new HandleRef(null, hwnd), BrowseForFolderMessages.BFFM_ENABLEOK, 0, 1); } else { IntPtr pszPath = Marshal.AllocHGlobal(MAX_PATH * Marshal.SystemDefaultCharSize); bool haveValidPath = PInvoke.Shell32.SHGetPathFromIDList(pidl, pszPath); String displayedPath = Marshal.PtrToStringAuto(pszPath); Marshal.FreeHGlobal(pszPath); // whether to enable the OK button or not. (if file is valid) PInvoke.User32.SendMessage(new HandleRef(null, hwnd), BrowseForFolderMessages.BFFM_ENABLEOK, 0, haveValidPath ? 1 : 0); // Maybe set the Edit Box text to the Full Folder path if (haveValidPath && !String.IsNullOrEmpty(displayedPath)) { if (_showEditBox && _showFullPathInEditBox) { if (_hwndEdit != IntPtr.Zero) PInvoke.User32.SetWindowText(_hwndEdit, displayedPath); } if ((_uiFlags & BrowseFlags.BIF_STATUSTEXT) == BrowseFlags.BIF_STATUSTEXT) PInvoke.User32.SendMessage(new HandleRef(null, hwnd), BrowseForFolderMessages.BFFM_SETSTATUSTEXT, 0, displayedPath); } } } break; } return 0; } private static PInvoke.IMalloc GetSHMalloc() { PInvoke.IMalloc[] ppMalloc = new PInvoke.IMalloc[1]; PInvoke.Shell32.SHGetMalloc(ppMalloc); return ppMalloc[0]; } public override void Reset() { this._rootFolder = (Environment.SpecialFolder)0; this._descriptionText = string.Empty; this._selectedPath = string.Empty; this._selectedPathNeedsCheck = false; this._showNewFolderButton = true; this._showEditBox = true; this._newStyle = true; this._dontIncludeNetworkFoldersBelowDomainLevel = false; this._hwndEdit = IntPtr.Zero; this._rootFolderLocation = IntPtr.Zero; } protected override bool RunDialog(IntPtr hWndOwner) { bool result = false; if (_rootFolderLocation == IntPtr.Zero) { PInvoke.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int)this._rootFolder, ref _rootFolderLocation); if (_rootFolderLocation == IntPtr.Zero) { PInvoke.Shell32.SHGetSpecialFolderLocation(hWndOwner, 0, ref _rootFolderLocation); if (_rootFolderLocation == IntPtr.Zero) { throw new InvalidOperationException("FolderBrowserDialogNoRootFolder"); } } } _hwndEdit = IntPtr.Zero; //_uiFlags = 0; if (_dontIncludeNetworkFoldersBelowDomainLevel) _uiFlags += BrowseFlags.BIF_DONTGOBELOWDOMAIN; if (this._newStyle) _uiFlags += BrowseFlags.BIF_NEWDIALOGSTYLE; if (!this._showNewFolderButton) _uiFlags += BrowseFlags.BIF_NONEWFOLDERBUTTON; if (this._showEditBox) _uiFlags += BrowseFlags.BIF_EDITBOX; if (this._showBothFilesAndFolders) _uiFlags += BrowseFlags.BIF_BROWSEINCLUDEFILES; if (Control.CheckForIllegalCrossThreadCalls && (Application.OleRequired() != ApartmentState.STA)) { throw new ThreadStateException("DebuggingException: ThreadMustBeSTA"); } IntPtr pidl = IntPtr.Zero; IntPtr hglobal = IntPtr.Zero; IntPtr pszPath = IntPtr.Zero; try { PInvoke.BROWSEINFO browseInfo = new PInvoke.BROWSEINFO(); hglobal = Marshal.AllocHGlobal(MAX_PATH * Marshal.SystemDefaultCharSize); pszPath = Marshal.AllocHGlobal(MAX_PATH * Marshal.SystemDefaultCharSize); this._callback = new PInvoke.BrowseFolderCallbackProc(this.FolderBrowserCallback); browseInfo.pidlRoot = _rootFolderLocation; browseInfo.Owner = hWndOwner; browseInfo.pszDisplayName = hglobal; browseInfo.Title = this._descriptionText; browseInfo.Flags = _uiFlags; browseInfo.callback = this._callback; browseInfo.lParam = IntPtr.Zero; browseInfo.iImage = 0; pidl = PInvoke.Shell32.SHBrowseForFolder(browseInfo); if (((_uiFlags & BrowseFlags.BIF_BROWSEFORPRINTER) == BrowseFlags.BIF_BROWSEFORPRINTER) || ((_uiFlags & BrowseFlags.BIF_BROWSEFORCOMPUTER) == BrowseFlags.BIF_BROWSEFORCOMPUTER)) { this._selectedPath = Marshal.PtrToStringAuto(browseInfo.pszDisplayName); result = true; } else { if (pidl != IntPtr.Zero) { PInvoke.Shell32.SHGetPathFromIDList(pidl, pszPath); this._selectedPathNeedsCheck = true; this._selectedPath = Marshal.PtrToStringAuto(pszPath); result = true; } } } finally { PInvoke.IMalloc sHMalloc = GetSHMalloc(); sHMalloc.Free(_rootFolderLocation); _rootFolderLocation = IntPtr.Zero; if (pidl != IntPtr.Zero) { sHMalloc.Free(pidl); } if (pszPath != IntPtr.Zero) { Marshal.FreeHGlobal(pszPath); } if (hglobal != IntPtr.Zero) { Marshal.FreeHGlobal(hglobal); } this._callback = null; } return result; } // Properties //[SRDescription("FolderBrowserDialogDescription"), SRCategory("CatFolderBrowsing"), Browsable(true), DefaultValue(""), Localizable(true)] /// <summary> /// This description appears near the top of the dialog box, providing direction to the user. /// </summary> public string Description { get { return this._descriptionText; } set { this._descriptionText = value ?? string.Empty; } } //[Localizable(false), SRCategory("CatFolderBrowsing"), SRDescription("FolderBrowserDialogRootFolder"), TypeConverter(typeof(SpecialFolderEnumConverter)), Browsable(true), DefaultValue(0)] public Environment.SpecialFolder RootFolder { get { return this._rootFolder; } set { if (!Enum.IsDefined(typeof(Environment.SpecialFolder), value)) { throw new InvalidEnumArgumentException("value", (int)value, typeof(Environment.SpecialFolder)); } this._rootFolder = value; } } //[Browsable(true), SRDescription("FolderBrowserDialogSelectedPath"), SRCategory("CatFolderBrowsing"), DefaultValue(""), Editor("System.Windows.Forms.Design.SelectedPathEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), Localizable(true)] /// <summary> /// Set or get the selected path. /// </summary> public string SelectedPath { get { if (((this._selectedPath != null) && (this._selectedPath.Length != 0)) && this._selectedPathNeedsCheck) { new FileIOPermission(FileIOPermissionAccess.PathDiscovery, this._selectedPath).Demand(); this._selectedPathNeedsCheck = false; } return this._selectedPath; } set { this._selectedPath = (value == null) ? string.Empty : value; this._selectedPathNeedsCheck = true; } } //[SRDescription("FolderBrowserDialogShowNewFolderButton"), Localizable(false), Browsable(true), DefaultValue(true), SRCategory("CatFolderBrowsing")] /// <summary> /// Enable or disable the "New Folder" button in the browser dialog. /// </summary> public bool ShowNewFolderButton { get { return this._showNewFolderButton; } set { this._showNewFolderButton = value; } } /// <summary> /// Show an "edit box" in the folder browser. /// </summary> /// <remarks> /// The "edit box" normally shows the name of the selected folder. /// The user may also type a pathname directly into the edit box. /// </remarks> /// <seealso cref="ShowFullPathInEditBox"/> public bool ShowEditBox { get { return this._showEditBox; } set { this._showEditBox = value; } } /// <summary> /// Set whether to use the New Folder Browser dialog style. /// </summary> /// <remarks> /// The new style is resizable and includes a "New Folder" button. /// </remarks> public bool NewStyle { get { return this._newStyle; } set { this._newStyle = value; } } public bool DontIncludeNetworkFoldersBelowDomainLevel { get { return _dontIncludeNetworkFoldersBelowDomainLevel; } set { _dontIncludeNetworkFoldersBelowDomainLevel = value; } } /// <summary> /// Show the full path in the edit box as the user selects it. /// </summary> /// <remarks> /// This works only if ShowEditBox is also set to true. /// </remarks> public bool ShowFullPathInEditBox { get { return _showFullPathInEditBox; } set { _showFullPathInEditBox = value; } } public bool ShowBothFilesAndFolders { get { return _showBothFilesAndFolders; } set { _showBothFilesAndFolders = value; } } } internal static class PInvoke { static PInvoke() { } public delegate int BrowseFolderCallbackProc(IntPtr hwnd, int msg, IntPtr lParam, IntPtr lpData); internal static class User32 { [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, string lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, int lParam); [DllImport("user32.dll", SetLastError = true)] //public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); //public static extern IntPtr FindWindowEx(HandleRef hwndParent, HandleRef hwndChildAfter, string lpszClass, string lpszWindow); public static extern IntPtr FindWindowEx(HandleRef hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("user32.dll", SetLastError = true)] public static extern Boolean SetWindowText(IntPtr hWnd, String text); } [ComImport, Guid("00000002-0000-0000-c000-000000000046"), SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMalloc { [PreserveSig] IntPtr Alloc(int cb); [PreserveSig] IntPtr Realloc(IntPtr pv, int cb); [PreserveSig] void Free(IntPtr pv); [PreserveSig] int GetSize(IntPtr pv); [PreserveSig] int DidAlloc(IntPtr pv); [PreserveSig] void HeapMinimize(); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class BROWSEINFO { public IntPtr Owner; public IntPtr pidlRoot; public IntPtr pszDisplayName; public string Title; public int Flags; public BrowseFolderCallbackProc callback; public IntPtr lParam; public int iImage; } [SuppressUnmanagedCodeSecurity] internal static class Shell32 { // Methods [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SHBrowseForFolder([In] PInvoke.BROWSEINFO lpbi); [DllImport("shell32.dll")] public static extern int SHGetMalloc([Out, MarshalAs(UnmanagedType.LPArray)] PInvoke.IMalloc[] ppMalloc); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern bool SHGetPathFromIDList(IntPtr pidl, IntPtr pszPath); [DllImport("shell32.dll")] public static extern int SHGetSpecialFolderLocation(IntPtr hwnd, int csidl, ref IntPtr ppidl); } } }
39.317029
309
0.565636
[ "MIT" ]
Crazymine-hub/TileIconifier
TileIconifier/Controls/CustomFolderBrowserDialog/FolderBrowserDialogEx.cs
21,705
C#
using System; using System.Diagnostics; using System.Fabric; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Services.Runtime; namespace FileUpload.FileAPI { internal static class Program { /// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. ServiceRuntime.RegisterServiceAsync("FileUpload.FileAPIType", context => new File(context)).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(File).Name); // Prevents this host process from terminating so services keep running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } } } }
34.125
116
0.60293
[ "MIT" ]
marceloazuma/FileUpload
File/Program.cs
1,367
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p2.Pisp.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// The Initiation payload is sent by the initiating party to the ASPSP. It /// is used to request movement of funds from the debtor account to a /// creditor for a single domestic payment. /// </summary> public partial class OBWriteDomestic2DataInitiation { /// <summary> /// Initializes a new instance of the OBWriteDomestic2DataInitiation /// class. /// </summary> public OBWriteDomestic2DataInitiation() { CustomInit(); } /// <summary> /// Initializes a new instance of the OBWriteDomestic2DataInitiation /// class. /// </summary> /// <param name="instructionIdentification">Unique identification as /// assigned by an instructing party for an instructed party to /// unambiguously identify the instruction. /// Usage: the instruction identification is a point to point /// reference that can be used between the instructing party and the /// instructed party to refer to the individual instruction. It can be /// included in several messages related to the instruction.</param> /// <param name="endToEndIdentification">Unique identification assigned /// by the initiating party to unambiguously identify the transaction. /// This identification is passed on, unchanged, throughout the entire /// end-to-end chain. /// Usage: The end-to-end identification can be used for reconciliation /// or to link tasks relating to the transaction. It can be included in /// several messages related to the transaction. /// OB: The Faster Payments Scheme can only access 31 characters for /// the EndToEndIdentification field.</param> /// <param name="instructedAmount">Amount of money to be moved between /// the debtor and creditor, before deduction of charges, expressed in /// the currency as ordered by the initiating party. /// Usage: This amount has to be transported unchanged through the /// transaction chain.</param> /// <param name="creditorAccount">Unambiguous identification of the /// account of the creditor to which a credit entry will be posted as a /// result of the payment transaction.</param> /// <param name="debtorAccount">Unambiguous identification of the /// account of the debtor to which a debit entry will be made as a /// result of the transaction.</param> /// <param name="remittanceInformation">Information supplied to enable /// the matching of an entry with the items that the transfer is /// intended to settle, such as commercial invoices in an accounts' /// receivable system.</param> public OBWriteDomestic2DataInitiation(string instructionIdentification, string endToEndIdentification, OBWriteDomestic2DataInitiationInstructedAmount instructedAmount, OBWriteDomestic2DataInitiationCreditorAccount creditorAccount, string localInstrument = default(string), OBWriteDomestic2DataInitiationDebtorAccount debtorAccount = default(OBWriteDomestic2DataInitiationDebtorAccount), OBPostalAddress6 creditorPostalAddress = default(OBPostalAddress6), OBWriteDomestic2DataInitiationRemittanceInformation remittanceInformation = default(OBWriteDomestic2DataInitiationRemittanceInformation), IDictionary<string, object> supplementaryData = default(IDictionary<string, object>)) { InstructionIdentification = instructionIdentification; EndToEndIdentification = endToEndIdentification; LocalInstrument = localInstrument; InstructedAmount = instructedAmount; DebtorAccount = debtorAccount; CreditorAccount = creditorAccount; CreditorPostalAddress = creditorPostalAddress; RemittanceInformation = remittanceInformation; SupplementaryData = supplementaryData; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets unique identification as assigned by an instructing /// party for an instructed party to unambiguously identify the /// instruction. /// Usage: the instruction identification is a point to point /// reference that can be used between the instructing party and the /// instructed party to refer to the individual instruction. It can be /// included in several messages related to the instruction. /// </summary> [JsonProperty(PropertyName = "InstructionIdentification")] public string InstructionIdentification { get; set; } /// <summary> /// Gets or sets unique identification assigned by the initiating party /// to unambiguously identify the transaction. This identification is /// passed on, unchanged, throughout the entire end-to-end chain. /// Usage: The end-to-end identification can be used for reconciliation /// or to link tasks relating to the transaction. It can be included in /// several messages related to the transaction. /// OB: The Faster Payments Scheme can only access 31 characters for /// the EndToEndIdentification field. /// </summary> [JsonProperty(PropertyName = "EndToEndIdentification")] public string EndToEndIdentification { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "LocalInstrument")] public string LocalInstrument { get; set; } /// <summary> /// Gets or sets amount of money to be moved between the debtor and /// creditor, before deduction of charges, expressed in the currency as /// ordered by the initiating party. /// Usage: This amount has to be transported unchanged through the /// transaction chain. /// </summary> [JsonProperty(PropertyName = "InstructedAmount")] public OBWriteDomestic2DataInitiationInstructedAmount InstructedAmount { get; set; } /// <summary> /// Gets or sets unambiguous identification of the account of the /// debtor to which a debit entry will be made as a result of the /// transaction. /// </summary> [JsonProperty(PropertyName = "DebtorAccount")] public OBWriteDomestic2DataInitiationDebtorAccount DebtorAccount { get; set; } /// <summary> /// Gets or sets unambiguous identification of the account of the /// creditor to which a credit entry will be posted as a result of the /// payment transaction. /// </summary> [JsonProperty(PropertyName = "CreditorAccount")] public OBWriteDomestic2DataInitiationCreditorAccount CreditorAccount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "CreditorPostalAddress")] public OBPostalAddress6 CreditorPostalAddress { get; set; } /// <summary> /// Gets or sets information supplied to enable the matching of an /// entry with the items that the transfer is intended to settle, such /// as commercial invoices in an accounts' receivable system. /// </summary> [JsonProperty(PropertyName = "RemittanceInformation")] public OBWriteDomestic2DataInitiationRemittanceInformation RemittanceInformation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "SupplementaryData")] public IDictionary<string, object> SupplementaryData { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (InstructionIdentification == null) { throw new ValidationException(ValidationRules.CannotBeNull, "InstructionIdentification"); } if (EndToEndIdentification == null) { throw new ValidationException(ValidationRules.CannotBeNull, "EndToEndIdentification"); } if (InstructedAmount == null) { throw new ValidationException(ValidationRules.CannotBeNull, "InstructedAmount"); } if (CreditorAccount == null) { throw new ValidationException(ValidationRules.CannotBeNull, "CreditorAccount"); } if (InstructedAmount != null) { InstructedAmount.Validate(); } if (DebtorAccount != null) { DebtorAccount.Validate(); } if (CreditorAccount != null) { CreditorAccount.Validate(); } } } }
47.929293
686
0.653741
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.BankApiModels/UkObRw/V3p1p2/Pisp/Models/OBWriteDomestic2DataInitiation.cs
9,490
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace MyAlbum.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
25.25
88
0.680693
[ "MIT" ]
NhatTanVu/myalbum
src/WebSPA.Identity/Pages/Error.cshtml.cs
808
C#
#if UNITY_2020_1_OR_NEWER using System.Collections.Generic; using UnityEngine; using Unity.MLAgents.Sensors; namespace Unity.MLAgents.Extensions.Sensors { public class ArticulationBodyJointExtractor : IJointExtractor { ArticulationBody m_Body; public ArticulationBodyJointExtractor(ArticulationBody body) { m_Body = body; } public int NumObservations(PhysicsSensorSettings settings) { return NumObservations(m_Body, settings); } public static int NumObservations(ArticulationBody body, PhysicsSensorSettings settings) { if (body == null || body.isRoot) { return 0; } var totalCount = 0; if (settings.UseJointPositionsAndAngles) { switch (body.jointType) { case ArticulationJointType.RevoluteJoint: case ArticulationJointType.SphericalJoint: // Both RevoluteJoint and SphericalJoint have all angular components. // We use sine and cosine of the angles for the observations. totalCount += 2 * body.dofCount; break; case ArticulationJointType.FixedJoint: // Since FixedJoint can't moved, there aren't any interesting observations for it. break; case ArticulationJointType.PrismaticJoint: // One linear component totalCount += body.dofCount; break; } } if (settings.UseJointForces) { totalCount += body.dofCount; } return totalCount; } public int Write(PhysicsSensorSettings settings, ObservationWriter writer, int offset) { if (m_Body == null || m_Body.isRoot) { return 0; } var currentOffset = offset; // Write joint positions if (settings.UseJointPositionsAndAngles) { switch (m_Body.jointType) { case ArticulationJointType.RevoluteJoint: case ArticulationJointType.SphericalJoint: // All joint positions are angular for (var dofIndex = 0; dofIndex < m_Body.dofCount; dofIndex++) { var jointRotationRads = m_Body.jointPosition[dofIndex]; writer[currentOffset++] = Mathf.Sin(jointRotationRads); writer[currentOffset++] = Mathf.Cos(jointRotationRads); } break; case ArticulationJointType.FixedJoint: // No observations break; case ArticulationJointType.PrismaticJoint: writer[currentOffset++] = GetPrismaticValue(); break; } } if (settings.UseJointForces) { for (var dofIndex = 0; dofIndex < m_Body.dofCount; dofIndex++) { // take tanh to keep in [-1, 1] writer[currentOffset++] = (float) System.Math.Tanh(m_Body.jointForce[dofIndex]); } } return currentOffset - offset; } float GetPrismaticValue() { // Prismatic joints should have at most one free axis. bool limited = false; var drive = m_Body.xDrive; if (m_Body.linearLockX == ArticulationDofLock.LimitedMotion) { drive = m_Body.xDrive; limited = true; } else if (m_Body.linearLockY == ArticulationDofLock.LimitedMotion) { drive = m_Body.yDrive; limited = true; } else if (m_Body.linearLockZ == ArticulationDofLock.LimitedMotion) { drive = m_Body.zDrive; limited = true; } var jointPos = m_Body.jointPosition[0]; if (limited) { // If locked, interpolate between the limits. var upperLimit = drive.upperLimit; var lowerLimit = drive.lowerLimit; if (upperLimit <= lowerLimit) { // Invalid limits (probably equal), so don't try to lerp return 0; } var invLerped = Mathf.InverseLerp(lowerLimit, upperLimit, jointPos); // Convert [0, 1] -> [-1, 1] var normalized = 2.0f * invLerped - 1.0f; return normalized; } // take tanh() to keep in [-1, 1] return (float) System.Math.Tanh(jointPos); } } } #endif
34.843537
106
0.490824
[ "Apache-2.0" ]
CYBER-CROP/ml-agents
com.unity.ml-agents.extensions/Runtime/Sensors/ArticulationBodyJointExtractor.cs
5,122
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("2.Maximal sum")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("2.Maximal sum")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1da6a1a3-1e3b-43b9-b5fe-ff0d7a4a35c5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.810811
84
0.742673
[ "MIT" ]
lubangelova/Csharp-Advanced
Homework/02. Multidimensional Arrays/2.Maximal sum/Properties/AssemblyInfo.cs
1,402
C#
#pragma checksum "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "70cf4619df2b0786bc44d6b23839605bf306eabc" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Account_Manage_Index), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/Manage/Index.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\_ViewImports.cshtml" using YourSpace.Areas.Identity; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\_ViewImports.cshtml" using YourSpace.Areas.Identity.Pages; #line default #line hidden #nullable disable #nullable restore #line 1 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\_ViewImports.cshtml" using YourSpace.Areas.Identity.Pages.Account; #line default #line hidden #nullable disable #nullable restore #line 1 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml" using YourSpace.Areas.Identity.Pages.Account.Manage; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"70cf4619df2b0786bc44d6b23839605bf306eabc", @"/Areas/Identity/Pages/Account/Manage/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3fed07ed2767aad1a2fc2dd1db3639ea67eb5910", @"/Areas/Identity/Pages/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b8c05371aa67708ed420ba2069b7ecfef458c1d6", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"775fc870bd8dec70bcf0ce5f76f9b3da86e08597", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")] public class Areas_Identity_Pages_Account_Manage_Index : global::Microsoft.AspNetCore.Mvc.RazorPages.Page { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "Identity", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "/Account/Logout", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-route-returnUrl", "/", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("profile-form"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_StatusMessage", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_ValidationScriptsPartial", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 3 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" ViewData["Title"] = "Profile"; ViewData["ActivePage"] = ManageNavPages.Index; #line default #line hidden #nullable disable WriteLiteral("\r\n<div"); BeginWriteAttribute("class", " class=\"", 127, "\"", 135, 0); EndWriteAttribute(); WriteLiteral(@"> <ul class=""nav nav-tabs"" id=""myTab"" role=""tablist""> <li class=""nav-item""> <a class=""nav-link active"" id=""home-tab"" data-toggle=""tab"" href=""#home"" role=""tab"" aria-controls=""home"" aria-selected=""true"">Home</a> </li> <li class=""nav-item""> <a class=""nav-link"" id=""profile-tab"" data-toggle=""tab"" href=""#profile"" role=""tab"" aria-controls=""profile"" aria-selected=""false"">Profile</a> </li> <li class=""nav-item""> <a class=""nav-link"" id=""contact-tab"" data-toggle=""tab"" href=""#contact"" role=""tab"" aria-controls=""contact"" aria-selected=""false"">Contact</a> </li> </ul> <div class=""tab-content"" id=""myTabContent""> "); WriteLiteral(@" <div class=""tab-pane fade show active"" id=""home"" role=""tabpanel"" aria-labelledby=""home-tab""> <div class=""row""> <div class=""col col-md-6""> <div class=""d-flex flex-column""> <img class=""img-fluid"" src=""https://image.freepik.com/free-photo/smiling-young-man-wearing-sunglasses-taking-selfie-showing-thumb-up-gesture_23-2148203116.jpg"" /> <button class=""btn btn-primary w-100"">Change</button> </div> </div> <div class=""col col-md-6""> <div class=""d-flex flex-column""> "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "70cf4619df2b0786bc44d6b23839605bf306eabc10086", async() => { WriteLiteral("\r\n <button class=\"btn btn-danger\">\r\n Logout\r\n </button>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Page = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); if (__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-returnUrl", "Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper", "RouteValues")); } __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["returnUrl"] = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "70cf4619df2b0786bc44d6b23839605bf306eabc12638", async() => { WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "70cf4619df2b0786bc44d6b23839605bf306eabc12927", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper); #nullable restore #line 47 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "70cf4619df2b0786bc44d6b23839605bf306eabc14721", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 49 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Username); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "70cf4619df2b0786bc44d6b23839605bf306eabc16281", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 50 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Username); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); BeginWriteTagHelperAttribute(); __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __tagHelperExecutionContext.AddHtmlAttribute("disabled", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "70cf4619df2b0786bc44d6b23839605bf306eabc18345", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 53 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Input.PhoneNumber); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "70cf4619df2b0786bc44d6b23839605bf306eabc19914", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 54 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Input.PhoneNumber); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "70cf4619df2b0786bc44d6b23839605bf306eabc21564", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 55 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Input.PhoneNumber); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <button id=\"update-profile-button\" type=\"submit\" class=\"btn btn-primary\">Save</button>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n </div>\r\n </div>\r\n\r\n </div>\r\n\r\n"); WriteLiteral(" <div class=\"tab-pane fade\" id=\"profile\" role=\"tabpanel\" aria-labelledby=\"profile-tab\">\r\n tab\r\n </div>\r\n\r\n"); WriteLiteral(" <div class=\"tab-pane fade\" id=\"contact\" role=\"tabpanel\" aria-labelledby=\"contact-tab\">\r\n tab\r\n </div>\r\n\r\n </div>\r\n</div>\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "70cf4619df2b0786bc44d6b23839605bf306eabc25210", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_7.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7); #nullable restore #line 77 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Areas\Identity\Pages\Account\Manage\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Model = Model.StatusMessage; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("model", __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Model, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n\r\n\r\n"); DefineSection("Scripts", async() => { WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "70cf4619df2b0786bc44d6b23839605bf306eabc26934", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_8.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } ); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IndexModel> Html { get; private set; } public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<IndexModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<IndexModel>)PageContext?.ViewData; public IndexModel Model => ViewData.Model; } } #pragma warning restore 1591
75.814136
350
0.72715
[ "MIT" ]
Invectys/Sites
YourSpaceMDB_4.2_Optimization/YourSpace/obj/Debug/netcoreapp3.1/Razor/Areas/Identity/Pages/Account/Manage/Index.cshtml.g.cs
28,961
C#
using StackExchange.Redis.Branch.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace StackExchange.Redis.Branch.IntegrationTest.Fakes { [RedisQueryable] public class StockEntity : RedisEntity { public string Name { get; set; } public string Symbol { get; set; } public StockSector Sector { get; set; } public double Price { get; set; } public double PriceChangeRate { get; set; } public DateTime CreatedDateTime { get; set; } public bool IsActive { get; set; } public char FirstLetterOfName { get; set; } public byte LastByteOfName { get; set; } public short LengthOfNameShort { get; set; } public ushort LengthOfNameUshort { get; set; } public int LengthOfNameInt { get; set; } public uint LengthOfNameUint { get; set; } public long LengthOfNameLong { get; set; } public ulong LengthOfNameUlong { get; set; } public float LengthOfNameFloat { get; set; } public double LengthOfNameDouble { get; set; } public decimal LengthOfNameDecimal { get; set; } public StockMetaData MetaData { get; set; } [IgnoreDataMember] public string DummyString { get; set; } public StockEntity() { CreatedDateTime = DateTimeOffset.UtcNow.DateTime; } public StockEntity(string id, string name, StockSector sector, double price, double priceChangeRate) { Id = id; Name = name; Symbol = name.Substring(0, name.Length > 3 ? 3 : name.Length); Sector = sector; Price = price; PriceChangeRate = priceChangeRate; CreatedDateTime = DateTimeOffset.UtcNow.DateTime; IsActive = true; FirstLetterOfName = name.ToCharArray()[0]; LastByteOfName = (byte)name.ToCharArray()[name.Length - 1]; LengthOfNameShort = (short)name.Length; LengthOfNameUshort = (ushort)name.Length; LengthOfNameInt = name.Length; LengthOfNameUint = (uint)name.Length; LengthOfNameLong = name.Length; LengthOfNameUlong = (ulong)name.Length; LengthOfNameFloat = (float)name.Length; LengthOfNameDouble = (double)name.Length; LengthOfNameDecimal = (decimal)name.Length; Random random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; DummyString = new string(Enumerable.Repeat(chars, 10).Select(s => s[random.Next(s.Length)]).ToArray()); } public StockEntity(string id, string name, StockSector sector, double price, double priceChangeRate, StockMetaData metaData) { Id = id; Name = name; Symbol = name.Substring(0, name.Length > 3 ? 3 : name.Length); Sector = sector; Price = price; PriceChangeRate = priceChangeRate; CreatedDateTime = DateTimeOffset.UtcNow.DateTime; MetaData = metaData; IsActive = true; FirstLetterOfName = name.ToCharArray()[0]; LastByteOfName = (byte)name.ToCharArray()[name.Length - 1]; LengthOfNameShort = (short)name.Length; LengthOfNameUshort = (ushort)name.Length; LengthOfNameInt = name.Length; LengthOfNameUint = (uint)name.Length; LengthOfNameLong = name.Length; LengthOfNameUlong = (ulong)name.Length; LengthOfNameFloat = (float)name.Length; LengthOfNameDouble = (double)name.Length; LengthOfNameDecimal = (decimal)name.Length; Random random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; DummyString = new string(Enumerable.Repeat(chars, 10).Select(s => s[random.Next(s.Length)]).ToArray()); } public void FillCalculatedProperties() { FirstLetterOfName = Name.ToCharArray()[0]; LastByteOfName = (byte)Name.ToCharArray()[Name.Length - 1]; LengthOfNameShort = (short)Name.Length; LengthOfNameUshort = (ushort)Name.Length; LengthOfNameInt = Name.Length; LengthOfNameUint = (uint)Name.Length; LengthOfNameLong = Name.Length; LengthOfNameUlong = (ulong)Name.Length; LengthOfNameFloat = (float)Name.Length; LengthOfNameDouble = (double)Name.Length; LengthOfNameDecimal = (decimal)Name.Length; } } public enum StockSector { None = 0, Industrials = 1, HealthCare = 2, InformationTechnology = 3, CommunicationServices = 4, ConsumerDiscretionary = 5, Utilities = 6, Financials = 7, Materials = 8, RealEstate = 9, ConsumerStaples = 10, Energy = 11 }; public enum ProfitLevel { None = 0, Great = 1, Normal = 2, Loss = 3 }; public enum CurrencyCode { None = 0, USD = 1, EUR = 2 }; public class StockMetaData { public string Country { get; set; } public DateTime UpdateDateTime { get; set; } public CurrencyCode Currency { get; set; } public StockMetaData() { UpdateDateTime = DateTimeOffset.UtcNow.DateTime; } public StockMetaData(string country, CurrencyCode currency) { Country = country; Currency = currency; UpdateDateTime = DateTimeOffset.UtcNow.DateTime; } } }
32.104972
132
0.593702
[ "MIT" ]
dogabariscakmak/StackExchange.Redis.Branch
src/tests/StackExchange.Redis.Branch.IntegrationTest/Fakes/StockEntity.cs
5,813
C#
namespace MassTransit { using System.Threading.Tasks; public interface IMessageBuffer { Task Add<T>(IMessageEvent<T> messageEvent) where T : class; } }
17.272727
50
0.626316
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/MassTransit.Futures/IMessageBuffer.cs
192
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MementoServiceFacts.cs" company="WildGums"> // Copyright (c) 2008 - 2016 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Orc.Memento.Tests { using System; using System.Collections.Generic; using System.Linq; using Catel.Tests; using Mocks; using NUnit.Framework; public class MementoServiceFacts { #region Nested type: TheBeginBatchMethod [TestFixture] public class TheBeginBatchMethod { [TestCase] public void BeginsNewBatchWhenThereAlreadyIsABatch() { var mementoService = new MementoService(); var model = new MockModel(); var firstBatch = mementoService.BeginBatch("FirstBatch"); mementoService.Add(new PropertyChangeUndo(model, "Value", model.Value)); Assert.AreEqual(1, firstBatch.ActionCount); var secondBatch = mementoService.BeginBatch("SecondBatch"); mementoService.Add(new PropertyChangeUndo(model, "Value", model.Value)); Assert.AreEqual(1, secondBatch.ActionCount); // Also check if the first batch was closed Assert.AreEqual(1, mementoService.UndoBatches.Count()); Assert.AreEqual(1, firstBatch.ActionCount); } [TestCase] public void UndoBatches() { var model = new MockModel(); var mementoService = new MementoService(); mementoService.RegisterObject(model); string originalNumber = model.Value; mementoService.BeginBatch(); model.Value = "1000"; model.Value = "100"; model.Value = "10"; var mementoBatch = mementoService.EndBatch(); mementoBatch.Undo(); Assert.AreEqual(originalNumber, model.Value); } } #endregion #region Nested type: TheConstructor [TestFixture] public class TheConstructor { #region Methods [TestCase] public void ThrowsArgumentOutOfRangeExceptionForNegativeParameter() { ExceptionTester.CallMethodAndExpectException<ArgumentOutOfRangeException>(() => new MementoService(-1)); } [TestCase] public void ExpectDefaultMaximumSupportedActionsValue() { var mementoService = new MementoService(); Assert.AreEqual(300, mementoService.MaximumSupportedBatches); } #endregion } #endregion #region Nested type: TheEndBatchMethod [TestFixture] public class TheEndBatchMethod { [TestCase] public void EndsBatchWhenThereAlreadyIsABatch() { var mementoService = new MementoService(); var model = new MockModel(); var firstBatch = mementoService.BeginBatch("FirstBatch"); mementoService.Add(new PropertyChangeUndo(model, "Value", model.Value)); Assert.AreEqual(1, firstBatch.ActionCount); var secondBatch = mementoService.BeginBatch("SecondBatch"); mementoService.Add(new PropertyChangeUndo(model, "Value", model.Value)); Assert.AreEqual(1, secondBatch.ActionCount); mementoService.EndBatch(); Assert.AreEqual(2, mementoService.UndoBatches.Count()); } } #endregion #region Nested type: TheIsEnabledProperty [TestFixture] public class TheIsEnabledProperty { [TestCase] public void IsTrueByDefault() { var mementoService = new MementoService(); Assert.IsTrue(mementoService.IsEnabled); } [TestCase] public void PreventsAdditionsWhenDisabled() { var mementoService = new MementoService(); mementoService.IsEnabled = false; var undo1 = new MockUndo(true); mementoService.Add(undo1); Assert.IsFalse(mementoService.CanRedo); } } #endregion #region Nested type: TheMaximumSupportedProperty [TestFixture] public class TheMaximumSupportedProperty { #region Methods [TestCase] public void MaximumSupportedOperationsTest() { var mementoService = new MementoService(5); var listUndoOps = new List<MockUndo>(); for (var i = 0; i < 10; i++) { var memento = new MockUndo() {Value = i}; mementoService.Add(memento); listUndoOps.Add(memento); } var count = 0; while (mementoService.CanUndo) { mementoService.Undo(); count++; } for (var i = 0; i < 5; i++) { Assert.IsFalse(listUndoOps[i].UndoCalled); } for (var i = 5; i < 10; i++) { Assert.IsTrue(listUndoOps[i].UndoCalled); } Assert.AreEqual(count, mementoService.MaximumSupportedBatches); } #endregion } #endregion #region Nested type: TheRedoMethod [TestFixture] public class TheRedoMethod { #region Methods [TestCase] public void RedoTest() { var mementoService = new MementoService(); var undo1 = new MockUndo(true); mementoService.Add(undo1); mementoService.Undo(); Assert.IsTrue(undo1.UndoCalled); Assert.IsFalse(undo1.RedoCalled); Assert.IsTrue(mementoService.CanRedo); mementoService.Redo(); Assert.IsTrue(undo1.RedoCalled); Assert.IsFalse(mementoService.CanRedo); } [TestCase] public void HandlesDoubleRedo() { var obj = new MockModel {Value = "value1"}; var service = new MementoService(); service.RegisterObject(obj); obj.Value = "value2"; obj.Value = "value3"; service.Undo(); Assert.AreEqual("value2", obj.Value); service.Undo(); Assert.AreEqual("value1", obj.Value); service.Redo(); Assert.AreEqual("value2", obj.Value); service.Redo(); Assert.AreEqual("value3", obj.Value); } [TestCase] public void CanRedoTest() { var mementoService = new MementoService(); Assert.IsFalse(mementoService.CanUndo); mementoService.Add(new MockUndo()); Assert.IsTrue(mementoService.CanUndo); mementoService.Undo(); Assert.IsFalse(mementoService.CanRedo); mementoService.Add(new MockUndo(true)); Assert.IsTrue(mementoService.CanUndo); mementoService.Undo(); Assert.IsFalse(mementoService.CanUndo); Assert.IsTrue(mementoService.CanRedo); mementoService.Redo(); Assert.IsTrue(mementoService.CanUndo); Assert.IsFalse(mementoService.CanRedo); } [TestCase(1)] [TestCase(3)] [TestCase(6)] public void RaisesUpdatedEvent(int actionsCount) { var mementoService = new MementoService(); var raisedEventsCount = 0; mementoService.Updated += (sender, args) => { if(args.MementoAction == MementoAction.Redo) { raisedEventsCount++; } }; for (var i = 0; i < actionsCount; i++) { mementoService.Add(new MockUndo(true)); } for (var i = 0; i < actionsCount; i++) { mementoService.Undo(); } for (var i = 0; i < actionsCount; i++) { mementoService.Redo(); } Assert.AreEqual(actionsCount, raisedEventsCount); } #endregion } #endregion #region Nested type: TheUndoMethod [TestFixture] public class TheUndoMethod { #region Methods [TestCase] public void UndoTest() { var mementoService = new MementoService(); var undo1 = new MockUndo(); var undo2 = new MockUndo(); mementoService.Add(undo1); mementoService.Add(undo2); mementoService.Undo(); Assert.IsTrue(undo2.UndoCalled); Assert.IsFalse(undo1.UndoCalled); Assert.IsTrue(mementoService.CanUndo); } [TestCase] public void HandlesDoubleUndo() { var obj = new MockModel {Value = "value1"}; var service = new MementoService(); service.RegisterObject(obj); obj.Value = "value2"; obj.Value = "value3"; service.Undo(); Assert.AreEqual("value2", obj.Value); service.Undo(); Assert.AreEqual("value1", obj.Value); } [TestCase] public void CanUndoTest() { var mementoService = new MementoService(); Assert.IsFalse(mementoService.CanUndo); mementoService.Add(new MockUndo()); Assert.IsTrue(mementoService.CanUndo); mementoService.Undo(); Assert.IsFalse(mementoService.CanUndo); } [TestCase(1)] [TestCase(3)] [TestCase(6)] public void RaisesUpdatedEvent(int actionsCount) { var mementoService = new MementoService(); var raisedEventsCount = 0; mementoService.Updated += (sender, args) => { if (args.MementoAction == MementoAction.Undo) { raisedEventsCount++; } }; for (var i = 0; i < actionsCount; i++) { mementoService.Add(new MockUndo(true)); } for (var i = 0; i < actionsCount; i++) { mementoService.Undo(); } Assert.AreEqual(actionsCount, raisedEventsCount); } #endregion } #endregion #region Nested type: TheUnregisterObjectMethod [TestFixture] public class TheUnregisterObjectMethod { #region Methods [TestCase] public void ThrowsArgumentNullExceptionForNullInstance() { var service = new MementoService(); ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => service.UnregisterObject(null)); } [TestCase] public void CancelsSubscriptionForInstance() { var obj = new MockModel {Value = "value1"}; var service = new MementoService(); service.RegisterObject(obj); service.UnregisterObject(obj); obj.Value = "newvalue"; Assert.IsFalse(service.CanUndo); } [TestCase] public void ClearsCurrentUndoRedoStackForInstance() { var obj = new MockModel {Value = "value1"}; var service = new MementoService(); service.RegisterObject(obj); obj.Value = "newvalue1"; Assert.IsFalse(service.CanRedo); service.UnregisterObject(obj); Assert.IsFalse(service.CanUndo); } #endregion } #endregion [TestFixture] public class TheChangeNotifications { [TestCase] public void RaisesChangeRecordedEvent() { var mementoService = new MementoService(); var success = false; mementoService.Updated += (sender, e) => { if (e.MementoAction == MementoAction.ChangeRecorded) { success = true; } }; var undo1 = new MockUndo(); mementoService.Add(undo1); Assert.IsTrue(success); } [TestCase] public void RaisesClearDataEvent() { var mementoService = new MementoService(); var success = false; mementoService.Updated += (sender, e) => { if (e.MementoAction == MementoAction.ClearData) { success = true; } }; mementoService.Clear(); Assert.IsTrue(success); } } } }
30.802603
122
0.481127
[ "MIT" ]
WildGums/Orc.Memento
src/Orc.Memento.Tests/MementoServiceFacts.cs
14,202
C#
using System.Threading.Tasks; using RetroClash.Extensions; using RetroClash.Logic; namespace RetroClash.Protocol.Messages.Server { public class AllianceCreateFailedMessage : Message { public AllianceCreateFailedMessage(Device device) : base(device) { Id = 24332; } // Error Codes: // 1 = Invalid Name // 2 = Invalid Description // 3 = Name to short public override async Task Encode() { await Stream.WriteIntAsync(1); } } }
22.625
72
0.598527
[ "BSD-3-Clause" ]
HiimEiffel/RetroClashv0.6
RetroClash/Protocol/Messages/Server/AllianceCreateFailedMessage.cs
545
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// ConsumingResourcesEntityListing /// </summary> [DataContract] public partial class ConsumingResourcesEntityListing : IEquatable<ConsumingResourcesEntityListing>, IPagedResource<Dependency> { /// <summary> /// Initializes a new instance of the <see cref="ConsumingResourcesEntityListing" /> class. /// </summary> /// <param name="Entities">Entities.</param> /// <param name="PageSize">PageSize.</param> /// <param name="PageNumber">PageNumber.</param> /// <param name="Total">Total.</param> /// <param name="FirstUri">FirstUri.</param> /// <param name="SelfUri">SelfUri.</param> /// <param name="NextUri">NextUri.</param> /// <param name="PreviousUri">PreviousUri.</param> /// <param name="LastUri">LastUri.</param> /// <param name="PageCount">PageCount.</param> public ConsumingResourcesEntityListing(List<Dependency> Entities = null, int? PageSize = null, int? PageNumber = null, long? Total = null, string FirstUri = null, string SelfUri = null, string NextUri = null, string PreviousUri = null, string LastUri = null, int? PageCount = null) { this.Entities = Entities; this.PageSize = PageSize; this.PageNumber = PageNumber; this.Total = Total; this.FirstUri = FirstUri; this.SelfUri = SelfUri; this.NextUri = NextUri; this.PreviousUri = PreviousUri; this.LastUri = LastUri; this.PageCount = PageCount; } /// <summary> /// Gets or Sets Entities /// </summary> [DataMember(Name="entities", EmitDefaultValue=false)] public List<Dependency> Entities { get; set; } /// <summary> /// Gets or Sets PageSize /// </summary> [DataMember(Name="pageSize", EmitDefaultValue=false)] public int? PageSize { get; set; } /// <summary> /// Gets or Sets PageNumber /// </summary> [DataMember(Name="pageNumber", EmitDefaultValue=false)] public int? PageNumber { get; set; } /// <summary> /// Gets or Sets Total /// </summary> [DataMember(Name="total", EmitDefaultValue=false)] public long? Total { get; set; } /// <summary> /// Gets or Sets FirstUri /// </summary> [DataMember(Name="firstUri", EmitDefaultValue=false)] public string FirstUri { get; set; } /// <summary> /// Gets or Sets SelfUri /// </summary> [DataMember(Name="selfUri", EmitDefaultValue=false)] public string SelfUri { get; set; } /// <summary> /// Gets or Sets NextUri /// </summary> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// Gets or Sets PreviousUri /// </summary> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { get; set; } /// <summary> /// Gets or Sets LastUri /// </summary> [DataMember(Name="lastUri", EmitDefaultValue=false)] public string LastUri { get; set; } /// <summary> /// Gets or Sets PageCount /// </summary> [DataMember(Name="pageCount", EmitDefaultValue=false)] public int? PageCount { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ConsumingResourcesEntityListing {\n"); sb.Append(" Entities: ").Append(Entities).Append("\n"); sb.Append(" PageSize: ").Append(PageSize).Append("\n"); sb.Append(" PageNumber: ").Append(PageNumber).Append("\n"); sb.Append(" Total: ").Append(Total).Append("\n"); sb.Append(" FirstUri: ").Append(FirstUri).Append("\n"); sb.Append(" SelfUri: ").Append(SelfUri).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append(" LastUri: ").Append(LastUri).Append("\n"); sb.Append(" PageCount: ").Append(PageCount).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ConsumingResourcesEntityListing); } /// <summary> /// Returns true if ConsumingResourcesEntityListing instances are equal /// </summary> /// <param name="other">Instance of ConsumingResourcesEntityListing to be compared</param> /// <returns>Boolean</returns> public bool Equals(ConsumingResourcesEntityListing other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Entities == other.Entities || this.Entities != null && this.Entities.SequenceEqual(other.Entities) ) && ( this.PageSize == other.PageSize || this.PageSize != null && this.PageSize.Equals(other.PageSize) ) && ( this.PageNumber == other.PageNumber || this.PageNumber != null && this.PageNumber.Equals(other.PageNumber) ) && ( this.Total == other.Total || this.Total != null && this.Total.Equals(other.Total) ) && ( this.FirstUri == other.FirstUri || this.FirstUri != null && this.FirstUri.Equals(other.FirstUri) ) && ( this.SelfUri == other.SelfUri || this.SelfUri != null && this.SelfUri.Equals(other.SelfUri) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ) && ( this.LastUri == other.LastUri || this.LastUri != null && this.LastUri.Equals(other.LastUri) ) && ( this.PageCount == other.PageCount || this.PageCount != null && this.PageCount.Equals(other.PageCount) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Entities != null) hash = hash * 59 + this.Entities.GetHashCode(); if (this.PageSize != null) hash = hash * 59 + this.PageSize.GetHashCode(); if (this.PageNumber != null) hash = hash * 59 + this.PageNumber.GetHashCode(); if (this.Total != null) hash = hash * 59 + this.Total.GetHashCode(); if (this.FirstUri != null) hash = hash * 59 + this.FirstUri.GetHashCode(); if (this.SelfUri != null) hash = hash * 59 + this.SelfUri.GetHashCode(); if (this.NextUri != null) hash = hash * 59 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 59 + this.PreviousUri.GetHashCode(); if (this.LastUri != null) hash = hash * 59 + this.LastUri.GetHashCode(); if (this.PageCount != null) hash = hash * 59 + this.PageCount.GetHashCode(); return hash; } } } }
31.414201
289
0.469392
[ "MIT" ]
seowleng/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/ConsumingResourcesEntityListing.cs
10,618
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.Batch.Models { /// <summary> The CertificateVisibility. </summary> public enum CertificateVisibility { /// <summary> The Certificate should be visible to the user account under which the StartTask is run. Note that if AutoUser Scope is Pool for both the StartTask and a Task, this certificate will be visible to the Task as well. </summary> StartTask, /// <summary> The Certificate should be visible to the user accounts under which Job Tasks are run. </summary> Task, /// <summary> The Certificate should be visible to the user accounts under which users remotely access the Compute Node. </summary> RemoteUser } }
39.714286
245
0.707434
[ "MIT" ]
Petermarcu/azure-sdk-for-net
sdk/batch/Microsoft.Azure.Batch/Azure.Batch/src/Generated/Models/CertificateVisibility.cs
834
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace SharpNet { class SharpRoomDetails { #region Variables private string roomName; private short maxConnection; private short currentConnnections; private short ping; private bool isSecured = false; private IPEndPoint connection; #endregion #region Public Vars public string RoomName { get { return this.roomName; } } public short CurrentConnectionsCount { get { return this.currentConnnections; } } public short MaxConnectionsCount { get { return this.maxConnection; } } public bool IsSecured { get { return this.isSecured; } } public short Ping { get { return this.ping; } } public IPEndPoint Connection { get { return this.connection; } } #endregion #region Main public SharpRoomDetails(SharpRoom room) { this.roomName = room.RoomName; this.maxConnection = room.MaxConnectionCount; this.currentConnnections = room.ClientCount; this.isSecured = room.isSecured; } public SharpRoomDetails(ref SharpSerializer ser) { Read(ref ser); } #endregion #region Functions public void Setup(short ping, IPEndPoint connection) { this.ping = ping; this.connection = connection; } #endregion #region Write/Read public void Write(ref SharpSerializer ser) { ser.Write(this.roomName); ser.Write(this.currentConnnections); ser.Write(this.maxConnection); ser.Write(this.isSecured); } private void Read(ref SharpSerializer ser) { this.roomName = ser.ReadString(); this.currentConnnections = ser.ReadInt16(); this.maxConnection = ser.ReadInt16(); this.isSecured = ser.ReadBool(); } #endregion } }
30.319444
90
0.581768
[ "Apache-2.0" ]
MrOkiDoki/SharpNetworking
SharpNet/Room/SharpRoomDetails.cs
2,185
C#
using System; namespace Codenesium.DataConversionExtensions { public static class ShortExtensions { public static short ToShort(this short obj) { return obj; } public static long ToNullableShort(this object obj) { if (obj == null) { return 0; } else { return ToShort(obj.ToString()); } } public static Nullable<long> ToShort(this Nullable<short> obj) { if (obj == null) { return null; } else { return Convert.ToInt16(obj); } } public static long ToShort(this string obj) { return ToNullableShort(obj) ?? 0; } public static Nullable<long> ToNullableShort(this string obj) { if (obj == null) { return null; } else { short result = 0; if (short.TryParse(obj, out result)) { return result; } else { return null; } } } } }
14.112903
64
0.590857
[ "MIT" ]
codenesium/DataConversionExtensions
DataConversionExtensions/ShortExtensions.cs
877
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace NotificationService.Contracts.Models { /// <summary> /// ValidationResult. /// </summary> public class ValidationResult { /// <summary> /// Gets or sets a value indicating whether this <see cref="ValidationResult"/> is result. /// </summary> /// <value> /// <c>true</c> if validation is successful; otherwise, <c>false</c>. /// </value> public bool Result { get; set; } /// <summary> /// Gets or sets the message. /// </summary> /// <value> /// The message. /// </value> public string Message { get; set; } } }
26.321429
98
0.535957
[ "MIT" ]
QPC-database/notification-provider
NotificationService/NotificationService.Contracts/Models/ValidationResult.cs
739
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace SFA.DAS.SharedOuterApi.Interfaces { public interface IGetAllApiClient<T> : IGetApiClient<T> { Task<IEnumerable<TResponse>> GetAll<TResponse>(IGetAllApiRequest request); } }
26.8
82
0.753731
[ "MIT" ]
SkillsFundingAgency/das-apim-endpoints
src/SFA.DAS.SharedOuterApi/Interfaces/IGetAllApiClient.cs
270
C#
using System; namespace Skender.Stock.Indicators { [Serializable] public class RocResult : ResultBase { public double? Roc { get; set; } public double? RocSma { get; set; } } [Serializable] public class RocWbResult : ResultBase { public double? Roc { get; set; } public double? RocEma { get; set; } public double? UpperBand { get; set; } public double? LowerBand { get; set; } } }
22.047619
46
0.587473
[ "Apache-2.0" ]
BlankaKorvo/Stock.Indicators
src/m-r/Roc/Roc.Models.cs
463
C#
using System; using NetOffice; namespace NetOffice.WordApi.Enums { /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15,16)] [EntityTypeAttribute(EntityType.IsEnum)] public enum WdHelpTypeHID { /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>0</remarks> [SupportByVersionAttribute("Word", 9,10,11,12,14,15,16)] emptyenum = 0 } }
25.473684
59
0.652893
[ "MIT" ]
brunobola/NetOffice
Source/Word/Enums/WdHelpTypeHID.cs
486
C#
/* * Copyright 2008-2013 Mohawk College of Applied Arts and Technology * * 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. * * User: Justin Fyfe * Date: 09-26-2011 **/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace gpmrw { /// <summary> /// Trace listener event arguments /// </summary> class TraceListenerEventArgs : EventArgs { /// <summary> /// The message that was raised /// </summary> public string Message { get; set; } } /// <summary> /// An event based trace listener /// </summary> class EventTraceListener : TraceListener { /// <summary> /// Fired when a message is raised /// </summary> public event EventHandler<TraceListenerEventArgs> MessageRaised; public override void Write(string message) { if (MessageRaised != null) MessageRaised(this, new TraceListenerEventArgs() { Message = String.Format("{0}", message) }); } public override void WriteLine(string message) { if (MessageRaised != null) MessageRaised(this, new TraceListenerEventArgs() { Message = String.Format("{0}\r\n", message) }); } } }
28.734375
114
0.635672
[ "Apache-2.0" ]
avjabalpur/ccd-generator
gpmr/gpmrw/EventTraceListener.cs
1,841
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using System.Reflection; using IronPython.Compiler; using IronPython.Hosting; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Hosting.Providers; namespace Scripting { public class ScriptManager { internal List<ScriptContents> Scripts = new List<ScriptContents>(); internal static ScriptEngine GetPythonEngine() { ScriptEngine engine = Python.CreateEngine(); // Make sure they have access to this API as an assembly engine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly()); // make sure they have access to CLR engine.Runtime.ImportModule("clr"); return engine; } private ScriptContents LoadScript(string scriptFile, ScriptEngine engine) { Register.Clear(); ScriptSource Source = engine.CreateScriptSourceFromString(GetScriptCode(scriptFile), SourceCodeKind.File); var code = Source.Compile(); var scope = engine.CreateScope(); code.Execute(scope); if (Register.RegisteredFunctionNames.Count > 0) { foreach (var regFunc in Register.RegisteredFunctionNames) { if (scope.ContainsVariable(regFunc.Value)) { scope.GetVariable(regFunc.Value); } } } return null; } internal static string GetScriptCode(string scriptFile) { FileInfo file = new FileInfo(scriptFile); if (!file.Exists) return null; FileStream fs = file.OpenRead(); StreamReader sr = new StreamReader(fs); StringBuilder builder = new StringBuilder(); // add standard imports builder.AppendLine("from Scripting import API"); builder.AppendLine("from Scripting import Register"); builder.AppendLine("import clr"); builder.Append(sr.ReadToEnd()); fs.Close(); return builder.ToString(); } } }
28.156627
118
0.59264
[ "MIT" ]
JeffM2501/BestMUD
Scripting/ScriptManager.cs
2,339
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Npgsql; namespace cfNetDemo.lib { public class persist { public static NpgsqlConnection client; //Postgre client public persist() { Connect(); } public void Initialize() { Console.WriteLine("Initializing DB"); //var query = "CREATE TABLE IF NOT EXISTS \"items\"(\"code\" varchar(256) NOT NULL, \"name\" varchar(256) NOT NULL, \"integrated\" boolean NOT NULL)"; var query = "CREATE TABLE IF NOT EXISTS items (code varchar(256) NOT NULL, name varchar(256) NOT NULL, integrated boolean NOT NULL)"; var createTableCmd = new NpgsqlCommand(query, client); client.Open(); createTableCmd.ExecuteNonQuery(); client.Close(); Console.WriteLine("DB Initialized"); } public static List<ItemDB> Select() { Console.WriteLine("Select DB records"); var query = "SELECT code, name, integrated FROM items where integrated = false"; var SelectTableCmd = new NpgsqlCommand(query, client); client.Open(); NpgsqlDataReader dr = SelectTableCmd.ExecuteReader(); Console.WriteLine("Recrods Selected"); List<ItemDB> rows = new List<ItemDB>(); ItemDB row; // Output rows while (dr.Read()) { Console.WriteLine("{0} \t {1}", dr[0], dr[1]); row = new ItemDB(dr[0].ToString(), dr[1].ToString(), Convert.ToBoolean(dr[2])); rows.Add(row); } client.Close(); return rows; } public static void Insert(string body) { /** Implement Item Insertion **/ } public void Update(string item) { /** Implement Item Update **/ } public void Connect() { Console.WriteLine("Retriving Cloud Foundry Services"); string dbServiceName = Environment.GetEnvironmentVariable("DB_SERVICE_NAME"); //postgresql string vcapServices = Environment.GetEnvironmentVariable("VCAP_SERVICES"); Console.WriteLine(vcapServices); // if DB is bound to the App on Cloud Foundry if (vcapServices != null) { dynamic json = JsonConvert.DeserializeObject(vcapServices); foreach (dynamic obj in json.Children()) { if (((string)obj.Name).ToLowerInvariant().Contains(dbServiceName)) { dynamic credentials = (((JProperty)obj).Value[0] as dynamic).credentials; //.Net connects to Postgre using a connection string and not the PG uri String connectionString = "User ID=" + credentials.username; connectionString += ";Password=" + credentials.password; connectionString += ";Host=" + credentials.hostname; connectionString += ";Port=" + credentials.port; connectionString += ";Database=" + credentials.dbname; connectionString += ";Pooling=true;"; Console.WriteLine("Connecting to DB on: " + connectionString); client = new NpgsqlConnection(connectionString); Console.WriteLine("Connected to the DB!"); Initialize(); } } } else { Console.WriteLine("Connecting to Local DB!"); client = new NpgsqlConnection("User ID=postgres;Password=a1b2c3;Host=localhost;Port=5432;Database=itemdb;Pooling=true;"); Console.WriteLine("Connected to the DB!"); Initialize(); } } public void Disconnect() { } } }
34.866667
162
0.534178
[ "MIT" ]
jonarranzATscl/SCL_SMBSummit19_HACKATON
cfNetDemo-SCL/lib/persist.cs
4,186
C#
using System.ComponentModel; using System.Diagnostics; using System.ServiceModel; namespace Esha.Genesis.Services.Client.Internal { [DebuggerStepThrough] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(IsWrapped = false)] public class NutrientListResponse1 { [MessageBodyMember(Namespace = "http://ns.esha.com/2013/genesisapi")] public NutrientListResponse NutrientListResponse; public NutrientListResponse1() { } public NutrientListResponse1(NutrientListResponse nutrientListResponse) => NutrientListResponse = nutrientListResponse; } }
30.047619
127
0.74168
[ "MIT" ]
esha/freyr
src/Esha.Genesis.Services.Client/Internal/NutrientListResponse1.cs
633
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006-2019, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications byMegaKraken, Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.490) // Version 5.490.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Text; using System.Windows.Forms; // ReSharper disable MemberCanBeInternal // ReSharper disable EventNeverSubscribedTo.Global namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Hosts a collection of KryptonDataGridViewTextBoxCell cells. /// </summary> [Designer(typeof(KryptonTextBoxColumnDesigner))] [ToolboxBitmap(typeof(KryptonDataGridViewTextBoxColumn), "ToolboxBitmaps.KryptonTextBox.bmp")] public class KryptonDataGridViewTextBoxColumn : KryptonDataGridViewIconColumn { #region Instance Fields #endregion #region Events /// <summary> /// Occurs when the user clicks a button spec. /// </summary> public event EventHandler<DataGridViewButtonSpecClickEventArgs> ButtonSpecClick; #endregion #region Identity /// <summary> /// Initialize a new instance of the KryptonDataGridViewTextBoxColumn class. /// </summary> public KryptonDataGridViewTextBoxColumn() : base(new KryptonDataGridViewTextBoxCell()) { ButtonSpecs = new DataGridViewColumnSpecCollection(this); SortMode = DataGridViewColumnSortMode.Automatic; } /// <summary> /// Returns a String that represents the current Object. /// </summary> /// <returns>A String that represents the current Object.</returns> public override string ToString() { StringBuilder builder = new StringBuilder(0x40); builder.Append("KryptonDataGridViewTextBoxColumn { Name="); // ReSharper disable RedundantBaseQualifier builder.Append(base.Name); builder.Append(", Index="); builder.Append(base.Index.ToString(CultureInfo.CurrentCulture)); // ReSharper restore RedundantBaseQualifier builder.Append(" }"); return builder.ToString(); } /// <summary> /// Create a cloned copy of the column. /// </summary> /// <returns></returns> public override object Clone() { KryptonDataGridViewTextBoxColumn cloned = base.Clone() as KryptonDataGridViewTextBoxColumn; // Move the button specs over to the new clone foreach (ButtonSpec bs in ButtonSpecs) { cloned.ButtonSpecs.Add(bs.Clone()); } cloned.Multiline = Multiline; cloned.MultilineStringEditor = MultilineStringEditor; return cloned; } /// <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) { } base.Dispose(disposing); } #endregion #region Public /// <summary> /// Gets or sets the maximum number of characters that can be entered into the text box. /// </summary> [Category("Behavior")] [DefaultValue(typeof(int), "32767")] public int MaxInputLength { get { if (TextBoxCellTemplate == null) { throw new InvalidOperationException("KryptonDataGridViewTextBoxColumn cell template required"); } return TextBoxCellTemplate.MaxInputLength; } set { if (MaxInputLength != value) { TextBoxCellTemplate.MaxInputLength = value; if (DataGridView != null) { DataGridViewRowCollection rows = DataGridView.Rows; int count = rows.Count; for (int i = 0; i < count; i++) { if (rows.SharedRow(i).Cells[Index] is DataGridViewTextBoxCell cell) { cell.MaxInputLength = value; } } } } } } /// <summary> /// Gets or sets the sort mode for the column. /// </summary> [DefaultValue(typeof(DataGridViewColumnSortMode), "Automatic")] public new DataGridViewColumnSortMode SortMode { get => base.SortMode; set => base.SortMode = value; } /// <summary> /// Gets or sets the template used to model cell appearance. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override DataGridViewCell CellTemplate { get => base.CellTemplate; set { if ((value != null) && !(value is KryptonDataGridViewTextBoxCell)) { throw new InvalidCastException("Can only assign a object of type KryptonDataGridViewTextBoxCell"); } base.CellTemplate = value; } } /// <summary> /// Gets the collection of the button specifications. /// </summary> [Category("Data")] [Description("Set of extra button specs to appear with control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DataGridViewColumnSpecCollection ButtonSpecs { get; } /// <summary> /// Replicates the Multiline property of the KryptonDataGridViewTextBoxCell cell type. /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("Indicates whether the text in the editing control can span more than one line.")] public bool Multiline { get { if (TextBoxCellTemplate == null) { throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); } return TextBoxCellTemplate.Multiline; } set { if (TextBoxCellTemplate == null) { throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); } TextBoxCellTemplate.Multiline = value; if (DataGridView != null) { DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); if (dataGridViewRow.Cells[Index] is KryptonDataGridViewTextBoxCell dataGridViewCell) { dataGridViewCell.SetMultiline(rowIndex, value); } } DataGridView.InvalidateColumn(Index); } } } /// <summary> /// Replicates the MultilineStringEditor property of the KryptonDataGridViewTextBoxCell cell type. /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("Indicates whether the editing control uses the multiline string editor widget.")] public bool MultilineStringEditor { get { if (TextBoxCellTemplate == null) { throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); } return TextBoxCellTemplate.MultilineStringEditor; } set { if (TextBoxCellTemplate == null) { throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); } TextBoxCellTemplate.MultilineStringEditor = value; if (DataGridView != null) { DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); if (dataGridViewRow.Cells[Index] is KryptonDataGridViewTextBoxCell dataGridViewCell) { dataGridViewCell.SetMultilineStringEditor(rowIndex, value); } } DataGridView.InvalidateColumn(Index); } } } #endregion #region Private private KryptonDataGridViewTextBoxCell TextBoxCellTemplate => (KryptonDataGridViewTextBoxCell)CellTemplate; #endregion #region Internal internal void PerformButtonSpecClick(DataGridViewButtonSpecClickEventArgs args) { ButtonSpecClick?.Invoke(this, args); } #endregion } }
37.407143
169
0.557476
[ "BSD-3-Clause" ]
Smurf-IV/Krypton-Toolkit-Suite-NET-Core
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Controls Toolkit/KryptonDataGridViewTextBoxColumn.cs
10,477
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Newtonsoft.Json; using ReaLTaiizor.Child.Crown; using ReaLTaiizor.Forms; using ReserveBlockWinWallet.Models; namespace ReserveBlockWinWallet { public partial class WalletForm : LostForm { public static Process proc = new Process(); public static string nodeURL; public static bool IsWalletSyncing = true; public static bool ShowWalletSyncMessage = true; public WalletForm() { InitializeComponent(); txSendAddressDropDown.SelectedItemChanged += delegate { txSendAddressDropDown_SelectedIndexChanged(txSendAddressDropDown.SelectedItem != null ? txSendAddressDropDown.SelectedItem.Text : "empty"); }; recAddressDropDownList.SelectedItemChanged += delegate { recAddressDropDownList_SelectedIndexChanged(recAddressDropDownList.SelectedItem != null ? recAddressDropDownList.SelectedItem.Text : "empty"); }; valiDropDownList.SelectedItemChanged += delegate { valiAddressDropDown_SelectedIndexChanged(valiDropDownList.SelectedItem != null ? valiDropDownList.SelectedItem.Text : "empty"); }; this.FormClosing += WalletForm_FormClosing; walletInfo.AppendText("RBX Wallet Started on " + DateTime.Now.ToString()); walletInfo.AppendText(Environment.NewLine); walletInfo.AppendText("Connecting to RBX Network."); //Perform connect to peers check walletInfo.AppendText(Environment.NewLine); walletInfo.AppendText("Connected. Looking for new blocks."); //Look for new blocks walletStartTimeDate.Text = DateTime.Now.ToString(); System.Threading.Timer walletRefresh = new System.Threading.Timer(walletRefresh_Elapsed); walletRefresh.Change(10000, 20000); try { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = Directory.GetCurrentDirectory() + @"\RBXCore\ReserveBlockCore.exe"; start.WindowStyle = ProcessWindowStyle.Hidden; //Hides GUI start.CreateNoWindow = true; //Hides console start.Arguments = "enableapi"; proc.StartInfo = start; proc.Start(); } catch (Exception ex) { MessageBox.Show("Could not find the RBX Core CLI. Please read the readme.txt in RBXCore folder"); } nodeURL = "http://localhost:7292"; //nodeURL = "https://localhost:7777";// testurl - not for production GetWalletOnline(); SetWalletInfo(); GetWalletAddresses(); GetWalletValidatorAddresses(); DashPrintWalletTransactions(); } delegate void SetTextCallback(Form form, Control ctrl, string text); public static void SetText(Form form, Control ctrl, string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (ctrl.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); form.Invoke(d, new object[] { form, ctrl, text }); } else { ctrl.Text = text; } } public static void SetTextAppend(Form form, Control ctrl, string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (ctrl.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetTextAppend); form.Invoke(d, new object[] { form, ctrl, text }); } else { ctrl.Text += text; } } private async void walletRefresh_Elapsed(object sender) { await SetWalletInfo(); await GetWalletValidatorAddresses(); await DashPrintWalletTransactions(); await UpdateBalance(); } #region Wallet Get Walelt Online public async Task GetWalletOnline() { string onlineStatus = "Offline"; dashboardMainBox.AppendText("Hello! Welcome to RBX Wallet."); while (onlineStatus == "Offline") { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/CheckStatus"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data == "Online") { onlineStatus = "Online"; } dashboardMainBox.AppendText(Environment.NewLine); dashboardMainBox.AppendText("RBX Wallet has conneted to local node."); dashboardMainBox.AppendText(Environment.NewLine); dashboardMainBox.AppendText("Your RBX wallet needs to sync. Please wait for sync before sending any transactions or validating."); } else { } } } } catch (Exception ex) { } } } #endregion #region Sets the Wallet Info public async Task SetWalletInfo() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetWalletInfo"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); var walInfo = data.Split(':'); var blockHeight = walInfo[0]; var peerCount = walInfo[1]; var walletSync = walInfo[2].ToLower(); if (walletSync == "true") { IsWalletSyncing = true; } else { IsWalletSyncing = false; if (ShowWalletSyncMessage == true) { ShowWalletSyncMessage = false; var walletSyncedText = Environment.NewLine + "Your wallet is now synced. Thank you for waiting."; SetTextAppend(this, dashboardMainBox, walletSyncedText); } } SetText(this, peerCountLabel, peerCount + " / 6"); SetText(this, blockHeightLabel, blockHeight); //peerCountLabel.Text = peerCount + " / 6"; //blockHeightLabel.Text = blockHeight; //dashboardMainBox.AppendText(Environment.NewLine); //dashboardMainBox.AppendText("Current Block Height is: " + blockHeight); //dashboardMainBox.AppendText(Environment.NewLine); //dashboardMainBox.AppendText("You are connected to -> " + peerCount + " <- peers."); } else { } } } } catch (Exception ex) { } } #endregion #region Update balance public async Task UpdateBalance() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetAllAddresses"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "No Accounts") { var accounts = JsonConvert.DeserializeObject<List<Account>>(data); var bal = accounts.Sum(x => x.Balance).ToString("0.00000000"); SetText(this, dashMainBalLabel, bal + " RBX"); } } else { } } } } catch (Exception ex) { } } #endregion #region Get the Wallet Addresses public async Task GetWalletAddresses() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetAllAddresses"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "No Accounts") { var accounts = JsonConvert.DeserializeObject<List<Account>>(data); accounts.ForEach(x => { var addr = new CrownDropDownItem(x.Address); //SetText(this, blockHeightLabel, blockHeight); txSendAddressDropDown.Items.Add(addr); recAddressDropDownList.Items.Add(addr); }); var bal = accounts.Sum(x => x.Balance).ToString("0.00000000"); SetText(this, dashMainBalLabel, bal + " RBX"); } } else { } } } } catch (Exception ex) { } } #endregion #region Get the Wallet Validator public async Task GetWalletValidatorAddresses() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetValidatorAddresses"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "No Accounts") { var accounts = JsonConvert.DeserializeObject<List<Account>>(data); accounts.ForEach(x => { valiDropDownList.Items.Clear(); var addr = new CrownDropDownItem(x.Address); valiDropDownList.Items.Add(addr); }); } } else { } } } } catch (Exception ex) { } } #endregion #region Get Validator Info public async Task<string> GetValidatorInfo(string address) { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetValidatorInfo/" + address; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); return data; } else { } } } } catch (Exception ex) { } return "Failed to get name"; } #endregion #region Turn ON validating public async Task<string> TurnValidatorOn(string address) { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/TurnOnValidator/" + address; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); return data; } else { } } } } catch (Exception ex) { } return "Failed - Wallet Core may be closed or crashed."; } #endregion #region Turn Off validating public async Task<string> TurnValidatorOff(string address) { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/TurnOffValidator/" + address; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); return data; } else { } } } } catch (Exception ex) { } return "Failed - Wallet Core may be closed or crashed."; } #endregion #region Get the Wallet Info public async Task<Account?> GetWalletInfo(string addr) { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetAddressInfo/" + addr; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "No Accounts") { var account = JsonConvert.DeserializeObject<Account>(data); return account; } } else { } } } } catch (Exception ex) { } return null; } #endregion #region Get New Address public async Task<string> GetNewAddress() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetNewAddress"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "Fail") { return data; } } else { } } } } catch (Exception ex) { } return "Fail"; } #endregion #region Get the Wallet Addresses public async Task DashPrintWalletAddresses() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetAllAddresses"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "No Accounts") { dashboardMainBox.Clear(); var accounts = JsonConvert.DeserializeObject<List<Account>>(data); accounts.ForEach(x => { dashboardMainBox.AppendText("Address : " + x.Address + " - Balance: " + x.Balance.ToString()); dashboardMainBox.AppendText(Environment.NewLine); }); } } else { } } } } catch (Exception ex) { } } #endregion #region Get the Wallet Transactions public async Task DashPrintWalletTransactions() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/GetAllTransactions"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "No Accounts") { //dashboardMainBox.Clear(); SetText(this, dashRecentTxBox, " "); var transactions = JsonConvert.DeserializeObject<List<Transaction>>(data); if (transactions != null) { transactions.OrderByDescending(x => x.Height).Take(20).ToList().ForEach(x => { var row = "From: " + x.FromAddress + Environment.NewLine + "To: " + x.ToAddress + Environment.NewLine + "Amount: " + x.Amount.ToString("0.00") + Environment.NewLine + "Height: " + x.Height.ToString() + Environment.NewLine + Environment.NewLine; SetTextAppend(this, dashRecentTxBox, row); }); transactionsGrid.DataSource = transactions.OrderByDescending(x => x.Height).ToList(); } } } else { } } } } catch (Exception ex) { } } #endregion #region Import Private Key public async Task<string> ImportPrivateKey(string privKey) { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/ImportPrivateKey/" + privKey; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); if (data != "NAC") { return data; } } else { } } } } catch (Exception ex) { } return "FAIL"; } #endregion #region Send TX Out public async Task<string> SendTxOut(string fromAddr, string toAddr, string amount) { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/SendTransaction/" + fromAddr + "/" + toAddr + "/" + amount; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); return data; } else { } } } } catch (Exception ex) { } return "FAIL"; } #endregion #region Start Validating public async Task<string> StartValidating(string addr, string uname) { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/StartValidating/" + addr + "/" + uname; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); return data; } else { } } } } catch (Exception ex) { } return "FAIL"; } #endregion #region Exit public async Task Exit() { try { using (HttpClient client = new HttpClient()) { string endpoint = nodeURL + "/api/V1/SendExit"; using (var Response = await client.GetAsync(endpoint)) { if (Response.StatusCode == System.Net.HttpStatusCode.OK) { string data = await Response.Content.ReadAsStringAsync(); } else { } } } } catch (Exception ex) { } } #endregion #region Drop down on change events private async void txSendAddressDropDown_SelectedIndexChanged(string item) { if (item != "empty") { var account = await GetWalletInfo(item); if (account != null) { SetText(this, txSendBalanceLabel, account.Balance.ToString() + " RBX"); } else { SetText(this, txSendBalanceLabel, "0.00" + " RBX"); } } } private async void recAddressDropDownList_SelectedIndexChanged(string item) { if (item != "empty") { var account = await GetWalletInfo(item); if (account != null) { SetText(this, recAddressLabel, account.Address); SetText(this, recBalance, account.Balance.ToString() + " RBX"); SetText(this, recValiFlag, account.IsValidating == true ? "Yes" : "No"); } else { } } } private async void valiAddressDropDown_SelectedIndexChanged(string item) { if (item != "empty") { var account = await GetWalletInfo(item); if (account != null) { var uName = await GetValidatorInfo(account.Address); SetText(this, skyLabel31, account.Address); SetText(this, skyLabel29, account.Balance.ToString() + " RBX"); SetText(this, skyLabel27, account.IsValidating == true ? "Yes" : "No"); SetText(this, skyLabel35, account.Balance >= 1000M ? "Yes" : "No"); SetText(this, valiNameLabel, uName); } else { } } } #endregion #region Wallet Form Closing Event private void WalletForm_FormClosing(object? sender, FormClosingEventArgs e) { Exit(); //proc.Kill(); //proc.Dispose(); } #endregion #region Move side panel options private void MoveSidePanel(Control c) { SidePanel.Height = c.Height; SidePanel.Top = c.Top; } private void dashBtn_Click(object sender, EventArgs e) { MoveSidePanel(dashBtn); foreverTabPage1.SelectedIndex = 0; } private void sendBtn_Click(object sender, EventArgs e) { MoveSidePanel(sendBtn); foreverTabPage1.SelectedIndex = 1; } private void recBtn_Click(object sender, EventArgs e) { MoveSidePanel(recBtn); foreverTabPage1.SelectedIndex = 2; } private void tranBtn_Click(object sender, EventArgs e) { MoveSidePanel(tranBtn); foreverTabPage1.SelectedIndex = 3; } private void valiBtn_Click(object sender, EventArgs e) { MoveSidePanel(valiBtn); foreverTabPage1.SelectedIndex = 4; } private void nftBtn_Click(object sender, EventArgs e) { MoveSidePanel(nftBtn); foreverTabPage1.SelectedIndex = 5; } #endregion #region Show dialong options public static string ShowDialog(string text, string caption) { Form prompt = new Form() { Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption, StartPosition = FormStartPosition.CenterScreen }; Label textLabel = new Label() { Left = 50, Top = 20, Text = text }; TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 }; Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 80, DialogResult = DialogResult.OK }; confirmation.Click += (sender, e) => { prompt.Close(); }; prompt.Controls.Add(textBox); prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.AcceptButton = confirmation; return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : ""; } public static string ShowDialogValidator(string text, string caption) { Form prompt = new Form() { Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption, StartPosition = FormStartPosition.CenterScreen }; Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Width = 300 }; TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 }; Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 80, DialogResult = DialogResult.OK }; confirmation.Click += (sender, e) => { prompt.Close(); }; prompt.Controls.Add(textBox); prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.AcceptButton = confirmation; return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : ""; } public static string ShowDialogValidatorWait(string text, string caption) { Form prompt = new Form() { Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption, StartPosition = FormStartPosition.CenterScreen }; Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Width = 300 }; prompt.Controls.Add(textLabel); return ""; } #endregion private async void lostAcceptButton5_Click(object sender, EventArgs e) { if (IsWalletSyncing == false) { DialogResult dialogResult = MessageBox.Show("Are you sure you want to send funds?", "Are you sure you want to send funds?", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { //do something var txFrom = txSendAddressDropDown.SelectedItem.Text; var txTo = sendToTextBox.Text; var amount = amountSendTextBox.Text; if (txFrom != "" && txTo != "" && amount != "") { var result = await SendTxOut(txFrom, txTo, amount); MessageBox.Show(result); } } else if (dialogResult == DialogResult.No) { //do something else } } else { MessageBox.Show("Wallet is currently syncing. Please wait for it to finish."); } } private async void recGetNewAddressBtn_Click(object sender, EventArgs e) { var data = await GetNewAddress(); var addrInfo = data.Split(':'); var nAddr = addrInfo[0]; var nPrivKey = addrInfo[1]; var post = new StringBuilder(); post.AppendLine("New Address Created!"); post.Append(Environment.NewLine); post.AppendLine("Public Address: " + nAddr); post.Append(Environment.NewLine); post.AppendLine("Private Key: " + nPrivKey); post.Append(Environment.NewLine); post.AppendLine("Please make a back up of your private key! If it is lost you cannot recover account."); post.Append(Environment.NewLine); post.AppendLine("Never share your private key with anyone else!"); post.Append(Environment.NewLine); post.AppendLine("Your private key has been copied to clipboard."); post.Append(Environment.NewLine); MessageBox.Show(post.ToString()); Clipboard.SetText(nPrivKey); var addr = new CrownDropDownItem(nAddr); txSendAddressDropDown.Items.Add(addr); recAddressDropDownList.Items.Add(addr); } private async void startValiBtn_Click(object sender, EventArgs e) { if (IsWalletSyncing == false) { var post = new StringBuilder(); if (valiDropDownList.SelectedItem == null) { MessageBox.Show("You must select an address!"); } else { var addr = valiDropDownList.SelectedItem.Text; if (addr != "") { var valResult = await TurnValidatorOn(addr); if (valResult != "STV") { MessageBox.Show(valResult); } else { string promptValue = ShowDialogValidator("Choose a Unique Name for your Masternode.", "Name your Masternode!"); if (promptValue != "") { DialogResult dialogResult = MessageBox.Show("Are you sure you want to activate masternode?", "Are you sure you?", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { //do something MessageBox.Show("You are now broadcoasting to node. Please do not close the wallet until you receive another confirmation box like this one."); var result = await StartValidating(addr, promptValue); MessageBox.Show(result); } else if (dialogResult == DialogResult.No) { //do something else } } } } } } else { MessageBox.Show("Wallet is currently syncing. Please wait for it to finish."); } } private async void dashPrintAllAddrBtn_Click(object sender, EventArgs e) { await DashPrintWalletAddresses(); } private void dashClearMainBtn_Click(object sender, EventArgs e) { dashboardMainBox.Clear(); } private void chatButtonRight1_Click(object sender, EventArgs e) { if (recAddressLabel.Text != "--" && recAddressLabel.Text.StartsWith("R")) { Clipboard.SetText(recAddressLabel.Text); MessageBox.Show("Address copied to clipboard."); } } private async void recImpPrvKey_Click(object sender, EventArgs e) { string promptValue = ShowDialog("Insert Private Key", "Import Private Key"); if (promptValue != "") { var data = await ImportPrivateKey(promptValue); if (data != "FAIL") { var account = JsonConvert.DeserializeObject<Account>(data); var message = "Account: " + account.Address + " imported."; MessageBox.Show(message); await SetWalletInfo(); await GetWalletValidatorAddresses(); await UpdateBalance(); var addr = new CrownDropDownItem(account.Address); txSendAddressDropDown.Items.Add(addr); recAddressDropDownList.Items.Add(addr); } } } //Turn Validator Off private async void lostCancelButton2_Click(object sender, EventArgs e) { if (IsWalletSyncing == false) { var post = new StringBuilder(); if (valiDropDownList.SelectedItem == null) { MessageBox.Show("You must select an address!"); } else { var addr = valiDropDownList.SelectedItem.Text; if (addr != "") { var valResult = await TurnValidatorOff(addr); MessageBox.Show(valResult); } } } } } }
34.363309
214
0.437611
[ "MIT" ]
ReserveBlockIO/ReserveBlockWindowsWallet
ReserveBlockWinWallet/WalletForm.cs
38,214
C#
//----------------------------------------------------------------------- // <copyright file="CloudBlobContainer.Common.cs" company="Microsoft"> // Copyright 2012 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Blob { using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Core; using Microsoft.WindowsAzure.Storage.Core.Auth; using Microsoft.WindowsAzure.Storage.Core.Util; using System; using System.Collections.Generic; using System.Globalization; /// <summary> /// Represents a container in the Windows Azure Blob service. /// </summary> public sealed partial class CloudBlobContainer { /// <summary> /// Initializes a new instance of the <see cref="CloudBlobContainer"/> class. /// </summary> /// <param name="containerAddress">The absolute URI to the container.</param> public CloudBlobContainer(Uri containerAddress) : this(containerAddress, null /* credentials */) { } /// <summary> /// Initializes a new instance of the <see cref="CloudBlobContainer"/> class. /// </summary> /// <param name="containerAddress">The absolute URI to the container.</param> /// <param name="credentials">The account credentials.</param> public CloudBlobContainer(Uri containerAddress, StorageCredentials credentials) { this.ParseQueryAndVerify(containerAddress, credentials); this.Metadata = new Dictionary<string, string>(); this.Properties = new BlobContainerProperties(); } /// <summary> /// Initializes a new instance of the <see cref="CloudBlobContainer"/> class. /// </summary> /// <param name="containerName">The container name.</param> /// <param name="serviceClient">A client object that specifies the endpoint for the Blob service.</param> internal CloudBlobContainer(string containerName, CloudBlobClient serviceClient) : this(new BlobContainerProperties(), new Dictionary<string, string>(), containerName, serviceClient) { } /// <summary> /// Initializes a new instance of the <see cref="CloudBlobContainer" /> class. /// </summary> /// <param name="properties">The properties.</param> /// <param name="metadata">The metadata.</param> /// <param name="containerName">The container name.</param> /// <param name="serviceClient">The client to be used.</param> internal CloudBlobContainer(BlobContainerProperties properties, IDictionary<string, string> metadata, string containerName, CloudBlobClient serviceClient) { this.Uri = NavigationHelper.AppendPathToUri(serviceClient.BaseUri, containerName); this.ServiceClient = serviceClient; this.Name = containerName; this.Metadata = metadata; this.Properties = properties; } /// <summary> /// Gets the service client for the container. /// </summary> /// <value>A client object that specifies the endpoint for the Blob service.</value> public CloudBlobClient ServiceClient { get; private set; } /// <summary> /// Gets the container's URI. /// </summary> /// <value>The absolute URI to the container.</value> public Uri Uri { get; private set; } /// <summary> /// Gets the name of the container. /// </summary> /// <value>The container's name.</value> public string Name { get; private set; } /// <summary> /// Gets the container's metadata. /// </summary> /// <value>The container's metadata.</value> public IDictionary<string, string> Metadata { get; private set; } /// <summary> /// Gets the container's system properties. /// </summary> /// <value>The container's properties.</value> public BlobContainerProperties Properties { get; private set; } /// <summary> /// Parse URI for SAS (Shared Access Signature) information. /// </summary> /// <param name="address">The complete Uri.</param> /// <param name="credentials">The credentials to use.</param> private void ParseQueryAndVerify(Uri address, StorageCredentials credentials) { StorageCredentials parsedCredentials; DateTimeOffset? parsedSnapshot; this.Uri = NavigationHelper.ParseBlobQueryAndVerify(address, out parsedCredentials, out parsedSnapshot); if ((parsedCredentials != null) && (credentials != null) && !parsedCredentials.Equals(credentials)) { string error = string.Format(CultureInfo.CurrentCulture, SR.MultipleCredentialsProvided); throw new ArgumentException(error); } this.ServiceClient = new CloudBlobClient(NavigationHelper.GetServiceClientBaseAddress(this.Uri, null /* usePathStyleUris */), credentials ?? parsedCredentials); this.Name = NavigationHelper.GetContainerNameFromContainerAddress(this.Uri, this.ServiceClient.UsePathStyleUris); } /// <summary> /// Returns the canonical name for shared access. /// </summary> /// <returns>The canonical name.</returns> private string GetSharedAccessCanonicalName() { if (this.ServiceClient.UsePathStyleUris) { return this.Uri.AbsolutePath; } else { return NavigationHelper.GetCanonicalPathFromCreds(this.ServiceClient.Credentials, this.Uri.AbsolutePath); } } /// <summary> /// Returns a shared access signature for the container. /// </summary> /// <param name="policy">The access policy for the shared access signature.</param> /// <returns>A shared access signature, as a URI query string.</returns> /// <remarks>The query string returned includes the leading question mark.</remarks> public string GetSharedAccessSignature(SharedAccessBlobPolicy policy) { return this.GetSharedAccessSignature(policy, null /* groupPolicyIdentifier */); } /// <summary> /// Returns a shared access signature for the container. /// </summary> /// <param name="policy">The access policy for the shared access signature.</param> /// <param name="groupPolicyIdentifier">A container-level access policy.</param> /// <returns>A shared access signature, as a URI query string.</returns> /// <remarks>The query string returned includes the leading question mark.</remarks> public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, string groupPolicyIdentifier) { if (!this.ServiceClient.Credentials.IsSharedKey) { string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey); throw new InvalidOperationException(errorMessage); } string resourceName = this.GetSharedAccessCanonicalName(); StorageAccountKey accountKey = this.ServiceClient.Credentials.Key; string signature = SharedAccessSignatureHelper.GetSharedAccessSignatureHashImpl(policy, groupPolicyIdentifier, resourceName, accountKey.KeyValue); string accountKeyName = accountKey.KeyName; // Future resource type changes from "c" => "container" UriQueryBuilder builder = SharedAccessSignatureHelper.GetSharedAccessSignatureImpl(policy, groupPolicyIdentifier, "c", signature, accountKeyName); return builder.ToString(); } /// <summary> /// Gets a reference to a page blob in this container. /// </summary> /// <param name="blobName">The name of the blob.</param> /// <returns>A reference to a page blob.</returns> public CloudPageBlob GetPageBlobReference(string blobName) { return this.GetPageBlobReference(blobName, null /* snapshotTime */); } /// <summary> /// Returns a reference to a page blob in this virtual directory. /// </summary> /// <param name="blobName">The name of the page blob.</param> /// <param name="snapshotTime">The snapshot timestamp, if the blob is a snapshot.</param> /// <returns>A reference to a page blob.</returns> public CloudPageBlob GetPageBlobReference(string blobName, DateTimeOffset? snapshotTime) { CommonUtility.AssertNotNullOrEmpty("blobName", blobName); return new CloudPageBlob(blobName, snapshotTime, this); } /// <summary> /// Gets a reference to a block blob in this container. /// </summary> /// <param name="blobName">The name of the blob.</param> /// <returns>A reference to a block blob.</returns> public CloudBlockBlob GetBlockBlobReference(string blobName) { return this.GetBlockBlobReference(blobName, null /* snapshotTime */); } /// <summary> /// Gets a reference to a block blob in this container. /// </summary> /// <param name="blobName">The name of the blob.</param> /// <param name="snapshotTime">The snapshot timestamp, if the blob is a snapshot.</param> /// <returns>A reference to a block blob.</returns> public CloudBlockBlob GetBlockBlobReference(string blobName, DateTimeOffset? snapshotTime) { CommonUtility.AssertNotNullOrEmpty("blobName", blobName); return new CloudBlockBlob(blobName, snapshotTime, this); } /// <summary> /// Gets a reference to a virtual blob directory beneath this container. /// </summary> /// <param name="relativeAddress">The name of the virtual blob directory.</param> /// <returns>A reference to a virtual blob directory.</returns> public CloudBlobDirectory GetDirectoryReference(string relativeAddress) { CommonUtility.AssertNotNullOrEmpty("relativeAddress", relativeAddress); Uri blobDirectoryUri = NavigationHelper.AppendPathToUri(this.Uri, relativeAddress); return new CloudBlobDirectory(blobDirectoryUri.AbsoluteUri, this); } } }
47.302905
173
0.619649
[ "Apache-2.0" ]
markcowl/azure-sdk-for-net
microsoft-azure-api/Services/Storage/Lib/Common/Blob/CloudBlobContainer.Common.cs
11,162
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AppointmentsIntersection")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AppointmentsIntersection")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("12d13ddb-df70-4ee3-9959-2bc5d32452b4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.405405
84
0.749472
[ "MIT" ]
mdyakov/HackBulgaria
02.WeekTwo/MethodsPartTwo/AppointmentsIntersection/Properties/AssemblyInfo.cs
1,424
C#
using UnityEngine; public class A : MonoBehaviour { [SerializeField] On{caret} [SerializeField] public int value; }
14
38
0.714286
[ "Apache-2.0" ]
20chan/resharper-unity
resharper/resharper-unity/test/data/CSharp/CodeCompletion/List/NoCompletionFollowingSerializeFieldAttribute03.cs
126
C#
using AkkoCore.Services.Database.Enums; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Converters; using DSharpPlus.Entities; using System; using System.Linq; using System.Threading.Tasks; namespace AkkoCore.Commands.ArgumentConverters; internal sealed class GuildLogConverter : IArgumentConverter<GuildLogType> { public Task<Optional<GuildLogType>> ConvertAsync(string input, CommandContext ctx) { var result = Enum.GetValues<GuildLogType>().FirstOrDefault(x => input.Equals(x.ToString(), StringComparison.InvariantCultureIgnoreCase)); return (result is GuildLogType.None) ? Task.FromResult(Optional.FromNoValue<GuildLogType>()) : Task.FromResult(Optional.FromValue(result)); } }
35.666667
145
0.766355
[ "Apache-2.0" ]
Akko-Bot/AkkoBot
AkkoCore/Commands/ArgumentConverters/GuildLogConverter.cs
749
C#
using System; class T { int x; public int this[int a, T b] { get { return a+x; } set { x=b.x=value; } } public T(int x) { this.x = x; } public void print() { Console.WriteLine("{0}", x); } static public void Main() { T a = new T(1), b = new T(10); a.print(); b.print(); Console.WriteLine("{0}", a[2,b]); a[2,b] = 20; a.print(); b.print(); Console.WriteLine("{0}", a[2,b]++); b.print(); a[2,b] += 5; a.print(); b.print(); } }
20.636364
53
0.522026
[ "MIT" ]
pmache/singularityrdk
SOURCE/base/Windows/csic/test/indexer.cs
454
C#
using System; using Newtonsoft.Json; namespace AL.Core.Json.Converters { /// <summary> /// Provides conversion logic specifically for Player.AFK /// </summary> /// <seealso cref="Newtonsoft.Json.JsonConverter{T}" /> public class AfkConverter : JsonConverter<bool> { public override bool ReadJson( JsonReader reader, Type objectType, bool existingValue, bool hasExistingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return false; return (reader.TokenType == JsonToken.String) || serializer.Deserialize<bool>(reader); } public override void WriteJson(JsonWriter writer, bool value, JsonSerializer serializer) => throw new NotImplementedException(); } }
30.714286
99
0.617442
[ "MIT" ]
Sichii/ALClientCS
AL.Core/Json/Converters/AfkConverter.cs
862
C#
using STS.Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace STS.Infrastructure.Persistence.Configurations { public class SupplierConfiguration : IEntityTypeConfiguration<Supplier> { public void Configure(EntityTypeBuilder<Supplier> builder) { builder.Property(e => e.SupplierId).HasColumnName("SupplierID"); builder.Property(e => e.Address).HasMaxLength(60); builder.Property(e => e.City).HasMaxLength(15); builder.Property(e => e.CompanyName) .IsRequired() .HasMaxLength(40); builder.Property(e => e.ContactName).HasMaxLength(30); builder.Property(e => e.ContactTitle).HasMaxLength(30); builder.Property(e => e.Country).HasMaxLength(15); builder.Property(e => e.Fax).HasMaxLength(24); builder.Property(e => e.HomePage).HasColumnType("ntext"); builder.Property(e => e.Phone).HasMaxLength(24); builder.Property(e => e.PostalCode).HasMaxLength(10); builder.Property(e => e.Region).HasMaxLength(15); } } }
30.692308
76
0.634085
[ "MIT" ]
mrgrayhat/CleanMicroserviceArchitecture
src/MicroServices/IdentityServer/Infrastructure/Persistence/Configurations/SupplierConfiguration.cs
1,199
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddObsoleteAttribute { internal abstract class AbstractAddObsoleteAttributeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { private readonly ISyntaxFacts _syntaxFacts; private readonly string _title; protected AbstractAddObsoleteAttributeCodeFixProvider( ISyntaxFacts syntaxFacts, string title) { _syntaxFacts = syntaxFacts; _title = title; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; var attribute = await GetObsoleteAttributeAsync(document, cancellationToken).ConfigureAwait(false); if (attribute == null) { return; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = context.Diagnostics[0].Location.FindNode(cancellationToken); var container = GetContainer(root, node); if (container == null) { return; } RegisterCodeFix(context, _title, _title); } private static async Task<INamedTypeSymbol?> GetObsoleteAttributeAsync(Document document, CancellationToken cancellationToken) { var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var attribute = compilation.GetTypeByMetadataName(typeof(ObsoleteAttribute).FullName!); return attribute; } private SyntaxNode? GetContainer(SyntaxNode root, SyntaxNode node) { return _syntaxFacts.GetContainingMemberDeclaration(root, node.SpanStart) ?? _syntaxFacts.GetContainingTypeDeclaration(root, node.SpanStart); } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CodeActionOptionsProvider options, CancellationToken cancellationToken) { var obsoleteAttribute = await GetObsoleteAttributeAsync(document, cancellationToken).ConfigureAwait(false); // RegisterCodeFixesAsync checked for null Contract.ThrowIfNull(obsoleteAttribute); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var containers = diagnostics.Select(d => GetContainer(root, d.Location.FindNode(cancellationToken))) .WhereNotNull() .ToSet(); var generator = editor.Generator; foreach (var container in containers) { editor.AddAttribute(container, generator.Attribute(editor.Generator.TypeExpression(obsoleteAttribute))); } } } }
38.010526
134
0.669067
[ "MIT" ]
AlexanderSemenyak/roslyn
src/Analyzers/Core/CodeFixes/AddObsoleteAttribute/AbstractAddObsoleteAttributeCodeFixProvider.cs
3,613
C#
namespace NjamiNjam { partial class FrmKreirajRacun { /// <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(FrmKreirajRacun)); this.txtPopust = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.cmbNacinPlacanja = new System.Windows.Forms.ComboBox(); this.gumbKreiraj = new System.Windows.Forms.Button(); this.gumbIzlaz = new System.Windows.Forms.Button(); this.dsAktivneNarudzbeDohvatiNacinPlacanja = new NjamiNjam.Properties.DataSources.dsAktivneNarudzbeDohvatiNacinPlacanja(); ((System.ComponentModel.ISupportInitialize)(this.dsAktivneNarudzbeDohvatiNacinPlacanja)).BeginInit(); this.SuspendLayout(); // // txtPopust // this.txtPopust.Location = new System.Drawing.Point(119, 9); this.txtPopust.Name = "txtPopust"; this.txtPopust.Size = new System.Drawing.Size(100, 20); this.txtPopust.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.label1.Location = new System.Drawing.Point(60, 10); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(53, 16); this.label1.TabIndex = 1; this.label1.Text = "Popust:"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.label2.Location = new System.Drawing.Point(12, 51); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(101, 16); this.label2.TabIndex = 2; this.label2.Text = "Način plaćanja:"; // // cmbNacinPlacanja // this.cmbNacinPlacanja.FormattingEnabled = true; this.cmbNacinPlacanja.Location = new System.Drawing.Point(119, 50); this.cmbNacinPlacanja.Name = "cmbNacinPlacanja"; this.cmbNacinPlacanja.Size = new System.Drawing.Size(121, 21); this.cmbNacinPlacanja.TabIndex = 3; // // gumbKreiraj // this.gumbKreiraj.BackColor = System.Drawing.Color.Maroon; this.gumbKreiraj.ForeColor = System.Drawing.SystemColors.ButtonFace; this.gumbKreiraj.Location = new System.Drawing.Point(38, 89); this.gumbKreiraj.Name = "gumbKreiraj"; this.gumbKreiraj.Size = new System.Drawing.Size(78, 32); this.gumbKreiraj.TabIndex = 4; this.gumbKreiraj.Text = "Kreiraj"; this.gumbKreiraj.UseVisualStyleBackColor = false; this.gumbKreiraj.Click += new System.EventHandler(this.gumbKreiraj_Click); // // gumbIzlaz // this.gumbIzlaz.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.gumbIzlaz.ForeColor = System.Drawing.SystemColors.ButtonHighlight; this.gumbIzlaz.Location = new System.Drawing.Point(154, 89); this.gumbIzlaz.Name = "gumbIzlaz"; this.gumbIzlaz.Size = new System.Drawing.Size(86, 32); this.gumbIzlaz.TabIndex = 5; this.gumbIzlaz.Text = "Izlaz"; this.gumbIzlaz.UseVisualStyleBackColor = false; this.gumbIzlaz.Click += new System.EventHandler(this.gumbIzlaz_Click); // // dsAktivneNarudzbeDohvatiNacinPlacanja // this.dsAktivneNarudzbeDohvatiNacinPlacanja.DataSetName = "dsAktivneNarudzbeDohvatiNacinPlacanja"; this.dsAktivneNarudzbeDohvatiNacinPlacanja.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // FrmKreirajRacun // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.AppWorkspace; this.ClientSize = new System.Drawing.Size(264, 133); this.Controls.Add(this.gumbIzlaz); this.Controls.Add(this.gumbKreiraj); this.Controls.Add(this.cmbNacinPlacanja); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtPopust); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FrmKreirajRacun"; this.Text = "Kreiraj račun"; this.Load += new System.EventHandler(this.FrmKreirajRacun_Load); ((System.ComponentModel.ISupportInitialize)(this.dsAktivneNarudzbeDohvatiNacinPlacanja)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtPopust; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cmbNacinPlacanja; private System.Windows.Forms.Button gumbKreiraj; private System.Windows.Forms.Button gumbIzlaz; private Properties.DataSources.dsAktivneNarudzbeDohvatiNacinPlacanja dsAktivneNarudzbeDohvatiNacinPlacanja; } }
48.427536
170
0.613347
[ "MIT" ]
mmacinkov/Restaurant
NjamiNjam/NjamiNjam/NjamiNjam/FrmKreirajRacun.Designer.cs
6,688
C#
using System; using System.Threading.Tasks; using Orleans; using Orleans.Indexing; namespace UnitTests.GrainInterfaces { [Serializable] public class Player5PropertiesNonFaultTolerantLazy : PlayerProperties { [Index(typeof(ActiveHashIndexSingleBucket<string, IPlayer5GrainNonFaultTolerantLazy>)/*, IsEager: false*/, IsUnique: true)] public int Score { get; set; } [Index(typeof(ActiveHashIndexPartitionedPerKey<string, IPlayer5GrainNonFaultTolerantLazy>)/*, IsEager: false*/, IsUnique: true)] public string Location { get; set; } } public interface IPlayer5GrainNonFaultTolerantLazy : IPlayerGrain, IIndexableGrain<Player5PropertiesNonFaultTolerantLazy> { } }
32.818182
136
0.750693
[ "MIT" ]
OrleansContrib/Orleans.Indexing-1.5
test/TestGrainInterfaces/IPlayer5rainNonFaultTolerantLazy.cs
722
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Syncfusion.SfChart.XForms; namespace Sensus.Probes.Movement { public abstract class MagnetometerProbe : ListeningProbe { public override string DisplayName { get { return "Magnetism"; } } public override Type DatumType { get { return typeof(MagnetometerDatum); } } public override double? MaxDataStoresPerSecond { get => base.MaxDataStoresPerSecond; set => base.MaxDataStoresPerSecond = value; } public override string CollectionDescription => base.CollectionDescription; protected override bool DefaultKeepDeviceAwake { get { return true; } } protected override string DeviceAwakeWarning { get { return "Devices will use additional power to report all updates."; } } protected override string DeviceAsleepWarning { get { return "Devices will sleep and pause updates."; } } protected override bool WillHaveSignificantNegativeImpactOnBattery => base.WillHaveSignificantNegativeImpactOnBattery; protected override double RawParticipation => base.RawParticipation; protected override long DataRateSampleSize => base.DataRateSampleSize; public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override Task ProcessDataAsync(CancellationToken cancellationToken) { return base.ProcessDataAsync(cancellationToken); } public override Task ResetAsync() { return base.ResetAsync(); } public override Task<HealthTestResult> TestHealthAsync(List<AnalyticsTrackedEvent> events) { return base.TestHealthAsync(events); } public override string ToString() { return base.ToString(); } protected override ChartDataPoint GetChartDataPointFromDatum(Datum datum) { throw new NotImplementedException(); } protected override ChartAxis GetChartPrimaryAxis() { throw new NotImplementedException(); } protected override RangeAxisBase GetChartSecondaryAxis() { throw new NotImplementedException(); } protected override ChartSeries GetChartSeries() { throw new NotImplementedException(); } protected override Task InitializeAsync() { return base.InitializeAsync(); } protected override Task ProtectedStartAsync() { return base.ProtectedStartAsync(); } protected override Task ProtectedStopAsync() { return base.ProtectedStopAsync(); } protected override Task StartListeningAsync() { return base.StartListeningAsync(); } protected override Task StopListeningAsync() { return base.StopListeningAsync(); } } }
25.825758
138
0.595189
[ "Apache-2.0" ]
TeachmanLab/sensus
Sensus.Shared/Probes/Movement/MagnetometerProbe.cs
3,411
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace DapperDino.Areas.HappyToHelp.Controllers { [Route("/HappyToHelp/Ticket")] public class TicketController : BaseController { [Route("")] public IActionResult Index() { return View(); } } }
21.5
50
0.658915
[ "MIT" ]
DapperCoding/DapperDino-Website
DapperDino.Web/Areas/HappyToHelp/Controllers/TicketController.cs
389
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Design", "RCS1102:Make class static.", Justification = "<Pending>", Scope = "type", Target = "~T:TSF.Apps.Cross.iOS.Application")]
49.666667
158
0.756152
[ "Apache-2.0" ]
TheSharpFactory/samples
sources/Applications/Cross-Platform/Linux/iOS.Blazor/GlobalSuppressions.cs
449
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace lab_48_business_search { using System; using System.Collections.Generic; public partial class Territory { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Territory() { this.Employees = new HashSet<Employee>(); } public string TerritoryID { get; set; } public string TerritoryDescription { get; set; } public int RegionID { get; set; } public virtual Region Region { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Employee> Employees { get; set; } } }
37.5
128
0.586667
[ "MIT" ]
ajohnson96/2019-06-c-sharp-labs
labs/lab_48_business_search/Territory.cs
1,200
C#
using System; using System.Text; using Elastic.Installer.Domain.Configuration.Service; using Elastic.Installer.Domain.Configuration.Wix; using Elastic.Installer.Domain.Model.Base; using Elastic.Installer.Domain.Model.Base.Service; using Elastic.Installer.Domain.Model.Elasticsearch.Locations; using Elastic.Installer.Domain.Model.Elasticsearch.XPack; using Elastic.Installer.Domain.Properties; using ReactiveUI; using Semver; namespace Elastic.Installer.Domain.Model.Elasticsearch.Notice { public class NoticeModel : StepBase<NoticeModel, NoticeModelValidator> { private readonly IServiceStateProvider _serviceStateProvider; public NoticeModel( VersionConfiguration versionConfig, IServiceStateProvider serviceStateProvider, LocationsModel locationsModel, ServiceModel serviceModel ) { this.IsRelevant = versionConfig.ExistingVersionInstalled; this.LocationsModel = locationsModel; this.ServiceModel = serviceModel; this.Header = "Notice"; this.ExistingVersion = versionConfig.UpgradeFromVersion; this.CurrentVersion = versionConfig.CurrentVersion; this.ReadMoreOnUpgrades = ReactiveCommand.Create(); this.ReadMoreOnXPackOpening = ReactiveCommand.Create(); this._serviceStateProvider = serviceStateProvider; this.Refresh(); if (!string.IsNullOrWhiteSpace(this.CurrentVersion?.Prerelease)) { if (versionConfig.ExistingVersionInstalled) { this.UpgradeTextHeader = TextResources.NoticeModel_ToPrerelease_Header; this.UpgradeText = TextResources.NoticeModel_ToPrerelease; } else { this.UpgradeTextHeader = TextResources.NoticeModel_Prerelease_Header; this.UpgradeText = TextResources.NoticeModel_Prerelease; } this.IsRelevant = true; //show prerelease notice always } else if (!string.IsNullOrWhiteSpace(this.ExistingVersion?.Prerelease)) { this.UpgradeTextHeader = TextResources.NoticeModel_FromPrerelease_Header; this.UpgradeText = TextResources.NoticeModel_FromPrerelease; this.IsRelevant = true; //show prerelease notice always } else { var v = Enum.GetName(typeof(VersionChange), versionConfig.VersionChange); var d = Enum.GetName(typeof(InstallationDirection), versionConfig.InstallationDirection); var prefix = nameof(NoticeModel) + "_" + v + d; this.UpgradeTextHeader = TextResources.ResourceManager.GetString(prefix + "_Header"); this.UpgradeText = TextResources.ResourceManager.GetString(prefix); } if (!string.IsNullOrWhiteSpace(this.UpgradeTextHeader)) this.UpgradeTextHeader = string.Format(this.UpgradeTextHeader, versionConfig.UpgradeFromVersion, versionConfig.CurrentVersion); this.ShowOpeningXPackBanner = this.ExistingVersion < XPackModel.XPackInstalledByDefaultVersion; this.ShowUpgradeDocumentationLink = versionConfig.VersionChange == VersionChange.Major || versionConfig.VersionChange == VersionChange.Minor; this.ExistingVersionInstalled = versionConfig.ExistingVersionInstalled; if (!ExistingVersionInstalled) this.UpgradingFrom6OrNewInstallation = true; else this.UpgradingFrom6OrNewInstallation = versionConfig.UpgradeFromVersion.Major < 7; } bool showUpgradeDocumentationLink; public bool ShowUpgradeDocumentationLink { get => showUpgradeDocumentationLink; private set => this.RaiseAndSetIfChanged(ref showUpgradeDocumentationLink, value); } bool showOpeningXPackBanner; public bool ShowOpeningXPackBanner { get => showOpeningXPackBanner; private set => this.RaiseAndSetIfChanged(ref showOpeningXPackBanner, value); } bool? existingVersionInstalled; public bool ExistingVersionInstalled { get => existingVersionInstalled.GetValueOrDefault(); private set => this.RaiseAndSetIfChanged(ref existingVersionInstalled, value); } bool? upgradingFrom6OrNewInstallation; public bool UpgradingFrom6OrNewInstallation { get => upgradingFrom6OrNewInstallation.GetValueOrDefault(); private set => this.RaiseAndSetIfChanged(ref upgradingFrom6OrNewInstallation, value); } public sealed override void Refresh() { if (ExistingVersionInstalled && this.ServiceModel.PreviouslyInstalledAsAService) this.ServiceModel.StartAfterInstall = true; } public ServiceModel ServiceModel { get; } public LocationsModel LocationsModel { get; } public SemVersion CurrentVersion { get; } public SemVersion ExistingVersion { get; } public string UpgradeTextHeader { get; } public string UpgradeText { get; } public ReactiveCommand<object> ReadMoreOnUpgrades { get; } public ReactiveCommand<object> ReadMoreOnXPackOpening { get; } public override string ToString() { var sb = new StringBuilder(); sb.AppendLine(nameof(NoticeModel)); sb.AppendLine($"- {nameof(CurrentVersion)} = {CurrentVersion}"); sb.AppendLine($"- {nameof(ExistingVersion)} = {ExistingVersion}"); sb.AppendLine($"- {nameof(ExistingVersionInstalled)} = {ExistingVersionInstalled}"); sb.AppendLine($"- {nameof(IsValid)} = {IsValid}"); return sb.ToString(); } } }
37.864662
144
0.778197
[ "Apache-2.0" ]
elastic/windows-installers
src/Installer/Elastic.Installer.Domain/Model/Elasticsearch/Notice/NoticeModel.cs
5,038
C#
using System; using System.Threading; using System.Threading.Tasks; using AutoMapper; using MediatR; using Microsoft.Extensions.Logging; using Ordering.Application.Contracts.Infrustructure; using Ordering.Application.Contracts.Persistence; using Ordering.Application.Models; using Ordering.Domain.Entities; namespace Ordering.Application.Features.Orders.Commands.ChecoutOrder { public class CheckoutOrderCommandHandler : IRequestHandler<CheckoutOrderCommand, int> { private readonly IMapper _mapper; private readonly IOrderRepository _orderRepository; private readonly IEmailServices _emailServices; private readonly ILogger<CheckoutOrderCommandHandler> _logger; public CheckoutOrderCommandHandler(IOrderRepository orderRepository, IMapper mapper, IEmailServices emailServices, ILogger<CheckoutOrderCommandHandler> logger) { _emailServices = emailServices; _orderRepository = orderRepository; _mapper = mapper; _logger = logger; } public async Task<int> Handle(CheckoutOrderCommand request, CancellationToken cancellationToken) { var orderEntity = _mapper.Map<Order>(request); var newOrder = await _orderRepository.AddAsync(orderEntity); _logger.LogInformation($"Order {newOrder.Id} is succesfully created."); await SendEmail(newOrder); return newOrder.Id; } private async Task SendEmail(Order order) { var email = new Email() { To = "orizvida@gmail.com", Body = "Order succesfully made", Subject = "Order succesfully made" }; try { await _emailServices.SendEmail(email); } catch (Exception ex) { _logger.LogError($"Order {order.Id} had error being created : ${ex.Message}"); } } } }
35.696429
167
0.648824
[ "MIT" ]
orizvida/AspnetMicroservices
src/Services/Ordering/Ordering.Application/Features/Orders/Commands/ChecoutOrder/CheckoutOrderCommandHandler.cs
1,999
C#
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// EmailSegmentCustomersResponse /// </summary> [DataContract] public partial class EmailSegmentCustomersResponse : IEquatable<EmailSegmentCustomersResponse>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="EmailSegmentCustomersResponse" /> class. /// </summary> /// <param name="customers">Customers on the page.</param> /// <param name="pageNumber">Page number (one based offset).</param> /// <param name="pageSize">Number of records per page.</param> /// <param name="totalCustomers">Total customers.</param> /// <param name="totalPages">Total number of pages.</param> public EmailSegmentCustomersResponse(List<EmailSegmentCustomer> customers = default(List<EmailSegmentCustomer>), int? pageNumber = default(int?), int? pageSize = default(int?), int? totalCustomers = default(int?), int? totalPages = default(int?)) { this.Customers = customers; this.PageNumber = pageNumber; this.PageSize = pageSize; this.TotalCustomers = totalCustomers; this.TotalPages = totalPages; } /// <summary> /// Customers on the page /// </summary> /// <value>Customers on the page</value> [DataMember(Name="customers", EmitDefaultValue=false)] public List<EmailSegmentCustomer> Customers { get; set; } /// <summary> /// Page number (one based offset) /// </summary> /// <value>Page number (one based offset)</value> [DataMember(Name="page_number", EmitDefaultValue=false)] public int? PageNumber { get; set; } /// <summary> /// Number of records per page /// </summary> /// <value>Number of records per page</value> [DataMember(Name="page_size", EmitDefaultValue=false)] public int? PageSize { get; set; } /// <summary> /// Total customers /// </summary> /// <value>Total customers</value> [DataMember(Name="total_customers", EmitDefaultValue=false)] public int? TotalCustomers { get; set; } /// <summary> /// Total number of pages /// </summary> /// <value>Total number of pages</value> [DataMember(Name="total_pages", EmitDefaultValue=false)] public int? TotalPages { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class EmailSegmentCustomersResponse {\n"); sb.Append(" Customers: ").Append(Customers).Append("\n"); sb.Append(" PageNumber: ").Append(PageNumber).Append("\n"); sb.Append(" PageSize: ").Append(PageSize).Append("\n"); sb.Append(" TotalCustomers: ").Append(TotalCustomers).Append("\n"); sb.Append(" TotalPages: ").Append(TotalPages).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as EmailSegmentCustomersResponse); } /// <summary> /// Returns true if EmailSegmentCustomersResponse instances are equal /// </summary> /// <param name="input">Instance of EmailSegmentCustomersResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(EmailSegmentCustomersResponse input) { if (input == null) return false; return ( this.Customers == input.Customers || this.Customers != null && this.Customers.SequenceEqual(input.Customers) ) && ( this.PageNumber == input.PageNumber || (this.PageNumber != null && this.PageNumber.Equals(input.PageNumber)) ) && ( this.PageSize == input.PageSize || (this.PageSize != null && this.PageSize.Equals(input.PageSize)) ) && ( this.TotalCustomers == input.TotalCustomers || (this.TotalCustomers != null && this.TotalCustomers.Equals(input.TotalCustomers)) ) && ( this.TotalPages == input.TotalPages || (this.TotalPages != null && this.TotalPages.Equals(input.TotalPages)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Customers != null) hashCode = hashCode * 59 + this.Customers.GetHashCode(); if (this.PageNumber != null) hashCode = hashCode * 59 + this.PageNumber.GetHashCode(); if (this.PageSize != null) hashCode = hashCode * 59 + this.PageSize.GetHashCode(); if (this.TotalCustomers != null) hashCode = hashCode * 59 + this.TotalCustomers.GetHashCode(); if (this.TotalPages != null) hashCode = hashCode * 59 + this.TotalPages.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
38
254
0.564976
[ "Apache-2.0" ]
UltraCart/rest_api_v2_sdk_csharp
src/com.ultracart.admin.v2/Model/EmailSegmentCustomersResponse.cs
7,372
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Graphite.NET")] [assembly: AssemblyDescription(".NET client library for Graphite")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ragnar Dahlén")] [assembly: AssemblyProduct("Graphite.NET")] [assembly: AssemblyCopyright("Copyright © Ragnar Dahlén")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("675c24c5-d0b9-436a-8eac-aa48394b5ab7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
39.189189
84
0.748966
[ "BSD-2-Clause" ]
ragnard/Graphite.NET
Graphite/Properties/AssemblyInfo.cs
1,455
C#
// $ANTLR 3.3.0.7239 C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g 2011-08-08 11:08:01 // The variable 'variable' is assigned but its value is never used. #pragma warning disable 219 // Unreachable code detected. #pragma warning disable 162 using System.Text; using System.Globalization; using System.Collections.Generic; using NCalc.Domain; using System; using Antlr.Runtime; using Stack = System.Collections.Generic.Stack<object>; using List = System.Collections.IList; using ArrayList = System.Collections.Generic.List<object>; using Antlr.Runtime.Tree; using RewriteRuleITokenStream = Antlr.Runtime.Tree.RewriteRuleTokenStream; [System.CodeDom.Compiler.GeneratedCode("ANTLR", "3.3.0.7239")] [System.CLSCompliant(false)] public partial class NCalcParser : Antlr.Runtime.Parser { internal static readonly string[] tokenNames = new string[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "DATETIME", "DIGIT", "E", "EscapeSequence", "FALSE", "FLOAT", "HexDigit", "ID", "INTEGER", "LETTER", "NAME", "STRING", "TRUE", "UnicodeEscape", "WS", "'!'", "'!='", "'%'", "'&&'", "'&'", "'('", "')'", "'*'", "'+'", "','", "'-'", "'/'", "':'", "'<'", "'<<'", "'<='", "'<>'", "'='", "'=='", "'>'", "'>='", "'>>'", "'?'", "'^'", "'and'", "'not'", "'or'", "'|'", "'||'", "'~'" }; public const int EOF=-1; public const int DATETIME=4; public const int DIGIT=5; public const int E=6; public const int EscapeSequence=7; public const int FALSE=8; public const int FLOAT=9; public const int HexDigit=10; public const int ID=11; public const int INTEGER=12; public const int LETTER=13; public const int NAME=14; public const int STRING=15; public const int TRUE=16; public const int UnicodeEscape=17; public const int WS=18; public const int T__19=19; public const int T__20=20; public const int T__21=21; public const int T__22=22; public const int T__23=23; public const int T__24=24; public const int T__25=25; public const int T__26=26; public const int T__27=27; public const int T__28=28; public const int T__29=29; public const int T__30=30; public const int T__31=31; public const int T__32=32; public const int T__33=33; public const int T__34=34; public const int T__35=35; public const int T__36=36; public const int T__37=37; public const int T__38=38; public const int T__39=39; public const int T__40=40; public const int T__41=41; public const int T__42=42; public const int T__43=43; public const int T__44=44; public const int T__45=45; public const int T__46=46; public const int T__47=47; public const int T__48=48; // delegates // delegators #if ANTLR_DEBUG private static readonly bool[] decisionCanBacktrack = new bool[] { false, // invalid decision false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; #else private static readonly bool[] decisionCanBacktrack = new bool[0]; #endif public NCalcParser( ITokenStream input ) : this( input, new RecognizerSharedState() ) { } public NCalcParser(ITokenStream input, RecognizerSharedState state) : base(input, state) { ITreeAdaptor treeAdaptor = null; CreateTreeAdaptor(ref treeAdaptor); TreeAdaptor = treeAdaptor ?? new CommonTreeAdaptor(); OnCreated(); } // Implement this function in your helper file to use a custom tree adaptor partial void CreateTreeAdaptor(ref ITreeAdaptor adaptor); private ITreeAdaptor adaptor; public ITreeAdaptor TreeAdaptor { get { return adaptor; } set { this.adaptor = value; } } public override string[] TokenNames { get { return NCalcParser.tokenNames; } } public override string GrammarFileName { get { return "C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g"; } } private const char BS = '\\'; private static NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); private string extractString(string text) { StringBuilder sb = new StringBuilder(text); int startIndex = 1; // Skip initial quote int slashIndex = -1; while ((slashIndex = sb.ToString().IndexOf(BS, startIndex)) != -1) { char escapeType = sb[slashIndex + 1]; switch (escapeType) { case 'u': string hcode = String.Concat(sb[slashIndex+4], sb[slashIndex+5]); string lcode = String.Concat(sb[slashIndex+2], sb[slashIndex+3]); char unicodeChar = Encoding.Unicode.GetChars(new byte[] { System.Convert.ToByte(hcode, 16), System.Convert.ToByte(lcode, 16)} )[0]; sb.Remove(slashIndex, 6).Insert(slashIndex, unicodeChar); break; case 'n': sb.Remove(slashIndex, 2).Insert(slashIndex, '\n'); break; case 'r': sb.Remove(slashIndex, 2).Insert(slashIndex, '\r'); break; case 't': sb.Remove(slashIndex, 2).Insert(slashIndex, '\t'); break; case '\'': sb.Remove(slashIndex, 2).Insert(slashIndex, '\''); break; case '\\': sb.Remove(slashIndex, 2).Insert(slashIndex, '\\'); break; default: throw new RecognitionException("Unvalid escape sequence: \\" + escapeType); } startIndex = slashIndex + 1; } sb.Remove(0, 1); sb.Remove(sb.Length - 1, 1); return sb.ToString(); } public List<string> Errors { get; private set; } public override void DisplayRecognitionError(String[] tokenNames, RecognitionException e) { base.DisplayRecognitionError(tokenNames, e); if(Errors == null) { Errors = new List<string>(); } String hdr = GetErrorHeader(e); String msg = GetErrorMessage(e, tokenNames); Errors.Add(msg + " at " + hdr); } partial void OnCreated(); partial void EnterRule(string ruleName, int ruleIndex); partial void LeaveRule(string ruleName, int ruleIndex); #region Rules public class ncalcExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_ncalcExpression(); partial void Leave_ncalcExpression(); // $ANTLR start "ncalcExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:77:1: ncalcExpression returns [LogicalExpression value] : logicalExpression EOF ; [GrammarRule("ncalcExpression")] public NCalcParser.ncalcExpression_return ncalcExpression() { Enter_ncalcExpression(); EnterRule("ncalcExpression", 1); TraceIn("ncalcExpression", 1); NCalcParser.ncalcExpression_return retval = new NCalcParser.ncalcExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken EOF2=null; NCalcParser.logicalExpression_return logicalExpression1 = default(NCalcParser.logicalExpression_return); CommonTree EOF2_tree=null; try { DebugEnterRule(GrammarFileName, "ncalcExpression"); DebugLocation(77, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:78:2: ( logicalExpression EOF ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:78:4: logicalExpression EOF { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(78, 4); PushFollow(Follow._logicalExpression_in_ncalcExpression56); logicalExpression1=logicalExpression(); PopFollow(); adaptor.AddChild(root_0, logicalExpression1.Tree); DebugLocation(78, 25); EOF2=(IToken)Match(input,EOF,Follow._EOF_in_ncalcExpression58); DebugLocation(78, 27); retval.value = (logicalExpression1!=null?logicalExpression1.value:default(LogicalExpression)); } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("ncalcExpression", 1); LeaveRule("ncalcExpression", 1); Leave_ncalcExpression(); } DebugLocation(79, 1); } finally { DebugExitRule(GrammarFileName, "ncalcExpression"); } return retval; } // $ANTLR end "ncalcExpression" public class logicalExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_logicalExpression(); partial void Leave_logicalExpression(); // $ANTLR start "logicalExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:81:1: logicalExpression returns [LogicalExpression value] : left= conditionalExpression ( '?' middle= conditionalExpression ':' right= conditionalExpression )? ; [GrammarRule("logicalExpression")] private NCalcParser.logicalExpression_return logicalExpression() { Enter_logicalExpression(); EnterRule("logicalExpression", 2); TraceIn("logicalExpression", 2); NCalcParser.logicalExpression_return retval = new NCalcParser.logicalExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal3=null; IToken char_literal4=null; NCalcParser.conditionalExpression_return left = default(NCalcParser.conditionalExpression_return); NCalcParser.conditionalExpression_return middle = default(NCalcParser.conditionalExpression_return); NCalcParser.conditionalExpression_return right = default(NCalcParser.conditionalExpression_return); CommonTree char_literal3_tree=null; CommonTree char_literal4_tree=null; try { DebugEnterRule(GrammarFileName, "logicalExpression"); DebugLocation(81, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:82:2: (left= conditionalExpression ( '?' middle= conditionalExpression ':' right= conditionalExpression )? ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:82:4: left= conditionalExpression ( '?' middle= conditionalExpression ':' right= conditionalExpression )? { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(82, 8); PushFollow(Follow._conditionalExpression_in_logicalExpression78); left=conditionalExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(82, 31); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(82, 57); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:82:57: ( '?' middle= conditionalExpression ':' right= conditionalExpression )? int alt1=2; try { DebugEnterSubRule(1); try { DebugEnterDecision(1, decisionCanBacktrack[1]); int LA1_0 = input.LA(1); if ((LA1_0==41)) { alt1=1; } } finally { DebugExitDecision(1); } switch (alt1) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:82:59: '?' middle= conditionalExpression ':' right= conditionalExpression { DebugLocation(82, 59); char_literal3=(IToken)Match(input,41,Follow._41_in_logicalExpression84); char_literal3_tree = (CommonTree)adaptor.Create(char_literal3); adaptor.AddChild(root_0, char_literal3_tree); DebugLocation(82, 69); PushFollow(Follow._conditionalExpression_in_logicalExpression88); middle=conditionalExpression(); PopFollow(); adaptor.AddChild(root_0, middle.Tree); DebugLocation(82, 92); char_literal4=(IToken)Match(input,31,Follow._31_in_logicalExpression90); char_literal4_tree = (CommonTree)adaptor.Create(char_literal4); adaptor.AddChild(root_0, char_literal4_tree); DebugLocation(82, 101); PushFollow(Follow._conditionalExpression_in_logicalExpression94); right=conditionalExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(82, 124); retval.value = new TernaryExpression((left!=null?left.value:default(LogicalExpression)), (middle!=null?middle.value:default(LogicalExpression)), (right!=null?right.value:default(LogicalExpression))); } break; } } finally { DebugExitSubRule(1); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("logicalExpression", 2); LeaveRule("logicalExpression", 2); Leave_logicalExpression(); } DebugLocation(83, 1); } finally { DebugExitRule(GrammarFileName, "logicalExpression"); } return retval; } // $ANTLR end "logicalExpression" public class conditionalExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_conditionalExpression(); partial void Leave_conditionalExpression(); // $ANTLR start "conditionalExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:85:1: conditionalExpression returns [LogicalExpression value] : left= booleanAndExpression ( ( '||' | 'or' ) right= conditionalExpression )* ; [GrammarRule("conditionalExpression")] private NCalcParser.conditionalExpression_return conditionalExpression() { Enter_conditionalExpression(); EnterRule("conditionalExpression", 3); TraceIn("conditionalExpression", 3); NCalcParser.conditionalExpression_return retval = new NCalcParser.conditionalExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken set5=null; NCalcParser.booleanAndExpression_return left = default(NCalcParser.booleanAndExpression_return); NCalcParser.conditionalExpression_return right = default(NCalcParser.conditionalExpression_return); CommonTree set5_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "conditionalExpression"); DebugLocation(85, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:89:2: (left= booleanAndExpression ( ( '||' | 'or' ) right= conditionalExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:89:4: left= booleanAndExpression ( ( '||' | 'or' ) right= conditionalExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(89, 8); PushFollow(Follow._booleanAndExpression_in_conditionalExpression121); left=booleanAndExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(89, 30); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(89, 56); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:89:56: ( ( '||' | 'or' ) right= conditionalExpression )* try { DebugEnterSubRule(2); while (true) { int alt2=2; try { DebugEnterDecision(2, decisionCanBacktrack[2]); int LA2_0 = input.LA(1); if ((LA2_0==45||LA2_0==47)) { alt2=1; } } finally { DebugExitDecision(2); } switch ( alt2 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:90:4: ( '||' | 'or' ) right= conditionalExpression { DebugLocation(90, 4); set5=(IToken)input.LT(1); if (input.LA(1)==45||input.LA(1)==47) { input.Consume(); adaptor.AddChild(root_0, (CommonTree)adaptor.Create(set5)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); throw mse; } DebugLocation(90, 18); type = BinaryExpressionType.Or; DebugLocation(91, 9); PushFollow(Follow._conditionalExpression_in_conditionalExpression146); right=conditionalExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(91, 32); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop2; } } loop2: ; } finally { DebugExitSubRule(2); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("conditionalExpression", 3); LeaveRule("conditionalExpression", 3); Leave_conditionalExpression(); } DebugLocation(93, 1); } finally { DebugExitRule(GrammarFileName, "conditionalExpression"); } return retval; } // $ANTLR end "conditionalExpression" public class booleanAndExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_booleanAndExpression(); partial void Leave_booleanAndExpression(); // $ANTLR start "booleanAndExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:95:1: booleanAndExpression returns [LogicalExpression value] : left= bitwiseOrExpression ( ( '&&' | 'and' ) right= bitwiseOrExpression )* ; [GrammarRule("booleanAndExpression")] private NCalcParser.booleanAndExpression_return booleanAndExpression() { Enter_booleanAndExpression(); EnterRule("booleanAndExpression", 4); TraceIn("booleanAndExpression", 4); NCalcParser.booleanAndExpression_return retval = new NCalcParser.booleanAndExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken set6=null; NCalcParser.bitwiseOrExpression_return left = default(NCalcParser.bitwiseOrExpression_return); NCalcParser.bitwiseOrExpression_return right = default(NCalcParser.bitwiseOrExpression_return); CommonTree set6_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "booleanAndExpression"); DebugLocation(95, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:99:2: (left= bitwiseOrExpression ( ( '&&' | 'and' ) right= bitwiseOrExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:99:4: left= bitwiseOrExpression ( ( '&&' | 'and' ) right= bitwiseOrExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(99, 8); PushFollow(Follow._bitwiseOrExpression_in_booleanAndExpression180); left=bitwiseOrExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(99, 29); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(99, 55); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:99:55: ( ( '&&' | 'and' ) right= bitwiseOrExpression )* try { DebugEnterSubRule(3); while (true) { int alt3=2; try { DebugEnterDecision(3, decisionCanBacktrack[3]); int LA3_0 = input.LA(1); if ((LA3_0==22||LA3_0==43)) { alt3=1; } } finally { DebugExitDecision(3); } switch ( alt3 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:100:4: ( '&&' | 'and' ) right= bitwiseOrExpression { DebugLocation(100, 4); set6=(IToken)input.LT(1); if (input.LA(1)==22||input.LA(1)==43) { input.Consume(); adaptor.AddChild(root_0, (CommonTree)adaptor.Create(set6)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); throw mse; } DebugLocation(100, 19); type = BinaryExpressionType.And; DebugLocation(101, 9); PushFollow(Follow._bitwiseOrExpression_in_booleanAndExpression205); right=bitwiseOrExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(101, 30); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop3; } } loop3: ; } finally { DebugExitSubRule(3); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("booleanAndExpression", 4); LeaveRule("booleanAndExpression", 4); Leave_booleanAndExpression(); } DebugLocation(103, 1); } finally { DebugExitRule(GrammarFileName, "booleanAndExpression"); } return retval; } // $ANTLR end "booleanAndExpression" public class bitwiseOrExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_bitwiseOrExpression(); partial void Leave_bitwiseOrExpression(); // $ANTLR start "bitwiseOrExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:105:1: bitwiseOrExpression returns [LogicalExpression value] : left= bitwiseXOrExpression ( '|' right= bitwiseOrExpression )* ; [GrammarRule("bitwiseOrExpression")] private NCalcParser.bitwiseOrExpression_return bitwiseOrExpression() { Enter_bitwiseOrExpression(); EnterRule("bitwiseOrExpression", 5); TraceIn("bitwiseOrExpression", 5); NCalcParser.bitwiseOrExpression_return retval = new NCalcParser.bitwiseOrExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal7=null; NCalcParser.bitwiseXOrExpression_return left = default(NCalcParser.bitwiseXOrExpression_return); NCalcParser.bitwiseOrExpression_return right = default(NCalcParser.bitwiseOrExpression_return); CommonTree char_literal7_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "bitwiseOrExpression"); DebugLocation(105, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:109:2: (left= bitwiseXOrExpression ( '|' right= bitwiseOrExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:109:4: left= bitwiseXOrExpression ( '|' right= bitwiseOrExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(109, 8); PushFollow(Follow._bitwiseXOrExpression_in_bitwiseOrExpression237); left=bitwiseXOrExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(109, 30); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(109, 56); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:109:56: ( '|' right= bitwiseOrExpression )* try { DebugEnterSubRule(4); while (true) { int alt4=2; try { DebugEnterDecision(4, decisionCanBacktrack[4]); int LA4_0 = input.LA(1); if ((LA4_0==46)) { alt4=1; } } finally { DebugExitDecision(4); } switch ( alt4 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:110:4: '|' right= bitwiseOrExpression { DebugLocation(110, 4); char_literal7=(IToken)Match(input,46,Follow._46_in_bitwiseOrExpression246); char_literal7_tree = (CommonTree)adaptor.Create(char_literal7); adaptor.AddChild(root_0, char_literal7_tree); DebugLocation(110, 8); type = BinaryExpressionType.BitwiseOr; DebugLocation(111, 9); PushFollow(Follow._bitwiseOrExpression_in_bitwiseOrExpression256); right=bitwiseOrExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(111, 30); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop4; } } loop4: ; } finally { DebugExitSubRule(4); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("bitwiseOrExpression", 5); LeaveRule("bitwiseOrExpression", 5); Leave_bitwiseOrExpression(); } DebugLocation(113, 1); } finally { DebugExitRule(GrammarFileName, "bitwiseOrExpression"); } return retval; } // $ANTLR end "bitwiseOrExpression" public class bitwiseXOrExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_bitwiseXOrExpression(); partial void Leave_bitwiseXOrExpression(); // $ANTLR start "bitwiseXOrExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:115:1: bitwiseXOrExpression returns [LogicalExpression value] : left= bitwiseAndExpression ( '^' right= bitwiseAndExpression )* ; [GrammarRule("bitwiseXOrExpression")] private NCalcParser.bitwiseXOrExpression_return bitwiseXOrExpression() { Enter_bitwiseXOrExpression(); EnterRule("bitwiseXOrExpression", 6); TraceIn("bitwiseXOrExpression", 6); NCalcParser.bitwiseXOrExpression_return retval = new NCalcParser.bitwiseXOrExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal8=null; NCalcParser.bitwiseAndExpression_return left = default(NCalcParser.bitwiseAndExpression_return); NCalcParser.bitwiseAndExpression_return right = default(NCalcParser.bitwiseAndExpression_return); CommonTree char_literal8_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "bitwiseXOrExpression"); DebugLocation(115, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:119:2: (left= bitwiseAndExpression ( '^' right= bitwiseAndExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:119:4: left= bitwiseAndExpression ( '^' right= bitwiseAndExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(119, 8); PushFollow(Follow._bitwiseAndExpression_in_bitwiseXOrExpression290); left=bitwiseAndExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(119, 30); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(119, 56); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:119:56: ( '^' right= bitwiseAndExpression )* try { DebugEnterSubRule(5); while (true) { int alt5=2; try { DebugEnterDecision(5, decisionCanBacktrack[5]); int LA5_0 = input.LA(1); if ((LA5_0==42)) { alt5=1; } } finally { DebugExitDecision(5); } switch ( alt5 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:120:4: '^' right= bitwiseAndExpression { DebugLocation(120, 4); char_literal8=(IToken)Match(input,42,Follow._42_in_bitwiseXOrExpression299); char_literal8_tree = (CommonTree)adaptor.Create(char_literal8); adaptor.AddChild(root_0, char_literal8_tree); DebugLocation(120, 8); type = BinaryExpressionType.BitwiseXOr; DebugLocation(121, 9); PushFollow(Follow._bitwiseAndExpression_in_bitwiseXOrExpression309); right=bitwiseAndExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(121, 31); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop5; } } loop5: ; } finally { DebugExitSubRule(5); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("bitwiseXOrExpression", 6); LeaveRule("bitwiseXOrExpression", 6); Leave_bitwiseXOrExpression(); } DebugLocation(123, 1); } finally { DebugExitRule(GrammarFileName, "bitwiseXOrExpression"); } return retval; } // $ANTLR end "bitwiseXOrExpression" public class bitwiseAndExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_bitwiseAndExpression(); partial void Leave_bitwiseAndExpression(); // $ANTLR start "bitwiseAndExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:125:1: bitwiseAndExpression returns [LogicalExpression value] : left= equalityExpression ( '&' right= equalityExpression )* ; [GrammarRule("bitwiseAndExpression")] private NCalcParser.bitwiseAndExpression_return bitwiseAndExpression() { Enter_bitwiseAndExpression(); EnterRule("bitwiseAndExpression", 7); TraceIn("bitwiseAndExpression", 7); NCalcParser.bitwiseAndExpression_return retval = new NCalcParser.bitwiseAndExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal9=null; NCalcParser.equalityExpression_return left = default(NCalcParser.equalityExpression_return); NCalcParser.equalityExpression_return right = default(NCalcParser.equalityExpression_return); CommonTree char_literal9_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "bitwiseAndExpression"); DebugLocation(125, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:129:2: (left= equalityExpression ( '&' right= equalityExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:129:4: left= equalityExpression ( '&' right= equalityExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(129, 8); PushFollow(Follow._equalityExpression_in_bitwiseAndExpression341); left=equalityExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(129, 28); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(129, 54); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:129:54: ( '&' right= equalityExpression )* try { DebugEnterSubRule(6); while (true) { int alt6=2; try { DebugEnterDecision(6, decisionCanBacktrack[6]); int LA6_0 = input.LA(1); if ((LA6_0==23)) { alt6=1; } } finally { DebugExitDecision(6); } switch ( alt6 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:130:4: '&' right= equalityExpression { DebugLocation(130, 4); char_literal9=(IToken)Match(input,23,Follow._23_in_bitwiseAndExpression350); char_literal9_tree = (CommonTree)adaptor.Create(char_literal9); adaptor.AddChild(root_0, char_literal9_tree); DebugLocation(130, 8); type = BinaryExpressionType.BitwiseAnd; DebugLocation(131, 9); PushFollow(Follow._equalityExpression_in_bitwiseAndExpression360); right=equalityExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(131, 29); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop6; } } loop6: ; } finally { DebugExitSubRule(6); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("bitwiseAndExpression", 7); LeaveRule("bitwiseAndExpression", 7); Leave_bitwiseAndExpression(); } DebugLocation(133, 1); } finally { DebugExitRule(GrammarFileName, "bitwiseAndExpression"); } return retval; } // $ANTLR end "bitwiseAndExpression" public class equalityExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_equalityExpression(); partial void Leave_equalityExpression(); // $ANTLR start "equalityExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:135:1: equalityExpression returns [LogicalExpression value] : left= relationalExpression ( ( ( '==' | '=' ) | ( '!=' | '<>' ) ) right= relationalExpression )* ; [GrammarRule("equalityExpression")] private NCalcParser.equalityExpression_return equalityExpression() { Enter_equalityExpression(); EnterRule("equalityExpression", 8); TraceIn("equalityExpression", 8); NCalcParser.equalityExpression_return retval = new NCalcParser.equalityExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken set10=null; IToken set11=null; NCalcParser.relationalExpression_return left = default(NCalcParser.relationalExpression_return); NCalcParser.relationalExpression_return right = default(NCalcParser.relationalExpression_return); CommonTree set10_tree=null; CommonTree set11_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "equalityExpression"); DebugLocation(135, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:139:2: (left= relationalExpression ( ( ( '==' | '=' ) | ( '!=' | '<>' ) ) right= relationalExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:139:4: left= relationalExpression ( ( ( '==' | '=' ) | ( '!=' | '<>' ) ) right= relationalExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(139, 8); PushFollow(Follow._relationalExpression_in_equalityExpression394); left=relationalExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(139, 30); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(139, 56); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:139:56: ( ( ( '==' | '=' ) | ( '!=' | '<>' ) ) right= relationalExpression )* try { DebugEnterSubRule(8); while (true) { int alt8=2; try { DebugEnterDecision(8, decisionCanBacktrack[8]); int LA8_0 = input.LA(1); if ((LA8_0==20||(LA8_0>=35 && LA8_0<=37))) { alt8=1; } } finally { DebugExitDecision(8); } switch ( alt8 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:140:4: ( ( '==' | '=' ) | ( '!=' | '<>' ) ) right= relationalExpression { DebugLocation(140, 4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:140:4: ( ( '==' | '=' ) | ( '!=' | '<>' ) ) int alt7=2; try { DebugEnterSubRule(7); try { DebugEnterDecision(7, decisionCanBacktrack[7]); int LA7_0 = input.LA(1); if (((LA7_0>=36 && LA7_0<=37))) { alt7=1; } else if ((LA7_0==20||LA7_0==35)) { alt7=2; } else { NoViableAltException nvae = new NoViableAltException("", 7, 0, input); DebugRecognitionException(nvae); throw nvae; } } finally { DebugExitDecision(7); } switch (alt7) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:140:6: ( '==' | '=' ) { DebugLocation(140, 6); set10=(IToken)input.LT(1); if ((input.LA(1)>=36 && input.LA(1)<=37)) { input.Consume(); adaptor.AddChild(root_0, (CommonTree)adaptor.Create(set10)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); throw mse; } DebugLocation(140, 20); type = BinaryExpressionType.Equal; } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:141:6: ( '!=' | '<>' ) { DebugLocation(141, 6); set11=(IToken)input.LT(1); if (input.LA(1)==20||input.LA(1)==35) { input.Consume(); adaptor.AddChild(root_0, (CommonTree)adaptor.Create(set11)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); throw mse; } DebugLocation(141, 21); type = BinaryExpressionType.NotEqual; } break; } } finally { DebugExitSubRule(7); } DebugLocation(142, 9); PushFollow(Follow._relationalExpression_in_equalityExpression441); right=relationalExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(142, 31); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop8; } } loop8: ; } finally { DebugExitSubRule(8); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("equalityExpression", 8); LeaveRule("equalityExpression", 8); Leave_equalityExpression(); } DebugLocation(144, 1); } finally { DebugExitRule(GrammarFileName, "equalityExpression"); } return retval; } // $ANTLR end "equalityExpression" public class relationalExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_relationalExpression(); partial void Leave_relationalExpression(); // $ANTLR start "relationalExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:146:1: relationalExpression returns [LogicalExpression value] : left= shiftExpression ( ( '<' | '<=' | '>' | '>=' ) right= shiftExpression )* ; [GrammarRule("relationalExpression")] private NCalcParser.relationalExpression_return relationalExpression() { Enter_relationalExpression(); EnterRule("relationalExpression", 9); TraceIn("relationalExpression", 9); NCalcParser.relationalExpression_return retval = new NCalcParser.relationalExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal12=null; IToken string_literal13=null; IToken char_literal14=null; IToken string_literal15=null; NCalcParser.shiftExpression_return left = default(NCalcParser.shiftExpression_return); NCalcParser.shiftExpression_return right = default(NCalcParser.shiftExpression_return); CommonTree char_literal12_tree=null; CommonTree string_literal13_tree=null; CommonTree char_literal14_tree=null; CommonTree string_literal15_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "relationalExpression"); DebugLocation(146, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:150:2: (left= shiftExpression ( ( '<' | '<=' | '>' | '>=' ) right= shiftExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:150:4: left= shiftExpression ( ( '<' | '<=' | '>' | '>=' ) right= shiftExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(150, 8); PushFollow(Follow._shiftExpression_in_relationalExpression474); left=shiftExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(150, 25); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(150, 51); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:150:51: ( ( '<' | '<=' | '>' | '>=' ) right= shiftExpression )* try { DebugEnterSubRule(10); while (true) { int alt10=2; try { DebugEnterDecision(10, decisionCanBacktrack[10]); int LA10_0 = input.LA(1); if ((LA10_0==32||LA10_0==34||(LA10_0>=38 && LA10_0<=39))) { alt10=1; } } finally { DebugExitDecision(10); } switch ( alt10 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:151:4: ( '<' | '<=' | '>' | '>=' ) right= shiftExpression { DebugLocation(151, 4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:151:4: ( '<' | '<=' | '>' | '>=' ) int alt9=4; try { DebugEnterSubRule(9); try { DebugEnterDecision(9, decisionCanBacktrack[9]); switch (input.LA(1)) { case 32: { alt9=1; } break; case 34: { alt9=2; } break; case 38: { alt9=3; } break; case 39: { alt9=4; } break; default: { NoViableAltException nvae = new NoViableAltException("", 9, 0, input); DebugRecognitionException(nvae); throw nvae; } } } finally { DebugExitDecision(9); } switch (alt9) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:151:6: '<' { DebugLocation(151, 6); char_literal12=(IToken)Match(input,32,Follow._32_in_relationalExpression485); char_literal12_tree = (CommonTree)adaptor.Create(char_literal12); adaptor.AddChild(root_0, char_literal12_tree); DebugLocation(151, 10); type = BinaryExpressionType.Lesser; } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:152:6: '<=' { DebugLocation(152, 6); string_literal13=(IToken)Match(input,34,Follow._34_in_relationalExpression495); string_literal13_tree = (CommonTree)adaptor.Create(string_literal13); adaptor.AddChild(root_0, string_literal13_tree); DebugLocation(152, 11); type = BinaryExpressionType.LesserOrEqual; } break; case 3: DebugEnterAlt(3); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:153:6: '>' { DebugLocation(153, 6); char_literal14=(IToken)Match(input,38,Follow._38_in_relationalExpression506); char_literal14_tree = (CommonTree)adaptor.Create(char_literal14); adaptor.AddChild(root_0, char_literal14_tree); DebugLocation(153, 10); type = BinaryExpressionType.Greater; } break; case 4: DebugEnterAlt(4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:154:6: '>=' { DebugLocation(154, 6); string_literal15=(IToken)Match(input,39,Follow._39_in_relationalExpression516); string_literal15_tree = (CommonTree)adaptor.Create(string_literal15); adaptor.AddChild(root_0, string_literal15_tree); DebugLocation(154, 11); type = BinaryExpressionType.GreaterOrEqual; } break; } } finally { DebugExitSubRule(9); } DebugLocation(155, 9); PushFollow(Follow._shiftExpression_in_relationalExpression528); right=shiftExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(155, 26); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop10; } } loop10: ; } finally { DebugExitSubRule(10); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("relationalExpression", 9); LeaveRule("relationalExpression", 9); Leave_relationalExpression(); } DebugLocation(157, 1); } finally { DebugExitRule(GrammarFileName, "relationalExpression"); } return retval; } // $ANTLR end "relationalExpression" public class shiftExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_shiftExpression(); partial void Leave_shiftExpression(); // $ANTLR start "shiftExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:159:1: shiftExpression returns [LogicalExpression value] : left= additiveExpression ( ( '<<' | '>>' ) right= additiveExpression )* ; [GrammarRule("shiftExpression")] private NCalcParser.shiftExpression_return shiftExpression() { Enter_shiftExpression(); EnterRule("shiftExpression", 10); TraceIn("shiftExpression", 10); NCalcParser.shiftExpression_return retval = new NCalcParser.shiftExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken string_literal16=null; IToken string_literal17=null; NCalcParser.additiveExpression_return left = default(NCalcParser.additiveExpression_return); NCalcParser.additiveExpression_return right = default(NCalcParser.additiveExpression_return); CommonTree string_literal16_tree=null; CommonTree string_literal17_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "shiftExpression"); DebugLocation(159, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:163:2: (left= additiveExpression ( ( '<<' | '>>' ) right= additiveExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:163:4: left= additiveExpression ( ( '<<' | '>>' ) right= additiveExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(163, 8); PushFollow(Follow._additiveExpression_in_shiftExpression560); left=additiveExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(163, 28); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(163, 54); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:163:54: ( ( '<<' | '>>' ) right= additiveExpression )* try { DebugEnterSubRule(12); while (true) { int alt12=2; try { DebugEnterDecision(12, decisionCanBacktrack[12]); int LA12_0 = input.LA(1); if ((LA12_0==33||LA12_0==40)) { alt12=1; } } finally { DebugExitDecision(12); } switch ( alt12 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:164:4: ( '<<' | '>>' ) right= additiveExpression { DebugLocation(164, 4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:164:4: ( '<<' | '>>' ) int alt11=2; try { DebugEnterSubRule(11); try { DebugEnterDecision(11, decisionCanBacktrack[11]); int LA11_0 = input.LA(1); if ((LA11_0==33)) { alt11=1; } else if ((LA11_0==40)) { alt11=2; } else { NoViableAltException nvae = new NoViableAltException("", 11, 0, input); DebugRecognitionException(nvae); throw nvae; } } finally { DebugExitDecision(11); } switch (alt11) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:164:6: '<<' { DebugLocation(164, 6); string_literal16=(IToken)Match(input,33,Follow._33_in_shiftExpression571); string_literal16_tree = (CommonTree)adaptor.Create(string_literal16); adaptor.AddChild(root_0, string_literal16_tree); DebugLocation(164, 11); type = BinaryExpressionType.LeftShift; } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:165:6: '>>' { DebugLocation(165, 6); string_literal17=(IToken)Match(input,40,Follow._40_in_shiftExpression581); string_literal17_tree = (CommonTree)adaptor.Create(string_literal17); adaptor.AddChild(root_0, string_literal17_tree); DebugLocation(165, 11); type = BinaryExpressionType.RightShift; } break; } } finally { DebugExitSubRule(11); } DebugLocation(166, 9); PushFollow(Follow._additiveExpression_in_shiftExpression593); right=additiveExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(166, 29); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop12; } } loop12: ; } finally { DebugExitSubRule(12); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("shiftExpression", 10); LeaveRule("shiftExpression", 10); Leave_shiftExpression(); } DebugLocation(168, 1); } finally { DebugExitRule(GrammarFileName, "shiftExpression"); } return retval; } // $ANTLR end "shiftExpression" public class additiveExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_additiveExpression(); partial void Leave_additiveExpression(); // $ANTLR start "additiveExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:170:1: additiveExpression returns [LogicalExpression value] : left= multiplicativeExpression ( ( '+' | '-' ) right= multiplicativeExpression )* ; [GrammarRule("additiveExpression")] private NCalcParser.additiveExpression_return additiveExpression() { Enter_additiveExpression(); EnterRule("additiveExpression", 11); TraceIn("additiveExpression", 11); NCalcParser.additiveExpression_return retval = new NCalcParser.additiveExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal18=null; IToken char_literal19=null; NCalcParser.multiplicativeExpression_return left = default(NCalcParser.multiplicativeExpression_return); NCalcParser.multiplicativeExpression_return right = default(NCalcParser.multiplicativeExpression_return); CommonTree char_literal18_tree=null; CommonTree char_literal19_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "additiveExpression"); DebugLocation(170, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:174:2: (left= multiplicativeExpression ( ( '+' | '-' ) right= multiplicativeExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:174:4: left= multiplicativeExpression ( ( '+' | '-' ) right= multiplicativeExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(174, 8); PushFollow(Follow._multiplicativeExpression_in_additiveExpression625); left=multiplicativeExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(174, 34); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(174, 60); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:174:60: ( ( '+' | '-' ) right= multiplicativeExpression )* try { DebugEnterSubRule(14); while (true) { int alt14=2; try { DebugEnterDecision(14, decisionCanBacktrack[14]); int LA14_0 = input.LA(1); if ((LA14_0==27||LA14_0==29)) { alt14=1; } } finally { DebugExitDecision(14); } switch ( alt14 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:175:4: ( '+' | '-' ) right= multiplicativeExpression { DebugLocation(175, 4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:175:4: ( '+' | '-' ) int alt13=2; try { DebugEnterSubRule(13); try { DebugEnterDecision(13, decisionCanBacktrack[13]); int LA13_0 = input.LA(1); if ((LA13_0==27)) { alt13=1; } else if ((LA13_0==29)) { alt13=2; } else { NoViableAltException nvae = new NoViableAltException("", 13, 0, input); DebugRecognitionException(nvae); throw nvae; } } finally { DebugExitDecision(13); } switch (alt13) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:175:6: '+' { DebugLocation(175, 6); char_literal18=(IToken)Match(input,27,Follow._27_in_additiveExpression636); char_literal18_tree = (CommonTree)adaptor.Create(char_literal18); adaptor.AddChild(root_0, char_literal18_tree); DebugLocation(175, 10); type = BinaryExpressionType.Plus; } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:176:6: '-' { DebugLocation(176, 6); char_literal19=(IToken)Match(input,29,Follow._29_in_additiveExpression646); char_literal19_tree = (CommonTree)adaptor.Create(char_literal19); adaptor.AddChild(root_0, char_literal19_tree); DebugLocation(176, 10); type = BinaryExpressionType.Minus; } break; } } finally { DebugExitSubRule(13); } DebugLocation(177, 9); PushFollow(Follow._multiplicativeExpression_in_additiveExpression658); right=multiplicativeExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(177, 35); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop14; } } loop14: ; } finally { DebugExitSubRule(14); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("additiveExpression", 11); LeaveRule("additiveExpression", 11); Leave_additiveExpression(); } DebugLocation(179, 1); } finally { DebugExitRule(GrammarFileName, "additiveExpression"); } return retval; } // $ANTLR end "additiveExpression" public class multiplicativeExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_multiplicativeExpression(); partial void Leave_multiplicativeExpression(); // $ANTLR start "multiplicativeExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:181:1: multiplicativeExpression returns [LogicalExpression value] : left= unaryExpression ( ( '*' | '/' | '%' ) right= unaryExpression )* ; [GrammarRule("multiplicativeExpression")] private NCalcParser.multiplicativeExpression_return multiplicativeExpression() { Enter_multiplicativeExpression(); EnterRule("multiplicativeExpression", 12); TraceIn("multiplicativeExpression", 12); NCalcParser.multiplicativeExpression_return retval = new NCalcParser.multiplicativeExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal20=null; IToken char_literal21=null; IToken char_literal22=null; NCalcParser.unaryExpression_return left = default(NCalcParser.unaryExpression_return); NCalcParser.unaryExpression_return right = default(NCalcParser.unaryExpression_return); CommonTree char_literal20_tree=null; CommonTree char_literal21_tree=null; CommonTree char_literal22_tree=null; BinaryExpressionType type = BinaryExpressionType.Unknown; try { DebugEnterRule(GrammarFileName, "multiplicativeExpression"); DebugLocation(181, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:185:2: (left= unaryExpression ( ( '*' | '/' | '%' ) right= unaryExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:185:4: left= unaryExpression ( ( '*' | '/' | '%' ) right= unaryExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(185, 8); PushFollow(Follow._unaryExpression_in_multiplicativeExpression690); left=unaryExpression(); PopFollow(); adaptor.AddChild(root_0, left.Tree); DebugLocation(185, 25); retval.value = (left!=null?left.value:default(LogicalExpression)); DebugLocation(185, 52); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:185:52: ( ( '*' | '/' | '%' ) right= unaryExpression )* try { DebugEnterSubRule(16); while (true) { int alt16=2; try { DebugEnterDecision(16, decisionCanBacktrack[16]); int LA16_0 = input.LA(1); if ((LA16_0==21||LA16_0==26||LA16_0==30)) { alt16=1; } } finally { DebugExitDecision(16); } switch ( alt16 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:186:4: ( '*' | '/' | '%' ) right= unaryExpression { DebugLocation(186, 4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:186:4: ( '*' | '/' | '%' ) int alt15=3; try { DebugEnterSubRule(15); try { DebugEnterDecision(15, decisionCanBacktrack[15]); switch (input.LA(1)) { case 26: { alt15=1; } break; case 30: { alt15=2; } break; case 21: { alt15=3; } break; default: { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); DebugRecognitionException(nvae); throw nvae; } } } finally { DebugExitDecision(15); } switch (alt15) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:186:6: '*' { DebugLocation(186, 6); char_literal20=(IToken)Match(input,26,Follow._26_in_multiplicativeExpression701); char_literal20_tree = (CommonTree)adaptor.Create(char_literal20); adaptor.AddChild(root_0, char_literal20_tree); DebugLocation(186, 10); type = BinaryExpressionType.Times; } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:187:6: '/' { DebugLocation(187, 6); char_literal21=(IToken)Match(input,30,Follow._30_in_multiplicativeExpression711); char_literal21_tree = (CommonTree)adaptor.Create(char_literal21); adaptor.AddChild(root_0, char_literal21_tree); DebugLocation(187, 10); type = BinaryExpressionType.Div; } break; case 3: DebugEnterAlt(3); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:188:6: '%' { DebugLocation(188, 6); char_literal22=(IToken)Match(input,21,Follow._21_in_multiplicativeExpression721); char_literal22_tree = (CommonTree)adaptor.Create(char_literal22); adaptor.AddChild(root_0, char_literal22_tree); DebugLocation(188, 10); type = BinaryExpressionType.Modulo; } break; } } finally { DebugExitSubRule(15); } DebugLocation(189, 9); PushFollow(Follow._unaryExpression_in_multiplicativeExpression733); right=unaryExpression(); PopFollow(); adaptor.AddChild(root_0, right.Tree); DebugLocation(189, 26); retval.value = new BinaryExpression(type, retval.value, (right!=null?right.value:default(LogicalExpression))); } break; default: goto loop16; } } loop16: ; } finally { DebugExitSubRule(16); } } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("multiplicativeExpression", 12); LeaveRule("multiplicativeExpression", 12); Leave_multiplicativeExpression(); } DebugLocation(191, 1); } finally { DebugExitRule(GrammarFileName, "multiplicativeExpression"); } return retval; } // $ANTLR end "multiplicativeExpression" public class unaryExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_unaryExpression(); partial void Leave_unaryExpression(); // $ANTLR start "unaryExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:194:1: unaryExpression returns [LogicalExpression value] : ( primaryExpression | ( '!' | 'not' ) primaryExpression | ( '~' ) primaryExpression | '-' primaryExpression ); [GrammarRule("unaryExpression")] private NCalcParser.unaryExpression_return unaryExpression() { Enter_unaryExpression(); EnterRule("unaryExpression", 13); TraceIn("unaryExpression", 13); NCalcParser.unaryExpression_return retval = new NCalcParser.unaryExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken set24=null; IToken char_literal26=null; IToken char_literal28=null; NCalcParser.primaryExpression_return primaryExpression23 = default(NCalcParser.primaryExpression_return); NCalcParser.primaryExpression_return primaryExpression25 = default(NCalcParser.primaryExpression_return); NCalcParser.primaryExpression_return primaryExpression27 = default(NCalcParser.primaryExpression_return); NCalcParser.primaryExpression_return primaryExpression29 = default(NCalcParser.primaryExpression_return); CommonTree set24_tree=null; CommonTree char_literal26_tree=null; CommonTree char_literal28_tree=null; try { DebugEnterRule(GrammarFileName, "unaryExpression"); DebugLocation(194, 4); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:195:2: ( primaryExpression | ( '!' | 'not' ) primaryExpression | ( '~' ) primaryExpression | '-' primaryExpression ) int alt17=4; try { DebugEnterDecision(17, decisionCanBacktrack[17]); switch (input.LA(1)) { case DATETIME: case FALSE: case FLOAT: case ID: case INTEGER: case NAME: case STRING: case TRUE: case 24: { alt17=1; } break; case 19: case 44: { alt17=2; } break; case 48: { alt17=3; } break; case 29: { alt17=4; } break; default: { NoViableAltException nvae = new NoViableAltException("", 17, 0, input); DebugRecognitionException(nvae); throw nvae; } } } finally { DebugExitDecision(17); } switch (alt17) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:195:4: primaryExpression { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(195, 4); PushFollow(Follow._primaryExpression_in_unaryExpression760); primaryExpression23=primaryExpression(); PopFollow(); adaptor.AddChild(root_0, primaryExpression23.Tree); DebugLocation(195, 22); retval.value = (primaryExpression23!=null?primaryExpression23.value:default(LogicalExpression)); } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:196:8: ( '!' | 'not' ) primaryExpression { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(196, 8); set24=(IToken)input.LT(1); if (input.LA(1)==19||input.LA(1)==44) { input.Consume(); adaptor.AddChild(root_0, (CommonTree)adaptor.Create(set24)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); throw mse; } DebugLocation(196, 22); PushFollow(Follow._primaryExpression_in_unaryExpression779); primaryExpression25=primaryExpression(); PopFollow(); adaptor.AddChild(root_0, primaryExpression25.Tree); DebugLocation(196, 40); retval.value = new UnaryExpression(UnaryExpressionType.Not, (primaryExpression25!=null?primaryExpression25.value:default(LogicalExpression))); } break; case 3: DebugEnterAlt(3); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:197:8: ( '~' ) primaryExpression { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(197, 8); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:197:8: ( '~' ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:197:9: '~' { DebugLocation(197, 9); char_literal26=(IToken)Match(input,48,Follow._48_in_unaryExpression791); char_literal26_tree = (CommonTree)adaptor.Create(char_literal26); adaptor.AddChild(root_0, char_literal26_tree); } DebugLocation(197, 14); PushFollow(Follow._primaryExpression_in_unaryExpression794); primaryExpression27=primaryExpression(); PopFollow(); adaptor.AddChild(root_0, primaryExpression27.Tree); DebugLocation(197, 32); retval.value = new UnaryExpression(UnaryExpressionType.BitwiseNot, (primaryExpression27!=null?primaryExpression27.value:default(LogicalExpression))); } break; case 4: DebugEnterAlt(4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:198:8: '-' primaryExpression { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(198, 8); char_literal28=(IToken)Match(input,29,Follow._29_in_unaryExpression805); char_literal28_tree = (CommonTree)adaptor.Create(char_literal28); adaptor.AddChild(root_0, char_literal28_tree); DebugLocation(198, 12); PushFollow(Follow._primaryExpression_in_unaryExpression807); primaryExpression29=primaryExpression(); PopFollow(); adaptor.AddChild(root_0, primaryExpression29.Tree); DebugLocation(198, 30); retval.value = new UnaryExpression(UnaryExpressionType.Negate, (primaryExpression29!=null?primaryExpression29.value:default(LogicalExpression))); } break; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("unaryExpression", 13); LeaveRule("unaryExpression", 13); Leave_unaryExpression(); } DebugLocation(199, 4); } finally { DebugExitRule(GrammarFileName, "unaryExpression"); } return retval; } // $ANTLR end "unaryExpression" public class primaryExpression_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public LogicalExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_primaryExpression(); partial void Leave_primaryExpression(); // $ANTLR start "primaryExpression" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:201:1: primaryExpression returns [LogicalExpression value] : ( '(' logicalExpression ')' |expr= value | identifier ( arguments )? ); [GrammarRule("primaryExpression")] private NCalcParser.primaryExpression_return primaryExpression() { Enter_primaryExpression(); EnterRule("primaryExpression", 14); TraceIn("primaryExpression", 14); NCalcParser.primaryExpression_return retval = new NCalcParser.primaryExpression_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal30=null; IToken char_literal32=null; NCalcParser.value_return expr = default(NCalcParser.value_return); NCalcParser.logicalExpression_return logicalExpression31 = default(NCalcParser.logicalExpression_return); NCalcParser.identifier_return identifier33 = default(NCalcParser.identifier_return); NCalcParser.arguments_return arguments34 = default(NCalcParser.arguments_return); CommonTree char_literal30_tree=null; CommonTree char_literal32_tree=null; try { DebugEnterRule(GrammarFileName, "primaryExpression"); DebugLocation(201, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:202:2: ( '(' logicalExpression ')' |expr= value | identifier ( arguments )? ) int alt19=3; try { DebugEnterDecision(19, decisionCanBacktrack[19]); switch (input.LA(1)) { case 24: { alt19=1; } break; case DATETIME: case FALSE: case FLOAT: case INTEGER: case STRING: case TRUE: { alt19=2; } break; case ID: case NAME: { alt19=3; } break; default: { NoViableAltException nvae = new NoViableAltException("", 19, 0, input); DebugRecognitionException(nvae); throw nvae; } } } finally { DebugExitDecision(19); } switch (alt19) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:202:4: '(' logicalExpression ')' { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(202, 4); char_literal30=(IToken)Match(input,24,Follow._24_in_primaryExpression829); char_literal30_tree = (CommonTree)adaptor.Create(char_literal30); adaptor.AddChild(root_0, char_literal30_tree); DebugLocation(202, 8); PushFollow(Follow._logicalExpression_in_primaryExpression831); logicalExpression31=logicalExpression(); PopFollow(); adaptor.AddChild(root_0, logicalExpression31.Tree); DebugLocation(202, 26); char_literal32=(IToken)Match(input,25,Follow._25_in_primaryExpression833); char_literal32_tree = (CommonTree)adaptor.Create(char_literal32); adaptor.AddChild(root_0, char_literal32_tree); DebugLocation(202, 31); retval.value = (logicalExpression31!=null?logicalExpression31.value:default(LogicalExpression)); } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:203:4: expr= value { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(203, 8); PushFollow(Follow._value_in_primaryExpression843); expr=value(); PopFollow(); adaptor.AddChild(root_0, expr.Tree); DebugLocation(203, 16); retval.value = (expr!=null?expr.value:default(ValueExpression)); } break; case 3: DebugEnterAlt(3); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:204:4: identifier ( arguments )? { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(204, 4); PushFollow(Follow._identifier_in_primaryExpression851); identifier33=identifier(); PopFollow(); adaptor.AddChild(root_0, identifier33.Tree); DebugLocation(204, 15); retval.value = (LogicalExpression) (identifier33!=null?identifier33.value:default(Identifier)); DebugLocation(204, 66); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:204:66: ( arguments )? int alt18=2; try { DebugEnterSubRule(18); try { DebugEnterDecision(18, decisionCanBacktrack[18]); int LA18_0 = input.LA(1); if ((LA18_0==24)) { alt18=1; } } finally { DebugExitDecision(18); } switch (alt18) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:204:67: arguments { DebugLocation(204, 67); PushFollow(Follow._arguments_in_primaryExpression856); arguments34=arguments(); PopFollow(); adaptor.AddChild(root_0, arguments34.Tree); DebugLocation(204, 77); retval.value = new Function((identifier33!=null?identifier33.value:default(Identifier)), ((arguments34!=null?arguments34.value:default(List<LogicalExpression>))).ToArray()); } break; } } finally { DebugExitSubRule(18); } } break; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("primaryExpression", 14); LeaveRule("primaryExpression", 14); Leave_primaryExpression(); } DebugLocation(205, 1); } finally { DebugExitRule(GrammarFileName, "primaryExpression"); } return retval; } // $ANTLR end "primaryExpression" public class value_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public ValueExpression value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_value(); partial void Leave_value(); // $ANTLR start "value" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:207:1: value returns [ValueExpression value] : ( INTEGER | FLOAT | STRING | DATETIME | TRUE | FALSE ); [GrammarRule("value")] private NCalcParser.value_return value() { Enter_value(); EnterRule("value", 15); TraceIn("value", 15); NCalcParser.value_return retval = new NCalcParser.value_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken INTEGER35=null; IToken FLOAT36=null; IToken STRING37=null; IToken DATETIME38=null; IToken TRUE39=null; IToken FALSE40=null; CommonTree INTEGER35_tree=null; CommonTree FLOAT36_tree=null; CommonTree STRING37_tree=null; CommonTree DATETIME38_tree=null; CommonTree TRUE39_tree=null; CommonTree FALSE40_tree=null; try { DebugEnterRule(GrammarFileName, "value"); DebugLocation(207, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:208:2: ( INTEGER | FLOAT | STRING | DATETIME | TRUE | FALSE ) int alt20=6; try { DebugEnterDecision(20, decisionCanBacktrack[20]); switch (input.LA(1)) { case INTEGER: { alt20=1; } break; case FLOAT: { alt20=2; } break; case STRING: { alt20=3; } break; case DATETIME: { alt20=4; } break; case TRUE: { alt20=5; } break; case FALSE: { alt20=6; } break; default: { NoViableAltException nvae = new NoViableAltException("", 20, 0, input); DebugRecognitionException(nvae); throw nvae; } } } finally { DebugExitDecision(20); } switch (alt20) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:208:5: INTEGER { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(208, 5); INTEGER35=(IToken)Match(input,INTEGER,Follow._INTEGER_in_value876); INTEGER35_tree = (CommonTree)adaptor.Create(INTEGER35); adaptor.AddChild(root_0, INTEGER35_tree); DebugLocation(208, 14); try { retval.value = new ValueExpression(int.Parse((INTEGER35!=null?INTEGER35.Text:null))); } catch(System.OverflowException) { retval.value = new ValueExpression(long.Parse((INTEGER35!=null?INTEGER35.Text:null))); } } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:209:4: FLOAT { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(209, 4); FLOAT36=(IToken)Match(input,FLOAT,Follow._FLOAT_in_value884); FLOAT36_tree = (CommonTree)adaptor.Create(FLOAT36); adaptor.AddChild(root_0, FLOAT36_tree); DebugLocation(209, 11); retval.value = new ValueExpression(double.Parse((FLOAT36!=null?FLOAT36.Text:null), NumberStyles.Float, numberFormatInfo)); } break; case 3: DebugEnterAlt(3); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:210:4: STRING { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(210, 4); STRING37=(IToken)Match(input,STRING,Follow._STRING_in_value892); STRING37_tree = (CommonTree)adaptor.Create(STRING37); adaptor.AddChild(root_0, STRING37_tree); DebugLocation(210, 12); retval.value = new ValueExpression(extractString((STRING37!=null?STRING37.Text:null))); } break; case 4: DebugEnterAlt(4); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:211:5: DATETIME { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(211, 5); DATETIME38=(IToken)Match(input,DATETIME,Follow._DATETIME_in_value901); DATETIME38_tree = (CommonTree)adaptor.Create(DATETIME38); adaptor.AddChild(root_0, DATETIME38_tree); DebugLocation(211, 14); retval.value = new ValueExpression(DateTime.Parse((DATETIME38!=null?DATETIME38.Text:null).Substring(1, (DATETIME38!=null?DATETIME38.Text:null).Length-2))); } break; case 5: DebugEnterAlt(5); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:212:4: TRUE { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(212, 4); TRUE39=(IToken)Match(input,TRUE,Follow._TRUE_in_value908); TRUE39_tree = (CommonTree)adaptor.Create(TRUE39); adaptor.AddChild(root_0, TRUE39_tree); DebugLocation(212, 10); retval.value = new ValueExpression(true); } break; case 6: DebugEnterAlt(6); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:213:4: FALSE { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(213, 4); FALSE40=(IToken)Match(input,FALSE,Follow._FALSE_in_value916); FALSE40_tree = (CommonTree)adaptor.Create(FALSE40); adaptor.AddChild(root_0, FALSE40_tree); DebugLocation(213, 11); retval.value = new ValueExpression(false); } break; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("value", 15); LeaveRule("value", 15); Leave_value(); } DebugLocation(214, 1); } finally { DebugExitRule(GrammarFileName, "value"); } return retval; } // $ANTLR end "value" public class identifier_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public Identifier value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_identifier(); partial void Leave_identifier(); // $ANTLR start "identifier" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:216:1: identifier returns [Identifier value] : ( ID | NAME ); [GrammarRule("identifier")] private NCalcParser.identifier_return identifier() { Enter_identifier(); EnterRule("identifier", 16); TraceIn("identifier", 16); NCalcParser.identifier_return retval = new NCalcParser.identifier_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken ID41=null; IToken NAME42=null; CommonTree ID41_tree=null; CommonTree NAME42_tree=null; try { DebugEnterRule(GrammarFileName, "identifier"); DebugLocation(216, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:217:2: ( ID | NAME ) int alt21=2; try { DebugEnterDecision(21, decisionCanBacktrack[21]); int LA21_0 = input.LA(1); if ((LA21_0==ID)) { alt21=1; } else if ((LA21_0==NAME)) { alt21=2; } else { NoViableAltException nvae = new NoViableAltException("", 21, 0, input); DebugRecognitionException(nvae); throw nvae; } } finally { DebugExitDecision(21); } switch (alt21) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:217:5: ID { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(217, 5); ID41=(IToken)Match(input,ID,Follow._ID_in_identifier934); ID41_tree = (CommonTree)adaptor.Create(ID41); adaptor.AddChild(root_0, ID41_tree); DebugLocation(217, 8); retval.value = new Identifier((ID41!=null?ID41.Text:null)); } break; case 2: DebugEnterAlt(2); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:218:5: NAME { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(218, 5); NAME42=(IToken)Match(input,NAME,Follow._NAME_in_identifier942); NAME42_tree = (CommonTree)adaptor.Create(NAME42); adaptor.AddChild(root_0, NAME42_tree); DebugLocation(218, 10); retval.value = new Identifier((NAME42!=null?NAME42.Text:null).Substring(1, (NAME42!=null?NAME42.Text:null).Length-2)); } break; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("identifier", 16); LeaveRule("identifier", 16); Leave_identifier(); } DebugLocation(219, 1); } finally { DebugExitRule(GrammarFileName, "identifier"); } return retval; } // $ANTLR end "identifier" public class expressionList_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public List<LogicalExpression> value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_expressionList(); partial void Leave_expressionList(); // $ANTLR start "expressionList" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:221:1: expressionList returns [List<LogicalExpression> value] : first= logicalExpression ( ',' follow= logicalExpression )* ; [GrammarRule("expressionList")] private NCalcParser.expressionList_return expressionList() { Enter_expressionList(); EnterRule("expressionList", 17); TraceIn("expressionList", 17); NCalcParser.expressionList_return retval = new NCalcParser.expressionList_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal43=null; NCalcParser.logicalExpression_return first = default(NCalcParser.logicalExpression_return); NCalcParser.logicalExpression_return follow = default(NCalcParser.logicalExpression_return); CommonTree char_literal43_tree=null; List<LogicalExpression> expressions = new List<LogicalExpression>(); try { DebugEnterRule(GrammarFileName, "expressionList"); DebugLocation(221, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:225:2: (first= logicalExpression ( ',' follow= logicalExpression )* ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:225:4: first= logicalExpression ( ',' follow= logicalExpression )* { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(225, 9); PushFollow(Follow._logicalExpression_in_expressionList966); first=logicalExpression(); PopFollow(); adaptor.AddChild(root_0, first.Tree); DebugLocation(225, 28); expressions.Add((first!=null?first.value:default(LogicalExpression))); DebugLocation(225, 62); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:225:62: ( ',' follow= logicalExpression )* try { DebugEnterSubRule(22); while (true) { int alt22=2; try { DebugEnterDecision(22, decisionCanBacktrack[22]); int LA22_0 = input.LA(1); if ((LA22_0==28)) { alt22=1; } } finally { DebugExitDecision(22); } switch ( alt22 ) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:225:64: ',' follow= logicalExpression { DebugLocation(225, 64); char_literal43=(IToken)Match(input,28,Follow._28_in_expressionList973); char_literal43_tree = (CommonTree)adaptor.Create(char_literal43); adaptor.AddChild(root_0, char_literal43_tree); DebugLocation(225, 74); PushFollow(Follow._logicalExpression_in_expressionList977); follow=logicalExpression(); PopFollow(); adaptor.AddChild(root_0, follow.Tree); DebugLocation(225, 93); expressions.Add((follow!=null?follow.value:default(LogicalExpression))); } break; default: goto loop22; } } loop22: ; } finally { DebugExitSubRule(22); } DebugLocation(226, 2); retval.value = expressions; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("expressionList", 17); LeaveRule("expressionList", 17); Leave_expressionList(); } DebugLocation(227, 1); } finally { DebugExitRule(GrammarFileName, "expressionList"); } return retval; } // $ANTLR end "expressionList" public class arguments_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<CommonTree> { public List<LogicalExpression> value; private CommonTree _tree; public CommonTree Tree { get { return _tree; } set { _tree = value; } } } partial void Enter_arguments(); partial void Leave_arguments(); // $ANTLR start "arguments" // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:229:1: arguments returns [List<LogicalExpression> value] : '(' ( expressionList )? ')' ; [GrammarRule("arguments")] private NCalcParser.arguments_return arguments() { Enter_arguments(); EnterRule("arguments", 18); TraceIn("arguments", 18); NCalcParser.arguments_return retval = new NCalcParser.arguments_return(); retval.Start = (IToken)input.LT(1); CommonTree root_0 = null; IToken char_literal44=null; IToken char_literal46=null; NCalcParser.expressionList_return expressionList45 = default(NCalcParser.expressionList_return); CommonTree char_literal44_tree=null; CommonTree char_literal46_tree=null; retval.value = new List<LogicalExpression>(); try { DebugEnterRule(GrammarFileName, "arguments"); DebugLocation(229, 1); try { // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:233:2: ( '(' ( expressionList )? ')' ) DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:233:4: '(' ( expressionList )? ')' { root_0 = (CommonTree)adaptor.Nil(); DebugLocation(233, 4); char_literal44=(IToken)Match(input,24,Follow._24_in_arguments1006); char_literal44_tree = (CommonTree)adaptor.Create(char_literal44); adaptor.AddChild(root_0, char_literal44_tree); DebugLocation(233, 8); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:233:8: ( expressionList )? int alt23=2; try { DebugEnterSubRule(23); try { DebugEnterDecision(23, decisionCanBacktrack[23]); int LA23_0 = input.LA(1); if ((LA23_0==DATETIME||(LA23_0>=FALSE && LA23_0<=FLOAT)||(LA23_0>=ID && LA23_0<=INTEGER)||(LA23_0>=NAME && LA23_0<=TRUE)||LA23_0==19||LA23_0==24||LA23_0==29||LA23_0==44||LA23_0==48)) { alt23=1; } } finally { DebugExitDecision(23); } switch (alt23) { case 1: DebugEnterAlt(1); // C:\\Users\\sebros\\My Projects\\NCalc\\Grammar\\NCalc.g:233:10: expressionList { DebugLocation(233, 10); PushFollow(Follow._expressionList_in_arguments1010); expressionList45=expressionList(); PopFollow(); adaptor.AddChild(root_0, expressionList45.Tree); DebugLocation(233, 25); retval.value = (expressionList45!=null?expressionList45.value:default(List<LogicalExpression>)); } break; } } finally { DebugExitSubRule(23); } DebugLocation(233, 62); char_literal46=(IToken)Match(input,25,Follow._25_in_arguments1017); char_literal46_tree = (CommonTree)adaptor.Create(char_literal46); adaptor.AddChild(root_0, char_literal46_tree); } retval.Stop = (IToken)input.LT(-1); retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input,re); retval.Tree = (CommonTree)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("arguments", 18); LeaveRule("arguments", 18); Leave_arguments(); } DebugLocation(234, 1); } finally { DebugExitRule(GrammarFileName, "arguments"); } return retval; } // $ANTLR end "arguments" #endregion Rules #region Follow sets private static class Follow { public static readonly BitSet _logicalExpression_in_ncalcExpression56 = new BitSet(new ulong[]{0x0UL}); public static readonly BitSet _EOF_in_ncalcExpression58 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _conditionalExpression_in_logicalExpression78 = new BitSet(new ulong[]{0x20000000002UL}); public static readonly BitSet _41_in_logicalExpression84 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _conditionalExpression_in_logicalExpression88 = new BitSet(new ulong[]{0x80000000UL}); public static readonly BitSet _31_in_logicalExpression90 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _conditionalExpression_in_logicalExpression94 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _booleanAndExpression_in_conditionalExpression121 = new BitSet(new ulong[]{0xA00000000002UL}); public static readonly BitSet _set_in_conditionalExpression130 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _conditionalExpression_in_conditionalExpression146 = new BitSet(new ulong[]{0xA00000000002UL}); public static readonly BitSet _bitwiseOrExpression_in_booleanAndExpression180 = new BitSet(new ulong[]{0x80000400002UL}); public static readonly BitSet _set_in_booleanAndExpression189 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _bitwiseOrExpression_in_booleanAndExpression205 = new BitSet(new ulong[]{0x80000400002UL}); public static readonly BitSet _bitwiseXOrExpression_in_bitwiseOrExpression237 = new BitSet(new ulong[]{0x400000000002UL}); public static readonly BitSet _46_in_bitwiseOrExpression246 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _bitwiseOrExpression_in_bitwiseOrExpression256 = new BitSet(new ulong[]{0x400000000002UL}); public static readonly BitSet _bitwiseAndExpression_in_bitwiseXOrExpression290 = new BitSet(new ulong[]{0x40000000002UL}); public static readonly BitSet _42_in_bitwiseXOrExpression299 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _bitwiseAndExpression_in_bitwiseXOrExpression309 = new BitSet(new ulong[]{0x40000000002UL}); public static readonly BitSet _equalityExpression_in_bitwiseAndExpression341 = new BitSet(new ulong[]{0x800002UL}); public static readonly BitSet _23_in_bitwiseAndExpression350 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _equalityExpression_in_bitwiseAndExpression360 = new BitSet(new ulong[]{0x800002UL}); public static readonly BitSet _relationalExpression_in_equalityExpression394 = new BitSet(new ulong[]{0x3800100002UL}); public static readonly BitSet _set_in_equalityExpression405 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _set_in_equalityExpression422 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _relationalExpression_in_equalityExpression441 = new BitSet(new ulong[]{0x3800100002UL}); public static readonly BitSet _shiftExpression_in_relationalExpression474 = new BitSet(new ulong[]{0xC500000002UL}); public static readonly BitSet _32_in_relationalExpression485 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _34_in_relationalExpression495 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _38_in_relationalExpression506 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _39_in_relationalExpression516 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _shiftExpression_in_relationalExpression528 = new BitSet(new ulong[]{0xC500000002UL}); public static readonly BitSet _additiveExpression_in_shiftExpression560 = new BitSet(new ulong[]{0x10200000002UL}); public static readonly BitSet _33_in_shiftExpression571 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _40_in_shiftExpression581 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _additiveExpression_in_shiftExpression593 = new BitSet(new ulong[]{0x10200000002UL}); public static readonly BitSet _multiplicativeExpression_in_additiveExpression625 = new BitSet(new ulong[]{0x28000002UL}); public static readonly BitSet _27_in_additiveExpression636 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _29_in_additiveExpression646 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _multiplicativeExpression_in_additiveExpression658 = new BitSet(new ulong[]{0x28000002UL}); public static readonly BitSet _unaryExpression_in_multiplicativeExpression690 = new BitSet(new ulong[]{0x44200002UL}); public static readonly BitSet _26_in_multiplicativeExpression701 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _30_in_multiplicativeExpression711 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _21_in_multiplicativeExpression721 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _unaryExpression_in_multiplicativeExpression733 = new BitSet(new ulong[]{0x44200002UL}); public static readonly BitSet _primaryExpression_in_unaryExpression760 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _set_in_unaryExpression771 = new BitSet(new ulong[]{0x101DB10UL}); public static readonly BitSet _primaryExpression_in_unaryExpression779 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _48_in_unaryExpression791 = new BitSet(new ulong[]{0x101DB10UL}); public static readonly BitSet _primaryExpression_in_unaryExpression794 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _29_in_unaryExpression805 = new BitSet(new ulong[]{0x101DB10UL}); public static readonly BitSet _primaryExpression_in_unaryExpression807 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _24_in_primaryExpression829 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _logicalExpression_in_primaryExpression831 = new BitSet(new ulong[]{0x2000000UL}); public static readonly BitSet _25_in_primaryExpression833 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _value_in_primaryExpression843 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _identifier_in_primaryExpression851 = new BitSet(new ulong[]{0x1000002UL}); public static readonly BitSet _arguments_in_primaryExpression856 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _INTEGER_in_value876 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _FLOAT_in_value884 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _STRING_in_value892 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _DATETIME_in_value901 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _TRUE_in_value908 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _FALSE_in_value916 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _ID_in_identifier934 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _NAME_in_identifier942 = new BitSet(new ulong[]{0x2UL}); public static readonly BitSet _logicalExpression_in_expressionList966 = new BitSet(new ulong[]{0x10000002UL}); public static readonly BitSet _28_in_expressionList973 = new BitSet(new ulong[]{0x110002109DB10UL}); public static readonly BitSet _logicalExpression_in_expressionList977 = new BitSet(new ulong[]{0x10000002UL}); public static readonly BitSet _24_in_arguments1006 = new BitSet(new ulong[]{0x110002309DB10UL}); public static readonly BitSet _expressionList_in_arguments1010 = new BitSet(new ulong[]{0x2000000UL}); public static readonly BitSet _25_in_arguments1017 = new BitSet(new ulong[]{0x2UL}); } #endregion Follow sets }
32.434963
415
0.674654
[ "MIT" ]
MichaelAguilar/NCalc
Evaluant.Calculator/NCalcParser.cs
101,489
C#
// // TestResult.cs // // Author: // Gabor Nemeth (gabor.nemeth.dev@gmail.hu) // // Copyright (C) 2015, Gabor Nemeth // using System; namespace NUnit.XForms { public enum TestResult { Success, Fail, Ignored } /// <summary> /// Result of a test /// </summary> public class TestResultInfo { public string Name { get; set; } public string Details { get; set; } public TestResult Success { get; set; } } }
16.258065
47
0.539683
[ "MIT" ]
gabornemeth/NUnit.XForms
NUnit.XForms/TestResult.cs
506
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NestController : MonoBehaviour { [SerializeField] private GameObject[] nest = null; private int nestIndex = 0; [SerializeField] private PlayerController playerController = null; [SerializeField] private GameObject nestIndicator = null; [SerializeField] private AudioController audioController; void Start () { for (int i = 0; i < nest.Length; i++) { nest[i].SetActive(false); } } private void OnTriggerEnter(Collider other) { if(other.CompareTag("Pickable")) { CreateNest(); Destroy(other.gameObject); } } private void CreateNest () { nestIndicator.SetActive(false); nest[nestIndex].SetActive(true); nestIndex++; ScoreManager.score++; audioController.PlayPoint(); if (nestIndex == 5) { playerController.GameWin(); } } }
24.581395
54
0.588458
[ "MIT" ]
bryanlincoln/gjams-2019-quack
Assets/Scripts/NestController.cs
1,059
C#
using System; using BLToolkit.Mapping; public abstract class TestObject { public abstract int ID { get; set; } public abstract string Name { get; set; } [Nullable] public abstract DateTime Date { get; set; } public static ObjectMapper ObjectMapper { get { return Map.GetObjectMapper(typeof(TestObject)); } } }
20.411765
58
0.677233
[ "MIT" ]
igor-tkachev/bltoolkit
UnitTests/CS/TestObject.cs
347
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.World.LightShare; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using System; using System.Runtime.Remoting.Lifetime; using System.Threading; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.Api { [Serializable] public class LS_Api : MarshalByRefObject, ILS_Api, IScriptApi { internal IScriptEngine m_ScriptEngine; internal SceneObjectPart m_host; internal bool m_LSFunctionsEnabled = false; internal IScriptModuleComms m_comms = null; public void Initialize( IScriptEngine scriptEngine, SceneObjectPart host, TaskInventoryItem item, WaitHandle coopSleepHandle) { m_ScriptEngine = scriptEngine; m_host = host; if (m_ScriptEngine.Config.GetBoolean("AllowLightShareFunctions", false)) m_LSFunctionsEnabled = true; m_comms = m_ScriptEngine.World.RequestModuleInterface<IScriptModuleComms>(); if (m_comms == null) m_LSFunctionsEnabled = false; } public override Object InitializeLifetimeService() { ILease lease = (ILease)base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.FromMinutes(0); // lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0); // lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0); } return lease; } public Scene World { get { return m_ScriptEngine.World; } } /// <summary> /// Dumps an error message on the debug console. /// </summary> internal void LSShoutError(string message) { if (message.Length > 1023) message = message.Substring(0, 1023); World.SimChat(Utils.StringToBytes(message), ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, true); IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>(); wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message); } /// <summary> /// Get the current Windlight scene /// </summary> /// <returns>List of windlight parameters</returns> public LSL_List lsGetWindlightScene(LSL_List rules) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return new LSL_List(); } m_host.AddScriptLPS(1); RegionLightShareData wl = m_host.ParentGroup.Scene.RegionInfo.WindlightSettings; LSL_List values = new LSL_List(); int idx = 0; while (idx < rules.Length) { LSL_Integer ruleInt = rules.GetLSLIntegerItem(idx); uint rule = (uint)ruleInt; LSL_List toadd = new LSL_List(); switch (rule) { case (int)ScriptBaseClass.WL_AMBIENT: toadd.Add(new LSL_Rotation(wl.ambient.X, wl.ambient.Y, wl.ambient.Z, wl.ambient.W)); break; case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION: toadd.Add(new LSL_Vector(wl.bigWaveDirection.X, wl.bigWaveDirection.Y, 0.0f)); break; case (int)ScriptBaseClass.WL_BLUE_DENSITY: toadd.Add(new LSL_Rotation(wl.blueDensity.X, wl.blueDensity.Y, wl.blueDensity.Z, wl.blueDensity.W)); break; case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER: toadd.Add(new LSL_Float(wl.blurMultiplier)); break; case (int)ScriptBaseClass.WL_CLOUD_COLOR: toadd.Add(new LSL_Rotation(wl.cloudColor.X, wl.cloudColor.Y, wl.cloudColor.Z, wl.cloudColor.W)); break; case (int)ScriptBaseClass.WL_CLOUD_COVERAGE: toadd.Add(new LSL_Float(wl.cloudCoverage)); break; case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY: toadd.Add(new LSL_Vector(wl.cloudDetailXYDensity.X, wl.cloudDetailXYDensity.Y, wl.cloudDetailXYDensity.Z)); break; case (int)ScriptBaseClass.WL_CLOUD_SCALE: toadd.Add(new LSL_Float(wl.cloudScale)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X: toadd.Add(new LSL_Float(wl.cloudScrollX)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK: toadd.Add(new LSL_Integer(wl.cloudScrollXLock ? 1 : 0)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y: toadd.Add(new LSL_Float(wl.cloudScrollY)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK: toadd.Add(new LSL_Integer(wl.cloudScrollYLock ? 1 : 0)); break; case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY: toadd.Add(new LSL_Vector(wl.cloudXYDensity.X, wl.cloudXYDensity.Y, wl.cloudXYDensity.Z)); break; case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER: toadd.Add(new LSL_Float(wl.densityMultiplier)); break; case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER: toadd.Add(new LSL_Float(wl.distanceMultiplier)); break; case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS: toadd.Add(new LSL_Integer(wl.drawClassicClouds ? 1 : 0)); break; case (int)ScriptBaseClass.WL_EAST_ANGLE: toadd.Add(new LSL_Float(wl.eastAngle)); break; case (int)ScriptBaseClass.WL_FRESNEL_OFFSET: toadd.Add(new LSL_Float(wl.fresnelOffset)); break; case (int)ScriptBaseClass.WL_FRESNEL_SCALE: toadd.Add(new LSL_Float(wl.fresnelScale)); break; case (int)ScriptBaseClass.WL_HAZE_DENSITY: toadd.Add(new LSL_Float(wl.hazeDensity)); break; case (int)ScriptBaseClass.WL_HAZE_HORIZON: toadd.Add(new LSL_Float(wl.hazeHorizon)); break; case (int)ScriptBaseClass.WL_HORIZON: toadd.Add(new LSL_Rotation(wl.horizon.X, wl.horizon.Y, wl.horizon.Z, wl.horizon.W)); break; case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION: toadd.Add(new LSL_Vector(wl.littleWaveDirection.X, wl.littleWaveDirection.Y, 0.0f)); break; case (int)ScriptBaseClass.WL_MAX_ALTITUDE: toadd.Add(new LSL_Integer(wl.maxAltitude)); break; case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE: toadd.Add(new LSL_Key(wl.normalMapTexture.ToString())); break; case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE: toadd.Add(new LSL_Vector(wl.reflectionWaveletScale.X, wl.reflectionWaveletScale.Y, wl.reflectionWaveletScale.Z)); break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE: toadd.Add(new LSL_Float(wl.refractScaleAbove)); break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW: toadd.Add(new LSL_Float(wl.refractScaleBelow)); break; case (int)ScriptBaseClass.WL_SCENE_GAMMA: toadd.Add(new LSL_Float(wl.sceneGamma)); break; case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS: toadd.Add(new LSL_Float(wl.starBrightness)); break; case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS: toadd.Add(new LSL_Float(wl.sunGlowFocus)); break; case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE: toadd.Add(new LSL_Float(wl.sunGlowSize)); break; case (int)ScriptBaseClass.WL_SUN_MOON_COLOR: toadd.Add(new LSL_Rotation(wl.sunMoonColor.X, wl.sunMoonColor.Y, wl.sunMoonColor.Z, wl.sunMoonColor.W)); break; case (int)ScriptBaseClass.WL_SUN_MOON_POSITION: toadd.Add(new LSL_Float(wl.sunMoonPosition)); break; case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER: toadd.Add(new LSL_Float(wl.underwaterFogModifier)); break; case (int)ScriptBaseClass.WL_WATER_COLOR: toadd.Add(new LSL_Vector(wl.waterColor.X, wl.waterColor.Y, wl.waterColor.Z)); break; case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT: toadd.Add(new LSL_Float(wl.waterFogDensityExponent)); break; } if (toadd.Length > 0) { values.Add(ruleInt); values.Add(toadd.Data[0]); } idx++; } return values; } private RegionLightShareData getWindlightProfileFromRules(LSL_List rules) { RegionLightShareData wl = (RegionLightShareData)m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.Clone(); // LSL_List values = new LSL_List(); int idx = 0; while (idx < rules.Length) { uint rule; try { rule = (uint)rules.GetLSLIntegerItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule type: arg #{0} - parameter type must be integer", idx)); } LSL_Types.Quaternion iQ; LSL_Types.Vector3 iV; switch (rule) { case (int)ScriptBaseClass.WL_SUN_MOON_POSITION: idx++; try { wl.sunMoonPosition = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_MOON_POSITION: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_AMBIENT: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_AMBIENT: arg #{0} - parameter 1 must be rotation", idx)); } wl.ambient = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_BIG_WAVE_DIRECTION: arg #{0} - parameter 1 must be vector", idx)); } wl.bigWaveDirection = new Vector2((float)iV.x, (float)iV.y); break; case (int)ScriptBaseClass.WL_BLUE_DENSITY: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_BLUE_DENSITY: arg #{0} - parameter 1 must be rotation", idx)); } wl.blueDensity = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER: idx++; try { wl.blurMultiplier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_BLUR_MULTIPLIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_COLOR: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_COLOR: arg #{0} - parameter 1 must be rotation", idx)); } wl.cloudColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_CLOUD_COVERAGE: idx++; try { wl.cloudCoverage = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_COVERAGE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_DETAIL_XY_DENSITY: arg #{0} - parameter 1 must be vector", idx)); } wl.cloudDetailXYDensity = iV; break; case (int)ScriptBaseClass.WL_CLOUD_SCALE: idx++; try { wl.cloudScale = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCALE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X: idx++; try { wl.cloudScrollX = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_X: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK: idx++; try { wl.cloudScrollXLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_Y_LOCK: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y: idx++; try { wl.cloudScrollY = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_Y: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK: idx++; try { wl.cloudScrollYLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_Y_LOCK: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_XY_DENSITY: arg #{0} - parameter 1 must be vector", idx)); } wl.cloudXYDensity = iV; break; case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER: idx++; try { wl.densityMultiplier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_DENSITY_MULTIPLIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER: idx++; try { wl.distanceMultiplier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_DISTANCE_MULTIPLIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS: idx++; try { wl.drawClassicClouds = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_DRAW_CLASSIC_CLOUDS: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_EAST_ANGLE: idx++; try { wl.eastAngle = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_EAST_ANGLE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_FRESNEL_OFFSET: idx++; try { wl.fresnelOffset = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_FRESNEL_OFFSET: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_FRESNEL_SCALE: idx++; try { wl.fresnelScale = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_FRESNEL_SCALE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_HAZE_DENSITY: idx++; try { wl.hazeDensity = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_HAZE_DENSITY: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_HAZE_HORIZON: idx++; try { wl.hazeHorizon = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_HAZE_HORIZON: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_HORIZON: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_HORIZON: arg #{0} - parameter 1 must be rotation", idx)); } wl.horizon = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_LITTLE_WAVE_DIRECTION: arg #{0} - parameter 1 must be vector", idx)); } wl.littleWaveDirection = new Vector2((float)iV.x, (float)iV.y); break; case (int)ScriptBaseClass.WL_MAX_ALTITUDE: idx++; try { wl.maxAltitude = (ushort)rules.GetLSLIntegerItem(idx).value; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_MAX_ALTITUDE: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE: idx++; try { wl.normalMapTexture = new UUID(rules.GetLSLStringItem(idx).m_string); } catch (ArgumentException) { throw new InvalidCastException(string.Format("Error running rule WL_NORMAL_MAP_TEXTURE: arg #{0} - parameter 1 must be key", idx)); } break; case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_REFLECTION_WAVELET_SCALE: arg #{0} - parameter 1 must be vector", idx)); } wl.reflectionWaveletScale = iV; break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE: idx++; try { wl.refractScaleAbove = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_REFRACT_SCALE_ABOVE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW: idx++; try { wl.refractScaleBelow = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_REFRACT_SCALE_BELOW: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SCENE_GAMMA: idx++; try { wl.sceneGamma = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SCENE_GAMMA: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS: idx++; try { wl.starBrightness = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_STAR_BRIGHTNESS: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS: idx++; try { wl.sunGlowFocus = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_GLOW_FOCUS: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE: idx++; try { wl.sunGlowSize = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_GLOW_SIZE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SUN_MOON_COLOR: idx++; iQ = rules.GetQuaternionItem(idx); try { wl.sunMoonColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_MOON_COLOR: arg #{0} - parameter 1 must be rotation", idx)); } break; case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER: idx++; try { wl.underwaterFogModifier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_UNDERWATER_FOG_MODIFIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_WATER_COLOR: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_WATER_COLOR: arg #{0} - parameter 1 must be vector", idx)); } wl.waterColor = iV; break; case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT: idx++; try { wl.waterFogDensityExponent = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_WATER_FOG_DENSITY_EXPONENT: arg #{0} - parameter 1 must be float", idx)); } break; } idx++; } return wl; } /// <summary> /// Set the current Windlight scene /// </summary> /// <param name="rules"></param> /// <returns>success: true or false</returns> public int lsSetWindlightScene(LSL_List rules) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return 0; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { LSShoutError("lsSetWindlightScene can only be used by estate managers or owners."); return 0; } int success = 0; m_host.AddScriptLPS(1); if (LightShareModule.EnableWindlight) { RegionLightShareData wl; try { wl = getWindlightProfileFromRules(rules); } catch(InvalidCastException e) { LSShoutError(e.Message); return 0; } wl.valid = true; m_host.ParentGroup.Scene.StoreWindlightProfile(wl); success = 1; } else { LSShoutError("Windlight module is disabled"); return 0; } return success; } public void lsClearWindlightScene() { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { LSShoutError("lsSetWindlightScene can only be used by estate managers or owners."); return; } m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.valid = false; if (m_host.ParentGroup.Scene.SimulationDataService != null) m_host.ParentGroup.Scene.SimulationDataService.RemoveRegionWindlightSettings(m_host.ParentGroup.Scene.RegionInfo.RegionID); m_host.ParentGroup.Scene.EventManager.TriggerOnSaveNewWindlightProfile(); } /// <summary> /// Set the current Windlight scene to a target avatar /// </summary> /// <param name="rules"></param> /// <returns>success: true or false</returns> public int lsSetWindlightSceneTargeted(LSL_List rules, LSL_Key target) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return 0; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { LSShoutError("lsSetWindlightSceneTargeted can only be used by estate managers or owners."); return 0; } int success = 0; m_host.AddScriptLPS(1); if (LightShareModule.EnableWindlight) { RegionLightShareData wl; try { wl = getWindlightProfileFromRules(rules); } catch(InvalidCastException e) { LSShoutError(e.Message); return 0; } World.EventManager.TriggerOnSendNewWindlightProfileTargeted(wl, new UUID(target.m_string)); success = 1; } else { LSShoutError("Windlight module is disabled"); return 0; } return success; } } }
47.450739
169
0.470906
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LS_Api.cs
38,530
C#
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Glass.Mapper.Pipelines { /// <summary> /// Class PipelineException /// </summary> public class PipelineException : ApplicationException { /// <summary> /// Gets the args. /// </summary> /// <value>The args.</value> public AbstractPipelineArgs Args { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="PipelineException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="args">The args.</param> public PipelineException(string message, AbstractPipelineArgs args) { Args = args; } } }
27.745098
85
0.642403
[ "Apache-2.0" ]
smithc/Glass.Mapper
Source/Glass.Mapper/Pipelines/PipelineException.cs
1,415
C#
using DotNetty.Common.Internal.Logging; using Haukcode.HighResolutionTimer; using Microsoft.Extensions.Logging.Console; using Newtonsoft.Json; using NReco.Logging.File; using Org.BouncyCastle.Math; using RT.Cryptography; using RT.Models; using Server.Common; using Server.Common.Logging; using Server.Dme.Config; using Server.Plugins; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using System.Timers; namespace Server.Dme { class Program { public const string CONFIG_FILE = "config.json"; public const string PLUGINS_PATH = "plugins/"; public static ServerSettings Settings = new ServerSettings(); public static IPAddress SERVER_IP = IPAddress.Parse("192.168.0.178"); public static Dictionary<int, MediusManager> Managers = new Dictionary<int, MediusManager>(); public static TcpServer TcpServer = new TcpServer(); public static PluginsManager Plugins = null; private static FileLoggerProvider _fileLogger = null; private static ulong _sessionKeyCounter = 0; private static readonly object _sessionKeyCounterLock = (object)_sessionKeyCounter; private static DateTime _timeLastPluginTick = Utils.GetHighPrecisionUtcTime(); private static int _ticks = 0; private static Stopwatch _sw = new Stopwatch(); private static HighResolutionTimer _timer; private static DateTime _lastConfigRefresh = Utils.GetHighPrecisionUtcTime(); static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance<Program>(); static async Task TickAsync() { try { #if DEBUG || RELEASE if (!_sw.IsRunning) _sw.Start(); #endif #if DEBUG || RELEASE ++_ticks; if (_sw.Elapsed.TotalSeconds > 5f) { // _sw.Stop(); var averageMsPerTick = 1000 * (_sw.Elapsed.TotalSeconds / _ticks); var error = Math.Abs(Settings.MainLoopSleepMs - averageMsPerTick) / Settings.MainLoopSleepMs; if (error > 0.1f) Logger.Error($"Average Ms between ticks is: {averageMsPerTick} is {error * 100}% off of target {Settings.MainLoopSleepMs}"); //var dt = DateTime.UtcNow - Utils.GetHighPrecisionUtcTime(); //if (Math.Abs(dt.TotalMilliseconds) > 50) // Logger.Error($"System clock and local clock are out of sync! delta ms: {dt.TotalMilliseconds}"); _sw.Restart(); _ticks = 0; } #endif var tasks = new List<Task>() { TcpServer.Tick() }; foreach (var manager in Managers) { if (manager.Value.IsConnected) { tasks.Add(manager.Value.Tick()); } else if ((Utils.GetHighPrecisionUtcTime() - manager.Value.TimeLostConnection)?.TotalSeconds > Settings.MPSReconnectInterval) { tasks.Add(manager.Value.Start()); } } // Tick plugins if ((Utils.GetHighPrecisionUtcTime() - _timeLastPluginTick).TotalMilliseconds > Settings.PluginTickIntervalMs) { _timeLastPluginTick = Utils.GetHighPrecisionUtcTime(); Plugins.Tick(); } await Task.WhenAll(tasks); // Reload config if ((Utils.GetHighPrecisionUtcTime() - _lastConfigRefresh).TotalMilliseconds > Settings.RefreshConfigInterval) { RefreshConfig(); _lastConfigRefresh = Utils.GetHighPrecisionUtcTime(); } } catch (Exception ex) { Logger.Error(ex); await TcpServer.Stop(); await Task.WhenAll(Managers.Select(x => x.Value.Stop())); } } static async Task StartServerAsync() { int waitMs = Settings.MainLoopSleepMs; Logger.Info("Starting medius components..."); Logger.Info($"Starting TCP on port {TcpServer.Port}."); TcpServer.Start(); Logger.Info($"TCP started."); // build and start medius managers per app id foreach (var applicationId in Settings.ApplicationIds) { var manager = new MediusManager(applicationId); Logger.Info($"Starting MPS for appid {applicationId}."); await manager.Start(); Logger.Info($"MPS started."); Managers.Add(applicationId, manager); } // Logger.Info("Started."); // start timer _timer = new HighResolutionTimer(); _timer.SetPeriod(waitMs); _timer.Start(); // iterate while (true) { // handle tick rate change if (Settings.MainLoopSleepMs != waitMs) { waitMs = Settings.MainLoopSleepMs; _timer.Stop(); _timer.SetPeriod(waitMs); _timer.Start(); } // tick await TickAsync(); // wait for next tick _timer.WaitForTrigger(); } } static async Task Main(string[] args) { // Initialize(); // Add file logger if path is valid if (new FileInfo(LogSettings.Singleton.LogPath)?.Directory?.Exists ?? false) { var loggingOptions = new FileLoggerOptions() { Append = false, FileSizeLimitBytes = LogSettings.Singleton.RollingFileSize, MaxRollingFiles = LogSettings.Singleton.RollingFileCount }; InternalLoggerFactory.DefaultFactory.AddProvider(_fileLogger = new FileLoggerProvider(LogSettings.Singleton.LogPath, loggingOptions)); _fileLogger.MinLevel = Settings.Logging.LogLevel; } // Optionally add console logger (always enabled when debugging) #if DEBUG InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => level >= LogSettings.Singleton.LogLevel, true)); #else if (Settings.Logging.LogToConsole) InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => level >= LogSettings.Singleton.LogLevel, true)); #endif // Initialize plugins Plugins = new PluginsManager(PLUGINS_PATH); // await StartServerAsync(); } static void Initialize() { RefreshServerIp(); RefreshConfig(); } /// <summary> /// /// </summary> static void RefreshConfig() { var usePublicIp = Settings.UsePublicIp; // var serializerSettings = new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Ignore, }; // Load settings if (File.Exists(CONFIG_FILE)) { // Populate existing object JsonConvert.PopulateObject(File.ReadAllText(CONFIG_FILE), Settings, serializerSettings); } else { // Save defaults File.WriteAllText(CONFIG_FILE, JsonConvert.SerializeObject(Settings, Formatting.Indented)); } // Set LogSettings singleton LogSettings.Singleton = Settings.Logging; // Update default rsa key Pipeline.Attribute.ScertClientAttribute.DefaultRsaAuthKey = Settings.DefaultKey; // Update file logger min level if (_fileLogger != null) _fileLogger.MinLevel = Settings.Logging.LogLevel; // Determine server ip if (usePublicIp != Settings.UsePublicIp) RefreshServerIp(); } static void RefreshServerIp() { if (!Settings.UsePublicIp) { SERVER_IP = Utils.GetLocalIPAddress(); } else { if (string.IsNullOrWhiteSpace(Settings.PublicIpOverride)) SERVER_IP = IPAddress.Parse(Utils.GetPublicIPAddress()); else SERVER_IP = IPAddress.Parse(Settings.PublicIpOverride); } } public static MediusManager GetManager(int applicationId, bool useDefaultOnMissing) { if (Managers.TryGetValue(applicationId, out var manager)) return manager; if (useDefaultOnMissing && Managers.TryGetValue(0, out manager)) return manager; return null; } public static string GenerateSessionKey() { lock (_sessionKeyCounterLock) { return (++_sessionKeyCounter).ToString(); } } } }
34.32872
154
0.534724
[ "MIT" ]
jtjanecek/horizon-server
Server.Dme/Program.cs
9,923
C#
#nullable enable using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using mxProject.Devs.DataGeneration.Configuration; using mxProject.Devs.DataGeneration.Configuration.Fields; using mxProject.Tools.DataFountain.Messaging; using mxProject.Tools.DataFountain.Models; namespace mxProject.Tools.DataFountain.Forms.FieldEditors.TupleFields { /// <summary> /// Editor for <see cref="DirectProductFieldSettings"/>. /// </summary> internal partial class DirectProductFieldEditor : TupleFieldEditorBase { /// <summary> /// Creates a new instance. /// </summary> /// <param name="context"></param> internal DirectProductFieldEditor(DataFountainContext context) : base(context) { InitializeComponent(); Init(); } /// <summary> /// Initializes this instance. /// </summary> private void Init() { InitFieldType(); btnPreview.Click += (sender, e) => { if (!ValidateInputValues()) { return; } try { ShowPreview(GetFieldSettingsAsNew()); } catch (Exception ex) { MessageBox.Show(ex.Message); } }; } #region field type /// <summary> /// Initializes field types. /// </summary> private void InitFieldType() { cmbFieldType.DropDownStyle = ComboBoxStyle.DropDownList; cmbFieldType.Items.Clear(); cmbFieldType.Items.Add(DataGeneratorTupleFieldType.DirectProduct); cmbFieldType.SelectedIndex = 0; cmbFieldType.Enabled = false; } #endregion #region field private DirectProductFieldSettingsState m_FieldState = null!; #endregion #region start editting /// <summary> /// Sets the specified field for editing. /// </summary> /// <param name="fieldState"></param> internal void SetDirectProductFieldSettings(DirectProductFieldSettingsState fieldState) { m_FieldState = fieldState; } /// <inheritdoc/> protected override void SetFieldSettings(DataGeneratorTupleFieldSettingsState? fieldState) { if (fieldState is DirectProductFieldSettingsState directProduct) { SetDirectProductFieldSettings(directProduct); } } #endregion #region validation /// <summary> /// Validate the input values. /// </summary> /// <returns></returns> private bool ValidateInputValues() { errorProvider1.Clear(); if (!ValidateInputValues(out string? message, out Control? control)) { if (!string.IsNullOrEmpty(message)) { MessageBox.Show(message); } if (control != null) { errorProvider1.SetError(control, message); FormUtility.SetFocus(control, true); } return false; } return true; } /// <inheritdoc/> protected override bool ValidateInputValues(out string? invalidMessage, out Control? invalidControl) { if (!base.ValidateInputValues(out invalidMessage, out invalidControl)) { return false; } if (m_FieldState.DirectProduct?.Fields == null || m_FieldState.DirectProduct?.Fields.Length == 0) { invalidMessage = "No field is set in the DirectProduct field."; invalidControl = null; return false; } if (m_FieldState.DirectProduct?.Fields.Length == 1) { invalidMessage = "Set two or more fields in the DirectProduct field."; invalidControl = null; return false; } invalidMessage = null; invalidControl = null; return true; } #endregion #region end of editting /// <inheritdoc/> protected override DataGeneratorTupleFieldSettings GetFieldSettingsAsNew() { if (m_FieldState.Settings is DirectProductFieldSettings settings) { return (DirectProductFieldSettings)settings.Clone(); } else { return null!; } } #endregion #region preview /// <summary> /// Generates and previews the value of the current field. /// </summary> /// <param name="fieldSettings"></param> private void ShowPreview(DataGeneratorTupleFieldSettings fieldSettings) { DataGeneratorSettings generatorSettings = new(); generatorSettings.TupleFields = new[] { fieldSettings }; // using DataPreviewForm form = new(); Context.CurrentExecutor.ShowPreview(generatorSettings.ToJson(), FormUtility.PreviewDateCount); } #endregion } }
27.329949
109
0.561478
[ "MIT" ]
mxProject/DataGenerator
mxDataFountain/mxDataFountain.Net472/Tools/DataFountain/Forms/FieldEditors/TupleFields/DirectProductFieldEditor.cs
5,386
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.Data.DataView; using Microsoft.ML; using Microsoft.ML.CommandLine; using Microsoft.ML.Data; using Microsoft.ML.EntryPoints; using Microsoft.ML.Internal.Internallearn; using Microsoft.ML.Internal.Utilities; using Microsoft.ML.Model; using Microsoft.ML.TextAnalytics; using Microsoft.ML.Transforms.Text; [assembly: LoadableClass(LatentDirichletAllocationTransformer.Summary, typeof(IDataTransform), typeof(LatentDirichletAllocationTransformer), typeof(LatentDirichletAllocationTransformer.Options), typeof(SignatureDataTransform), "Latent Dirichlet Allocation Transform", LatentDirichletAllocationTransformer.LoaderSignature, "Lda")] [assembly: LoadableClass(LatentDirichletAllocationTransformer.Summary, typeof(IDataTransform), typeof(LatentDirichletAllocationTransformer), null, typeof(SignatureLoadDataTransform), "Latent Dirichlet Allocation Transform", LatentDirichletAllocationTransformer.LoaderSignature)] [assembly: LoadableClass(LatentDirichletAllocationTransformer.Summary, typeof(LatentDirichletAllocationTransformer), null, typeof(SignatureLoadModel), "Latent Dirichlet Allocation Transform", LatentDirichletAllocationTransformer.LoaderSignature)] [assembly: LoadableClass(typeof(IRowMapper), typeof(LatentDirichletAllocationTransformer), null, typeof(SignatureLoadRowMapper), "Latent Dirichlet Allocation Transform", LatentDirichletAllocationTransformer.LoaderSignature)] namespace Microsoft.ML.Transforms.Text { // LightLDA transform: Big Topic Models on Modest Compute Clusters. // <a href="https://arxiv.org/abs/1412.1576">LightLDA</a> is an implementation of Latent Dirichlet Allocation (LDA). // Previous implementations of LDA such as SparseLDA or AliasLDA allow to achieve massive data and model scales, // for example models with tens of billions of parameters to be inferred from billions of documents. // However this requires using a cluster of thousands of machines with all ensuing costs to setup and maintain. // LightLDA solves this problem in a more cost-effective manner by providing an implementation // that is efficient enough for modest clusters with at most tens of machines... // For more details please see original LightLDA paper: // https://arxiv.org/abs/1412.1576 // http://www.www2015.it/documents/proceedings/proceedings/p1351.pdf // and open source implementation: // https://github.com/Microsoft/LightLDA // // See <a href="https://github.com/dotnet/machinelearning/blob/master/test/Microsoft.ML.TestFramework/DataPipe/TestDataPipe.cs"/> // for an example on how to use LatentDirichletAllocationTransformer. /// <include file='doc.xml' path='doc/members/member[@name="LightLDA"]/*' /> public sealed class LatentDirichletAllocationTransformer : OneToOneTransformerBase { internal sealed class Options : TransformInputBase { [Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "New column definition(s) (optional form: name:srcs)", Name = "Column", ShortName = "col", SortOrder = 49)] public Column[] Columns; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of topics", SortOrder = 50)] [TGUI(SuggestedSweeps = "20,40,100,200")] [TlcModule.SweepableDiscreteParam("NumTopic", new object[] { 20, 40, 100, 200 })] public int NumTopic = LatentDirichletAllocationEstimator.Defaults.NumTopic; [Argument(ArgumentType.AtMostOnce, HelpText = "Dirichlet prior on document-topic vectors")] [TGUI(SuggestedSweeps = "1,10,100,200")] [TlcModule.SweepableDiscreteParam("AlphaSum", new object[] { 1, 10, 100, 200 })] public float AlphaSum = LatentDirichletAllocationEstimator.Defaults.AlphaSum; [Argument(ArgumentType.AtMostOnce, HelpText = "Dirichlet prior on vocab-topic vectors")] [TGUI(SuggestedSweeps = "0.01,0.015,0.07,0.02")] [TlcModule.SweepableDiscreteParam("Beta", new object[] { 0.01f, 0.015f, 0.07f, 0.02f })] public float Beta = LatentDirichletAllocationEstimator.Defaults.Beta; [Argument(ArgumentType.Multiple, HelpText = "Number of Metropolis Hasting step")] [TGUI(SuggestedSweeps = "2,4,8,16")] [TlcModule.SweepableDiscreteParam("Mhstep", new object[] { 2, 4, 8, 16 })] public int Mhstep = LatentDirichletAllocationEstimator.Defaults.Mhstep; [Argument(ArgumentType.AtMostOnce, HelpText = "Number of iterations", ShortName = "iter")] [TGUI(SuggestedSweeps = "100,200,300,400")] [TlcModule.SweepableDiscreteParam("NumIterations", new object[] { 100, 200, 300, 400 })] public int NumIterations = LatentDirichletAllocationEstimator.Defaults.NumIterations; [Argument(ArgumentType.AtMostOnce, HelpText = "Compute log likelihood over local dataset on this iteration interval", ShortName = "llInterval")] public int LikelihoodInterval = LatentDirichletAllocationEstimator.Defaults.LikelihoodInterval; // REVIEW: Should change the default when multi-threading support is optimized. [Argument(ArgumentType.AtMostOnce, HelpText = "The number of training threads. Default value depends on number of logical processors.", ShortName = "t", SortOrder = 50)] public int NumThreads = LatentDirichletAllocationEstimator.Defaults.NumThreads; [Argument(ArgumentType.AtMostOnce, HelpText = "The threshold of maximum count of tokens per doc", ShortName = "maxNumToken", SortOrder = 50)] public int NumMaxDocToken = LatentDirichletAllocationEstimator.Defaults.NumMaxDocToken; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of words to summarize the topic", ShortName = "ns")] public int NumSummaryTermPerTopic = LatentDirichletAllocationEstimator.Defaults.NumSummaryTermPerTopic; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of burn-in iterations", ShortName = "burninIter")] [TGUI(SuggestedSweeps = "10,20,30,40")] [TlcModule.SweepableDiscreteParam("NumBurninIterations", new object[] { 10, 20, 30, 40 })] public int NumBurninIterations = LatentDirichletAllocationEstimator.Defaults.NumBurninIterations; [Argument(ArgumentType.AtMostOnce, HelpText = "Reset the random number generator for each document", ShortName = "reset")] public bool ResetRandomGenerator = LatentDirichletAllocationEstimator.Defaults.ResetRandomGenerator; [Argument(ArgumentType.AtMostOnce, HelpText = "Whether to output the topic-word summary in text format", ShortName = "summary")] public bool OutputTopicWordSummary; } internal sealed class Column : OneToOneColumn { [Argument(ArgumentType.AtMostOnce, HelpText = "The number of topics")] public int? NumTopic; [Argument(ArgumentType.AtMostOnce, HelpText = "Dirichlet prior on document-topic vectors")] public float? AlphaSum; [Argument(ArgumentType.AtMostOnce, HelpText = "Dirichlet prior on vocab-topic vectors")] public float? Beta; [Argument(ArgumentType.Multiple, HelpText = "Number of Metropolis Hasting step")] public int? Mhstep; [Argument(ArgumentType.AtMostOnce, HelpText = "Number of iterations", ShortName = "iter")] public int? NumIterations; [Argument(ArgumentType.AtMostOnce, HelpText = "Compute log likelihood over local dataset on this iteration interval", ShortName = "llInterval")] public int? LikelihoodInterval; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of training threads", ShortName = "t")] public int? NumThreads; [Argument(ArgumentType.AtMostOnce, HelpText = "The threshold of maximum count of tokens per doc", ShortName = "maxNumToken")] public int? NumMaxDocToken; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of words to summarize the topic", ShortName = "ns")] public int? NumSummaryTermPerTopic; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of burn-in iterations", ShortName = "burninIter")] public int? NumBurninIterations = 10; [Argument(ArgumentType.AtMostOnce, HelpText = "Reset the random number generator for each document", ShortName = "reset")] public bool? ResetRandomGenerator; internal static Column Parse(string str) { Contracts.AssertNonEmpty(str); var res = new Column(); if (res.TryParse(str)) return res; return null; } internal bool TryUnparse(StringBuilder sb) { Contracts.AssertValue(sb); if (NumTopic != null || AlphaSum != null || Beta != null || Mhstep != null || NumIterations != null || LikelihoodInterval != null || NumThreads != null || NumMaxDocToken != null || NumSummaryTermPerTopic != null || ResetRandomGenerator != null) return false; return TryUnparseCore(sb); } } /// <summary> /// Provide details about the topics discovered by <a href="https://arxiv.org/abs/1412.1576">LightLDA.</a> /// </summary> public sealed class LdaSummary { // For each topic, provide information about the (item, score) pairs. public readonly ImmutableArray<List<(int Item, float Score)>> ItemScoresPerTopic; // For each topic, provide information about the (item, word, score) tuple. public readonly ImmutableArray<List<(int Item, string Word, float Score)>> WordScoresPerTopic; internal LdaSummary(ImmutableArray<List<(int Item, float Score)>> itemScoresPerTopic) { ItemScoresPerTopic = itemScoresPerTopic; } internal LdaSummary(ImmutableArray<List<(int Item, string Word, float Score)>> wordScoresPerTopic) { WordScoresPerTopic = wordScoresPerTopic; } } [BestFriend] internal LdaSummary GetLdaDetails(int iinfo) { Contracts.Assert(0 <= iinfo && iinfo < _ldas.Length); var ldaState = _ldas[iinfo]; var mapping = _columnMappings[iinfo]; return ldaState.GetLdaSummary(mapping); } private sealed class LdaState : IDisposable { internal readonly LatentDirichletAllocationEstimator.ColumnOptions InfoEx; private readonly int _numVocab; private readonly object _preparationSyncRoot; private readonly object _testSyncRoot; private bool _predictionPreparationDone; private LdaSingleBox _ldaTrainer; private LdaState() { _preparationSyncRoot = new object(); _testSyncRoot = new object(); } internal LdaState(IExceptionContext ectx, LatentDirichletAllocationEstimator.ColumnOptions ex, int numVocab) : this() { Contracts.AssertValue(ectx); ectx.AssertValue(ex, "ex"); ectx.Assert(numVocab >= 0); InfoEx = ex; _numVocab = numVocab; _ldaTrainer = new LdaSingleBox( InfoEx.NumTopic, numVocab, /* Need to set number of vocabulary here */ InfoEx.AlphaSum, InfoEx.Beta, InfoEx.NumIter, InfoEx.LikelihoodInterval, InfoEx.NumThread, InfoEx.MHStep, InfoEx.NumSummaryTermPerTopic, false, InfoEx.NumMaxDocToken); } internal LdaState(IExceptionContext ectx, ModelLoadContext ctx) : this() { ectx.AssertValue(ctx); // *** Binary format *** // <ColInfoEx> // int: vocabnum // long: memblocksize // long: aliasMemBlockSize // (serializing term by term, for one term) // int: term_id, int: topic_num, KeyValuePair<int, int>[]: termTopicVector InfoEx = new LatentDirichletAllocationEstimator.ColumnOptions(ectx, ctx); _numVocab = ctx.Reader.ReadInt32(); ectx.CheckDecode(_numVocab > 0); long memBlockSize = ctx.Reader.ReadInt64(); ectx.CheckDecode(memBlockSize > 0); long aliasMemBlockSize = ctx.Reader.ReadInt64(); ectx.CheckDecode(aliasMemBlockSize > 0); _ldaTrainer = new LdaSingleBox( InfoEx.NumTopic, _numVocab, /* Need to set number of vocabulary here */ InfoEx.AlphaSum, InfoEx.Beta, InfoEx.NumIter, InfoEx.LikelihoodInterval, InfoEx.NumThread, InfoEx.MHStep, InfoEx.NumSummaryTermPerTopic, false, InfoEx.NumMaxDocToken); _ldaTrainer.AllocateModelMemory(_numVocab, InfoEx.NumTopic, memBlockSize, aliasMemBlockSize); for (int i = 0; i < _numVocab; i++) { int termID = ctx.Reader.ReadInt32(); ectx.CheckDecode(termID >= 0); int termTopicNum = ctx.Reader.ReadInt32(); ectx.CheckDecode(termTopicNum >= 0); int[] topicId = new int[termTopicNum]; int[] topicProb = new int[termTopicNum]; for (int j = 0; j < termTopicNum; j++) { topicId[j] = ctx.Reader.ReadInt32(); topicProb[j] = ctx.Reader.ReadInt32(); } //set the topic into _ldaTrainer inner topic table _ldaTrainer.SetModel(termID, topicId, topicProb, termTopicNum); } //do the preparation if (!_predictionPreparationDone) { lock (_preparationSyncRoot) { _ldaTrainer.InitializeBeforeTest(); _predictionPreparationDone = true; } } } internal LdaSummary GetLdaSummary(VBuffer<ReadOnlyMemory<char>> mapping) { if (mapping.Length == 0) { var itemScoresPerTopicBuilder = ImmutableArray.CreateBuilder<List<(int Item, float Score)>>(); for (int i = 0; i < _ldaTrainer.NumTopic; i++) { var scores = _ldaTrainer.GetTopicSummary(i); var itemScores = new List<(int, float)>(); foreach (KeyValuePair<int, float> p in scores) { itemScores.Add((p.Key, p.Value)); } itemScoresPerTopicBuilder.Add(itemScores); } return new LdaSummary(itemScoresPerTopicBuilder.ToImmutable()); } else { ReadOnlyMemory<char> slotName = default; var wordScoresPerTopicBuilder = ImmutableArray.CreateBuilder<List<(int Item, string Word, float Score)>>(); for (int i = 0; i < _ldaTrainer.NumTopic; i++) { var scores = _ldaTrainer.GetTopicSummary(i); var wordScores = new List<(int, string, float)>(); foreach (KeyValuePair<int, float> p in scores) { mapping.GetItemOrDefault(p.Key, ref slotName); wordScores.Add((p.Key, slotName.ToString(), p.Value)); } wordScoresPerTopicBuilder.Add(wordScores); } return new LdaSummary(wordScoresPerTopicBuilder.ToImmutable()); } } internal void Save(ModelSaveContext ctx) { Contracts.AssertValue(ctx); long memBlockSize = 0; long aliasMemBlockSize = 0; _ldaTrainer.GetModelStat(out memBlockSize, out aliasMemBlockSize); // *** Binary format *** // <ColInfoEx> // int: vocabnum // long: memblocksize // long: aliasMemBlockSize // (serializing term by term, for one term) // int: term_id, int: topic_num, KeyValuePair<int, int>[]: termTopicVector InfoEx.Save(ctx); ctx.Writer.Write(_ldaTrainer.NumVocab); ctx.Writer.Write(memBlockSize); ctx.Writer.Write(aliasMemBlockSize); //save model from this interface for (int i = 0; i < _ldaTrainer.NumVocab; i++) { KeyValuePair<int, int>[] termTopicVector = _ldaTrainer.GetModel(i); //write the topic to disk through ctx ctx.Writer.Write(i); //term_id ctx.Writer.Write(termTopicVector.Length); foreach (KeyValuePair<int, int> p in termTopicVector) { ctx.Writer.Write(p.Key); ctx.Writer.Write(p.Value); } } } public void AllocateDataMemory(int docNum, long corpusSize) { _ldaTrainer.AllocateDataMemory(docNum, corpusSize); } public int FeedTrain(IExceptionContext ectx, in VBuffer<Double> input) { Contracts.AssertValue(ectx); // REVIEW: Input the counts to your trainer here. This // is called multiple times. int docSize = 0; int termNum = 0; var inputValues = input.GetValues(); for (int i = 0; i < inputValues.Length; i++) { int termFreq = GetFrequency(inputValues[i]); if (termFreq < 0) { // Ignore this row. return 0; } if (docSize >= InfoEx.NumMaxDocToken - termFreq) break; // If legal then add the term. docSize += termFreq; termNum++; } // Ignore empty doc. if (docSize == 0) return 0; int actualSize = 0; if (input.IsDense) actualSize = _ldaTrainer.LoadDocDense(inputValues, termNum, input.Length); else actualSize = _ldaTrainer.LoadDoc(input.GetIndices(), inputValues, termNum, input.Length); ectx.Assert(actualSize == 2 * docSize + 1, string.Format("The doc size are distinct. Actual: {0}, Expected: {1}", actualSize, 2 * docSize + 1)); return actualSize; } public void CompleteTrain() { //allocate all kinds of in memory sample tables _ldaTrainer.InitializeBeforeTrain(); //call native lda trainer to perform the multi-thread training _ldaTrainer.Train(""); /* Need to pass in an empty string */ } public void Output(in VBuffer<Double> src, ref VBuffer<float> dst, int numBurninIter, bool reset) { // Prediction for a single document. // LdaSingleBox.InitializeBeforeTest() is NOT thread-safe. if (!_predictionPreparationDone) { lock (_preparationSyncRoot) { if (!_predictionPreparationDone) { //do some preparation for building tables in native c++ _ldaTrainer.InitializeBeforeTest(); _predictionPreparationDone = true; } } } int len = InfoEx.NumTopic; var srcValues = src.GetValues(); if (srcValues.Length == 0) { VBufferUtils.Resize(ref dst, len, 0); return; } VBufferEditor<float> editor; // Make sure all the frequencies are valid and truncate if the sum gets too large. int docSize = 0; int termNum = 0; for (int i = 0; i < srcValues.Length; i++) { int termFreq = GetFrequency(srcValues[i]); if (termFreq < 0) { // REVIEW: Should this log a warning message? And what should it produce? // It currently produces a vbuffer of all NA values. // REVIEW: Need a utility method to do this... editor = VBufferEditor.Create(ref dst, len); for (int k = 0; k < len; k++) editor.Values[k] = float.NaN; dst = editor.Commit(); return; } if (docSize >= InfoEx.NumMaxDocToken - termFreq) break; docSize += termFreq; termNum++; } // REVIEW: Too much memory allocation here on each prediction. List<KeyValuePair<int, float>> retTopics; if (src.IsDense) retTopics = _ldaTrainer.TestDocDense(srcValues, termNum, numBurninIter, reset); else retTopics = _ldaTrainer.TestDoc(src.GetIndices(), srcValues, termNum, numBurninIter, reset); int count = retTopics.Count; Contracts.Assert(count <= len); editor = VBufferEditor.Create(ref dst, len, count); double normalizer = 0; for (int i = 0; i < count; i++) { int index = retTopics[i].Key; float value = retTopics[i].Value; Contracts.Assert(value >= 0); Contracts.Assert(0 <= index && index < len); if (count < len) { Contracts.Assert(i == 0 || editor.Indices[i - 1] < index); editor.Indices[i] = index; } else Contracts.Assert(index == i); editor.Values[i] = value; normalizer += value; } if (normalizer > 0) { for (int i = 0; i < count; i++) editor.Values[i] = (float)(editor.Values[i] / normalizer); } dst = editor.Commit(); } public void Dispose() { _ldaTrainer.Dispose(); } } private sealed class Mapper : OneToOneMapperBase { private readonly LatentDirichletAllocationTransformer _parent; private readonly int[] _srcCols; public Mapper(LatentDirichletAllocationTransformer parent, DataViewSchema inputSchema) : base(parent.Host.Register(nameof(Mapper)), parent, inputSchema) { _parent = parent; _srcCols = new int[_parent.ColumnPairs.Length]; for (int i = 0; i < _parent.ColumnPairs.Length; i++) { if (!inputSchema.TryGetColumnIndex(_parent.ColumnPairs[i].inputColumnName, out _srcCols[i])) throw Host.ExceptSchemaMismatch(nameof(inputSchema), "input", _parent.ColumnPairs[i].inputColumnName); var srcCol = inputSchema[_srcCols[i]]; var srcType = srcCol.Type as VectorType; if (srcType == null || !srcType.IsKnownSize || !(srcType.ItemType is NumberDataViewType)) throw Host.ExceptSchemaMismatch(nameof(inputSchema), "input", _parent.ColumnPairs[i].inputColumnName, "known-size vector of float", srcCol.Type.ToString()); } } protected override DataViewSchema.DetachedColumn[] GetOutputColumnsCore() { var result = new DataViewSchema.DetachedColumn[_parent.ColumnPairs.Length]; for (int i = 0; i < _parent.ColumnPairs.Length; i++) { var info = _parent._columns[i]; result[i] = new DataViewSchema.DetachedColumn(_parent.ColumnPairs[i].outputColumnName, new VectorType(NumberDataViewType.Single, info.NumTopic), null); } return result; } protected override Delegate MakeGetter(DataViewRow input, int iinfo, Func<int, bool> activeOutput, out Action disposer) { Contracts.AssertValue(input); Contracts.Assert(0 <= iinfo && iinfo < _parent.ColumnPairs.Length); disposer = null; return GetTopic(input, iinfo); } private ValueGetter<VBuffer<float>> GetTopic(DataViewRow input, int iinfo) { var getSrc = RowCursorUtils.GetVecGetterAs<Double>(NumberDataViewType.Double, input, _srcCols[iinfo]); var src = default(VBuffer<Double>); var lda = _parent._ldas[iinfo]; int numBurninIter = lda.InfoEx.NumBurninIter; bool reset = lda.InfoEx.ResetRandomGenerator; return (ref VBuffer<float> dst) => { // REVIEW: This will work, but there are opportunities for caching // based on input.Counter that are probably worthwhile given how long inference takes. getSrc(ref src); lda.Output(in src, ref dst, numBurninIter, reset); }; } } internal const string LoaderSignature = "LdaTransform"; private static VersionInfo GetVersionInfo() { return new VersionInfo( modelSignature: "LIGHTLDA", verWrittenCur: 0x00010001, // Initial verReadableCur: 0x00010001, verWeCanReadBack: 0x00010001, loaderSignature: LoaderSignature, loaderAssemblyName: typeof(LatentDirichletAllocationTransformer).Assembly.FullName); } private readonly LatentDirichletAllocationEstimator.ColumnOptions[] _columns; private readonly LdaState[] _ldas; private readonly List<VBuffer<ReadOnlyMemory<char>>> _columnMappings; private const string RegistrationName = "LightLda"; private const string WordTopicModelFilename = "word_topic_summary.txt"; internal const string Summary = "The LDA transform implements LightLDA, a state-of-the-art implementation of Latent Dirichlet Allocation."; internal const string UserName = "Latent Dirichlet Allocation Transform"; internal const string ShortName = "LightLda"; private static (string outputColumnName, string inputColumnName)[] GetColumnPairs(LatentDirichletAllocationEstimator.ColumnOptions[] columns) { Contracts.CheckValue(columns, nameof(columns)); return columns.Select(x => (x.Name, x.InputColumnName)).ToArray(); } /// <summary> /// Initializes a new <see cref="LatentDirichletAllocationTransformer"/> object. /// </summary> /// <param name="env">Host Environment.</param> /// <param name="ldas">An array of LdaState objects, where ldas[i] is learnt from the i-th element of <paramref name="columns"/>.</param> /// <param name="columnMappings">A list of mappings, where columnMapping[i] is a map of slot names for the i-th element of <paramref name="columns"/>.</param> /// <param name="columns">Describes the parameters of the LDA process for each column pair.</param> private LatentDirichletAllocationTransformer(IHostEnvironment env, LdaState[] ldas, List<VBuffer<ReadOnlyMemory<char>>> columnMappings, params LatentDirichletAllocationEstimator.ColumnOptions[] columns) : base(Contracts.CheckRef(env, nameof(env)).Register(nameof(LatentDirichletAllocationTransformer)), GetColumnPairs(columns)) { Host.AssertNonEmpty(ColumnPairs); _ldas = ldas; _columnMappings = columnMappings; _columns = columns; } private LatentDirichletAllocationTransformer(IHost host, ModelLoadContext ctx) : base(host, ctx) { Host.AssertValue(ctx); // *** Binary format *** // <prefix handled in static Create method> // <base> // ldaState[num infos]: The LDA parameters // Note: columnsLength would be just one in most cases. var columnsLength = ColumnPairs.Length; _columns = new LatentDirichletAllocationEstimator.ColumnOptions[columnsLength]; _ldas = new LdaState[columnsLength]; for (int i = 0; i < _ldas.Length; i++) { _ldas[i] = new LdaState(Host, ctx); _columns[i] = _ldas[i].InfoEx; } } internal static LatentDirichletAllocationTransformer TrainLdaTransformer(IHostEnvironment env, IDataView inputData, params LatentDirichletAllocationEstimator.ColumnOptions[] columns) { var ldas = new LdaState[columns.Length]; List<VBuffer<ReadOnlyMemory<char>>> columnMappings; using (var ch = env.Start("Train")) { columnMappings = Train(env, ch, inputData, ldas, columns); } return new LatentDirichletAllocationTransformer(env, ldas, columnMappings, columns); } private void Dispose(bool disposing) { if (_ldas != null) { foreach (var state in _ldas) state?.Dispose(); } if (disposing) GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); } ~LatentDirichletAllocationTransformer() { Dispose(false); } // Factory method for SignatureLoadDataTransform. private static IDataTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input) => Create(env, ctx).MakeDataTransform(input); // Factory method for SignatureLoadRowMapper. private static IRowMapper Create(IHostEnvironment env, ModelLoadContext ctx, DataViewSchema inputSchema) => Create(env, ctx).MakeRowMapper(inputSchema); // Factory method for SignatureDataTransform. private static IDataTransform Create(IHostEnvironment env, Options options, IDataView input) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(options, nameof(options)); env.CheckValue(input, nameof(input)); env.CheckValue(options.Columns, nameof(options.Columns)); var cols = options.Columns.Select(colPair => new LatentDirichletAllocationEstimator.ColumnOptions(colPair, options)).ToArray(); return TrainLdaTransformer(env, input, cols).MakeDataTransform(input); } // Factory method for SignatureLoadModel private static LatentDirichletAllocationTransformer Create(IHostEnvironment env, ModelLoadContext ctx) { Contracts.CheckValue(env, nameof(env)); var h = env.Register(RegistrationName); h.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(GetVersionInfo()); return h.Apply( "Loading Model", ch => { // *** Binary Format *** // int: sizeof(float) // <remainder handled in ctors> int cbFloat = ctx.Reader.ReadInt32(); h.CheckDecode(cbFloat == sizeof(float)); return new LatentDirichletAllocationTransformer(h, ctx); }); } private protected override void SaveModel(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); ctx.SetVersionInfo(GetVersionInfo()); // *** Binary format *** // int: sizeof(float) // <base> // ldaState[num infos]: The LDA parameters ctx.Writer.Write(sizeof(float)); SaveColumns(ctx); for (int i = 0; i < _ldas.Length; i++) { _ldas[i].Save(ctx); } } private static int GetFrequency(double value) { int result = (int)value; if (!(result == value && result >= 0)) return -1; return result; } private static List<VBuffer<ReadOnlyMemory<char>>> Train(IHostEnvironment env, IChannel ch, IDataView inputData, LdaState[] states, params LatentDirichletAllocationEstimator.ColumnOptions[] columns) { env.AssertValue(ch); ch.AssertValue(inputData); ch.AssertValue(states); ch.Assert(states.Length == columns.Length); var activeColumns = new List<DataViewSchema.Column>(); int[] numVocabs = new int[columns.Length]; int[] srcCols = new int[columns.Length]; var columnMappings = new List<VBuffer<ReadOnlyMemory<char>>>(); var inputSchema = inputData.Schema; for (int i = 0; i < columns.Length; i++) { if (!inputData.Schema.TryGetColumnIndex(columns[i].InputColumnName, out int srcCol)) throw env.ExceptSchemaMismatch(nameof(inputData), "input", columns[i].InputColumnName); var srcColType = inputSchema[srcCol].Type as VectorType; if (srcColType == null || !srcColType.IsKnownSize || !(srcColType.ItemType is NumberDataViewType)) throw env.ExceptSchemaMismatch(nameof(inputSchema), "input", columns[i].InputColumnName, "known-size vector of float", srcColType.ToString()); srcCols[i] = srcCol; activeColumns.Add(inputData.Schema[srcCol]); numVocabs[i] = 0; VBuffer<ReadOnlyMemory<char>> dst = default; if (inputSchema[srcCol].HasSlotNames(srcColType.Size)) inputSchema[srcCol].Annotations.GetValue(AnnotationUtils.Kinds.SlotNames, ref dst); else dst = default(VBuffer<ReadOnlyMemory<char>>); columnMappings.Add(dst); } //the current lda needs the memory allocation before feedin data, so needs two sweeping of the data, //one for the pre-calc memory, one for feedin data really //another solution can be prepare these two value externally and put them in the beginning of the input file. long[] corpusSize = new long[columns.Length]; int[] numDocArray = new int[columns.Length]; using (var cursor = inputData.GetRowCursor(activeColumns)) { var getters = new ValueGetter<VBuffer<Double>>[columns.Length]; for (int i = 0; i < columns.Length; i++) { corpusSize[i] = 0; numDocArray[i] = 0; getters[i] = RowCursorUtils.GetVecGetterAs<Double>(NumberDataViewType.Double, cursor, srcCols[i]); } VBuffer<Double> src = default; long rowCount = 0; while (cursor.MoveNext()) { ++rowCount; for (int i = 0; i < columns.Length; i++) { int docSize = 0; getters[i](ref src); // compute term, doc instance#. var srcValues = src.GetValues(); for (int termID = 0; termID < srcValues.Length; termID++) { int termFreq = GetFrequency(srcValues[termID]); if (termFreq < 0) { // Ignore this row. docSize = 0; break; } if (docSize >= columns[i].NumMaxDocToken - termFreq) break; //control the document length //if legal then add the term docSize += termFreq; } // Ignore empty doc if (docSize == 0) continue; numDocArray[i]++; corpusSize[i] += docSize * 2 + 1; // in the beggining of each doc, there is a cursor variable // increase numVocab if needed. if (numVocabs[i] < src.Length) numVocabs[i] = src.Length; } } // No data to train on, just return if (rowCount == 0) return columnMappings; for (int i = 0; i < columns.Length; ++i) { if (numDocArray[i] != rowCount) { ch.Assert(numDocArray[i] < rowCount); ch.Warning($"Column '{columns[i].InputColumnName}' has skipped {rowCount - numDocArray[i]} of {rowCount} rows either empty or with negative, non-finite, or fractional values."); } } } // Initialize all LDA states for (int i = 0; i < columns.Length; i++) { var state = new LdaState(env, columns[i], numVocabs[i]); if (numDocArray[i] == 0 || corpusSize[i] == 0) throw ch.Except("The specified documents are all empty in column '{0}'.", columns[i].InputColumnName); state.AllocateDataMemory(numDocArray[i], corpusSize[i]); states[i] = state; } using (var cursor = inputData.GetRowCursor(activeColumns)) { int[] docSizeCheck = new int[columns.Length]; // This could be optimized so that if multiple trainers consume the same column, it is // fed into the train method once. var getters = new ValueGetter<VBuffer<Double>>[columns.Length]; for (int i = 0; i < columns.Length; i++) { docSizeCheck[i] = 0; getters[i] = RowCursorUtils.GetVecGetterAs<Double>(NumberDataViewType.Double, cursor, srcCols[i]); } VBuffer<double> src = default; while (cursor.MoveNext()) { for (int i = 0; i < columns.Length; i++) { getters[i](ref src); docSizeCheck[i] += states[i].FeedTrain(env, in src); } } for (int i = 0; i < columns.Length; i++) { env.Assert(corpusSize[i] == docSizeCheck[i]); states[i].CompleteTrain(); } } return columnMappings; } private protected override IRowMapper MakeRowMapper(DataViewSchema schema) => new Mapper(this, schema); } /// <include file='doc.xml' path='doc/members/member[@name="LightLDA"]/*' /> public sealed class LatentDirichletAllocationEstimator : IEstimator<LatentDirichletAllocationTransformer> { [BestFriend] internal static class Defaults { public const int NumTopic = 100; public const float AlphaSum = 100; public const float Beta = 0.01f; public const int Mhstep = 4; public const int NumIterations = 200; public const int LikelihoodInterval = 5; public const int NumThreads = 0; public const int NumMaxDocToken = 512; public const int NumSummaryTermPerTopic = 10; public const int NumBurninIterations = 10; public const bool ResetRandomGenerator = false; } private readonly IHost _host; private readonly ImmutableArray<ColumnOptions> _columns; /// <include file='doc.xml' path='doc/members/member[@name="LightLDA"]/*' /> /// <param name="env">The environment.</param> /// <param name="outputColumnName">Name of the column resulting from the transformation of <paramref name="inputColumnName"/>.</param> /// <param name="inputColumnName">Name of the column to transform. If set to <see langword="null"/>, the value of the <paramref name="outputColumnName"/> will be used as source.</param> /// <param name="numTopic">The number of topics.</param> /// <param name="alphaSum">Dirichlet prior on document-topic vectors.</param> /// <param name="beta">Dirichlet prior on vocab-topic vectors.</param> /// <param name="mhstep">Number of Metropolis Hasting step.</param> /// <param name="numIterations">Number of iterations.</param> /// <param name="likelihoodInterval">Compute log likelihood over local dataset on this iteration interval.</param> /// <param name="numThreads">The number of training threads. Default value depends on number of logical processors.</param> /// <param name="numMaxDocToken">The threshold of maximum count of tokens per doc.</param> /// <param name="numSummaryTermPerTopic">The number of words to summarize the topic.</param> /// <param name="numBurninIterations">The number of burn-in iterations.</param> /// <param name="resetRandomGenerator">Reset the random number generator for each document.</param> internal LatentDirichletAllocationEstimator(IHostEnvironment env, string outputColumnName, string inputColumnName = null, int numTopic = Defaults.NumTopic, float alphaSum = Defaults.AlphaSum, float beta = Defaults.Beta, int mhstep = Defaults.Mhstep, int numIterations = Defaults.NumIterations, int likelihoodInterval = Defaults.LikelihoodInterval, int numThreads = Defaults.NumThreads, int numMaxDocToken = Defaults.NumMaxDocToken, int numSummaryTermPerTopic = Defaults.NumSummaryTermPerTopic, int numBurninIterations = Defaults.NumBurninIterations, bool resetRandomGenerator = Defaults.ResetRandomGenerator) : this(env, new[] { new ColumnOptions(outputColumnName, inputColumnName ?? outputColumnName, numTopic, alphaSum, beta, mhstep, numIterations, likelihoodInterval, numThreads, numMaxDocToken, numSummaryTermPerTopic, numBurninIterations, resetRandomGenerator) }) { } /// <include file='doc.xml' path='doc/members/member[@name="LightLDA"]/*' /> /// <param name="env">The environment.</param> /// <param name="columns">Describes the parameters of the LDA process for each column pair.</param> internal LatentDirichletAllocationEstimator(IHostEnvironment env, params ColumnOptions[] columns) { Contracts.CheckValue(env, nameof(env)); _host = env.Register(nameof(LatentDirichletAllocationEstimator)); _columns = columns.ToImmutableArray(); } /// <summary> /// Describes how the transformer handles one column pair. /// </summary> public sealed class ColumnOptions { /// <summary> /// Name of the column resulting from the transformation of <cref see="InputColumnName"/>. /// </summary> public readonly string Name; /// <summary> /// Name of column to transform. /// </summary> public readonly string InputColumnName; /// <summary> /// The number of topics. /// </summary> public readonly int NumTopic; /// <summary> /// Dirichlet prior on document-topic vectors. /// </summary> public readonly float AlphaSum; /// <summary> /// Dirichlet prior on vocab-topic vectors. /// </summary> public readonly float Beta; /// <summary> /// Number of Metropolis Hasting step. /// </summary> public readonly int MHStep; /// <summary> /// Number of iterations. /// </summary> public readonly int NumIter; /// <summary> /// Compute log likelihood over local dataset on this iteration interval. /// </summary> public readonly int LikelihoodInterval; /// <summary> /// The number of training threads. /// </summary> public readonly int NumThread; /// <summary> /// The threshold of maximum count of tokens per doc. /// </summary> public readonly int NumMaxDocToken; /// <summary> /// The number of words to summarize the topic. /// </summary> public readonly int NumSummaryTermPerTopic; /// <summary> /// The number of burn-in iterations. /// </summary> public readonly int NumBurninIter; /// <summary> /// Reset the random number generator for each document. /// </summary> public readonly bool ResetRandomGenerator; /// <summary> /// Describes how the transformer handles one column pair. /// </summary> /// <param name="name">The column containing the output scores over a set of topics, represented as a vector of floats. </param> /// <param name="inputColumnName">The column representing the document as a vector of floats.A null value for the column means <paramref name="inputColumnName"/> is replaced. </param> /// <param name="numTopic">The number of topics.</param> /// <param name="alphaSum">Dirichlet prior on document-topic vectors.</param> /// <param name="beta">Dirichlet prior on vocab-topic vectors.</param> /// <param name="mhStep">Number of Metropolis Hasting step.</param> /// <param name="numIter">Number of iterations.</param> /// <param name="likelihoodInterval">Compute log likelihood over local dataset on this iteration interval.</param> /// <param name="numThread">The number of training threads. Default value depends on number of logical processors.</param> /// <param name="numMaxDocToken">The threshold of maximum count of tokens per doc.</param> /// <param name="numSummaryTermPerTopic">The number of words to summarize the topic.</param> /// <param name="numBurninIter">The number of burn-in iterations.</param> /// <param name="resetRandomGenerator">Reset the random number generator for each document.</param> public ColumnOptions(string name, string inputColumnName = null, int numTopic = LatentDirichletAllocationEstimator.Defaults.NumTopic, float alphaSum = LatentDirichletAllocationEstimator.Defaults.AlphaSum, float beta = LatentDirichletAllocationEstimator.Defaults.Beta, int mhStep = LatentDirichletAllocationEstimator.Defaults.Mhstep, int numIter = LatentDirichletAllocationEstimator.Defaults.NumIterations, int likelihoodInterval = LatentDirichletAllocationEstimator.Defaults.LikelihoodInterval, int numThread = LatentDirichletAllocationEstimator.Defaults.NumThreads, int numMaxDocToken = LatentDirichletAllocationEstimator.Defaults.NumMaxDocToken, int numSummaryTermPerTopic = LatentDirichletAllocationEstimator.Defaults.NumSummaryTermPerTopic, int numBurninIter = LatentDirichletAllocationEstimator.Defaults.NumBurninIterations, bool resetRandomGenerator = LatentDirichletAllocationEstimator.Defaults.ResetRandomGenerator) { Contracts.CheckValue(name, nameof(name)); Contracts.CheckValueOrNull(inputColumnName); Contracts.CheckParam(numTopic > 0, nameof(numTopic), "Must be positive."); Contracts.CheckParam(mhStep > 0, nameof(mhStep), "Must be positive."); Contracts.CheckParam(numIter > 0, nameof(numIter), "Must be positive."); Contracts.CheckParam(likelihoodInterval > 0, nameof(likelihoodInterval), "Must be positive."); Contracts.CheckParam(numThread >= 0, nameof(numThread), "Must be positive or zero."); Contracts.CheckParam(numMaxDocToken > 0, nameof(numMaxDocToken), "Must be positive."); Contracts.CheckParam(numSummaryTermPerTopic > 0, nameof(numSummaryTermPerTopic), "Must be positive"); Contracts.CheckParam(numBurninIter >= 0, nameof(numBurninIter), "Must be non-negative."); Name = name; InputColumnName = inputColumnName ?? name; NumTopic = numTopic; AlphaSum = alphaSum; Beta = beta; MHStep = mhStep; NumIter = numIter; LikelihoodInterval = likelihoodInterval; NumThread = numThread; NumMaxDocToken = numMaxDocToken; NumSummaryTermPerTopic = numSummaryTermPerTopic; NumBurninIter = numBurninIter; ResetRandomGenerator = resetRandomGenerator; } internal ColumnOptions(LatentDirichletAllocationTransformer.Column item, LatentDirichletAllocationTransformer.Options options) : this(item.Name, item.Source ?? item.Name, item.NumTopic ?? options.NumTopic, item.AlphaSum ?? options.AlphaSum, item.Beta ?? options.Beta, item.Mhstep ?? options.Mhstep, item.NumIterations ?? options.NumIterations, item.LikelihoodInterval ?? options.LikelihoodInterval, item.NumThreads ?? options.NumThreads, item.NumMaxDocToken ?? options.NumMaxDocToken, item.NumSummaryTermPerTopic ?? options.NumSummaryTermPerTopic, item.NumBurninIterations ?? options.NumBurninIterations, item.ResetRandomGenerator ?? options.ResetRandomGenerator) { } internal ColumnOptions(IExceptionContext ectx, ModelLoadContext ctx) { Contracts.AssertValue(ectx); ectx.AssertValue(ctx); // *** Binary format *** // int NumTopic; // float AlphaSum; // float Beta; // int MHStep; // int NumIter; // int LikelihoodInterval; // int NumThread; // int NumMaxDocToken; // int NumSummaryTermPerTopic; // int NumBurninIter; // byte ResetRandomGenerator; NumTopic = ctx.Reader.ReadInt32(); ectx.CheckDecode(NumTopic > 0); AlphaSum = ctx.Reader.ReadSingle(); Beta = ctx.Reader.ReadSingle(); MHStep = ctx.Reader.ReadInt32(); ectx.CheckDecode(MHStep > 0); NumIter = ctx.Reader.ReadInt32(); ectx.CheckDecode(NumIter > 0); LikelihoodInterval = ctx.Reader.ReadInt32(); ectx.CheckDecode(LikelihoodInterval > 0); NumThread = ctx.Reader.ReadInt32(); ectx.CheckDecode(NumThread >= 0); NumMaxDocToken = ctx.Reader.ReadInt32(); ectx.CheckDecode(NumMaxDocToken > 0); NumSummaryTermPerTopic = ctx.Reader.ReadInt32(); ectx.CheckDecode(NumSummaryTermPerTopic > 0); NumBurninIter = ctx.Reader.ReadInt32(); ectx.CheckDecode(NumBurninIter >= 0); ResetRandomGenerator = ctx.Reader.ReadBoolByte(); } internal void Save(ModelSaveContext ctx) { Contracts.AssertValue(ctx); // *** Binary format *** // int NumTopic; // float AlphaSum; // float Beta; // int MHStep; // int NumIter; // int LikelihoodInterval; // int NumThread; // int NumMaxDocToken; // int NumSummaryTermPerTopic; // int NumBurninIter; // byte ResetRandomGenerator; ctx.Writer.Write(NumTopic); ctx.Writer.Write(AlphaSum); ctx.Writer.Write(Beta); ctx.Writer.Write(MHStep); ctx.Writer.Write(NumIter); ctx.Writer.Write(LikelihoodInterval); ctx.Writer.Write(NumThread); ctx.Writer.Write(NumMaxDocToken); ctx.Writer.Write(NumSummaryTermPerTopic); ctx.Writer.Write(NumBurninIter); ctx.Writer.WriteBoolByte(ResetRandomGenerator); } } /// <summary> /// Returns the <see cref="SchemaShape"/> of the schema which will be produced by the transformer. /// Used for schema propagation and verification in a pipeline. /// </summary> public SchemaShape GetOutputSchema(SchemaShape inputSchema) { _host.CheckValue(inputSchema, nameof(inputSchema)); var result = inputSchema.ToDictionary(x => x.Name); foreach (var colInfo in _columns) { if (!inputSchema.TryFindColumn(colInfo.InputColumnName, out var col)) throw _host.ExceptSchemaMismatch(nameof(inputSchema), "input", colInfo.InputColumnName); if (col.ItemType.RawType != typeof(float) || col.Kind == SchemaShape.Column.VectorKind.Scalar) throw _host.ExceptSchemaMismatch(nameof(inputSchema), "input", colInfo.InputColumnName, "vector of float", col.GetTypeString()); result[colInfo.Name] = new SchemaShape.Column(colInfo.Name, SchemaShape.Column.VectorKind.Vector, NumberDataViewType.Single, false); } return new SchemaShape(result.Values); } /// <summary> /// Trains and returns a <see cref="LatentDirichletAllocationTransformer"/>. /// </summary> public LatentDirichletAllocationTransformer Fit(IDataView input) { return LatentDirichletAllocationTransformer.TrainLdaTransformer(_host, input, _columns.ToArray()); } } }
46.623876
226
0.568124
[ "MIT" ]
IndigoShock/machinelearning
src/Microsoft.ML.Transforms/Text/LdaTransform.cs
57,025
C#
// Copyright (c) 2021 homuler // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Rendering; using Stopwatch = System.Diagnostics.Stopwatch; namespace Mediapipe.Unity { public abstract class GraphRunner : MonoBehaviour { public enum ConfigType { None, CPU, GPU, OpenGLES, } #pragma warning disable IDE1006 // TODO: make it static protected string TAG => GetType().Name; #pragma warning restore IDE1006 [SerializeField] private TextAsset _cpuConfig = null; [SerializeField] private TextAsset _gpuConfig = null; [SerializeField] private TextAsset _openGlEsConfig = null; [SerializeField] private long _timeoutMicrosec = 0; private static readonly GlobalInstanceTable<int, GraphRunner> _InstanceTable = new GlobalInstanceTable<int, GraphRunner>(5); private static readonly Dictionary<IntPtr, int> _NameTable = new Dictionary<IntPtr, int>(); protected RunningMode runningMode { get; private set; } = RunningMode.Async; private bool _isRunning = false; public InferenceMode inferenceMode => configType == ConfigType.CPU ? InferenceMode.CPU : InferenceMode.GPU; public virtual ConfigType configType { get { if (GpuManager.IsInitialized) { #if UNITY_ANDROID if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3 && _openGlEsConfig != null) { return ConfigType.OpenGLES; } #endif if (_gpuConfig != null) { return ConfigType.GPU; } } return _cpuConfig != null ? ConfigType.CPU : ConfigType.None; } } public TextAsset textConfig { get { switch (configType) { case ConfigType.CPU: return _cpuConfig; case ConfigType.GPU: return _gpuConfig; case ConfigType.OpenGLES: return _openGlEsConfig; case ConfigType.None: default: return null; } } } public long timeoutMicrosec { get => _timeoutMicrosec; set => _timeoutMicrosec = (long)Mathf.Max(0, value); } public long timeoutMillisec { get => timeoutMicrosec / 1000; set => timeoutMicrosec = value * 1000; } public RotationAngle rotation { get; private set; } = 0; private Stopwatch _stopwatch; protected CalculatorGraph calculatorGraph { get; private set; } protected Timestamp latestTimestamp; protected virtual void Start() { _InstanceTable.Add(GetInstanceID(), this); } protected virtual void OnDestroy() { Stop(); } public WaitForResult WaitForInit(RunningMode runningMode) { return new WaitForResult(this, Initialize(runningMode)); } public virtual IEnumerator Initialize(RunningMode runningMode) { this.runningMode = runningMode; Logger.LogInfo(TAG, $"Config Type = {configType}"); Logger.LogInfo(TAG, $"Running Mode = {runningMode}"); InitializeCalculatorGraph().AssertOk(); _stopwatch = new Stopwatch(); _stopwatch.Start(); Logger.LogInfo(TAG, "Loading dependent assets..."); var assetRequests = RequestDependentAssets(); yield return new WaitWhile(() => assetRequests.Any((request) => request.keepWaiting)); var errors = assetRequests.Where((request) => request.isError).Select((request) => request.error).ToList(); if (errors.Count > 0) { foreach (var error in errors) { Logger.LogError(TAG, error); } throw new InternalException("Failed to prepare dependent assets"); } } public abstract void StartRun(ImageSource imageSource); protected void StartRun(SidePacket sidePacket) { calculatorGraph.StartRun(sidePacket).AssertOk(); _isRunning = true; } public virtual void Stop() { if (calculatorGraph != null) { if (_isRunning) { using (var status = calculatorGraph.CloseAllPacketSources()) { if (!status.Ok()) { Logger.LogError(TAG, status.ToString()); } } using (var status = calculatorGraph.WaitUntilDone()) { if (!status.Ok()) { Logger.LogError(TAG, status.ToString()); } } } _isRunning = false; var _ = _NameTable.Remove(calculatorGraph.mpPtr); calculatorGraph.Dispose(); calculatorGraph = null; } if (_stopwatch != null && _stopwatch.IsRunning) { _stopwatch.Stop(); } } protected void AddPacketToInputStream<T>(string streamName, Packet<T> packet) { calculatorGraph.AddPacketToInputStream(streamName, packet).AssertOk(); } protected void AddTextureFrameToInputStream(string streamName, TextureFrame textureFrame) { latestTimestamp = GetCurrentTimestamp(); if (configType == ConfigType.OpenGLES) { var gpuBuffer = textureFrame.BuildGpuBuffer(GpuManager.GlCalculatorHelper.GetGlContext()); AddPacketToInputStream(streamName, new GpuBufferPacket(gpuBuffer, latestTimestamp)); return; } var imageFrame = textureFrame.BuildImageFrame(); textureFrame.Release(); AddPacketToInputStream(streamName, new ImageFramePacket(imageFrame, latestTimestamp)); } protected bool TryGetNext<TPacket, TValue>(OutputStream<TPacket, TValue> stream, out TValue value, bool allowBlock, long currentTimestampMicrosec) where TPacket : Packet<TValue>, new() { var result = stream.TryGetNext(out value, allowBlock); return result || allowBlock || stream.ResetTimestampIfTimedOut(currentTimestampMicrosec, timeoutMicrosec); } protected long GetCurrentTimestampMicrosec() { return _stopwatch == null || !_stopwatch.IsRunning ? -1 : _stopwatch.ElapsedTicks / (TimeSpan.TicksPerMillisecond / 1000); } protected Timestamp GetCurrentTimestamp() { var microsec = GetCurrentTimestampMicrosec(); return microsec < 0 ? Timestamp.Unset() : new Timestamp(microsec); } protected Status InitializeCalculatorGraph() { calculatorGraph = new CalculatorGraph(); _NameTable.Add(calculatorGraph.mpPtr, GetInstanceID()); // NOTE: There's a simpler way to initialize CalculatorGraph. // // calculatorGraph = new CalculatorGraph(config.text); // // However, if the config format is invalid, this code does not initialize CalculatorGraph and does not throw exceptions either. // The problem is that if you call ObserveStreamOutput in this state, the program will crash. // The following code is not very efficient, but it will return Non-OK status when an invalid configuration is given. try { var baseConfig = textConfig == null ? null : CalculatorGraphConfig.Parser.ParseFromTextFormat(textConfig.text); if (baseConfig == null) { throw new InvalidOperationException("Failed to get the text config. Check if the config is set to GraphRunner"); } var status = ConfigureCalculatorGraph(baseConfig); return !status.Ok() || inferenceMode == InferenceMode.CPU ? status : calculatorGraph.SetGpuResources(GpuManager.GpuResources); } catch (Exception e) { return Status.FailedPrecondition(e.ToString()); } } /// <summary> /// Configure and initialize the <see cref="CalculatorGraph" />. /// </summary> /// <remarks> /// This is the main process in <see cref="InitializeCalculatorGraph" />.<br /> /// At least, <c>calculatorGraph.Initialize</c> must be called here. /// In addition to that, <see cref="OutputStream" /> instances should be initialized. /// </remarks> /// <param name="config"> /// A <see cref="CalculatorGraphConfig" /> instance corresponding to <see cref="textConfig" />.<br /> /// It can be dynamically modified here. /// </param> protected virtual Status ConfigureCalculatorGraph(CalculatorGraphConfig config) { return calculatorGraph.Initialize(config); } protected void SetImageTransformationOptions(SidePacket sidePacket, ImageSource imageSource, bool expectedToBeMirrored = false) { // NOTE: The origin is left-bottom corner in Unity, and right-top corner in MediaPipe. rotation = imageSource.rotation.Reverse(); var inputRotation = rotation; var isInverted = CoordinateSystem.ImageCoordinate.IsInverted(rotation); var shouldBeMirrored = imageSource.isHorizontallyFlipped ^ expectedToBeMirrored; var inputHorizontallyFlipped = isInverted ^ shouldBeMirrored; var inputVerticallyFlipped = !isInverted; if ((inputHorizontallyFlipped && inputVerticallyFlipped) || rotation == RotationAngle.Rotation180) { inputRotation = inputRotation.Add(RotationAngle.Rotation180); inputHorizontallyFlipped = !inputHorizontallyFlipped; inputVerticallyFlipped = !inputVerticallyFlipped; } Logger.LogDebug($"input_rotation = {inputRotation}, input_horizontally_flipped = {inputHorizontallyFlipped}, input_vertically_flipped = {inputVerticallyFlipped}"); sidePacket.Emplace("input_rotation", new IntPacket((int)inputRotation)); sidePacket.Emplace("input_horizontally_flipped", new BoolPacket(inputHorizontallyFlipped)); sidePacket.Emplace("input_vertically_flipped", new BoolPacket(inputVerticallyFlipped)); } protected WaitForResult WaitForAsset(string assetName, string uniqueKey, long timeoutMillisec, bool overwrite = false) { return new WaitForResult(this, AssetLoader.PrepareAssetAsync(assetName, uniqueKey, overwrite), timeoutMillisec); } protected WaitForResult WaitForAsset(string assetName, long timeoutMillisec, bool overwrite = false) { return WaitForAsset(assetName, assetName, timeoutMillisec, overwrite); } protected WaitForResult WaitForAsset(string assetName, string uniqueKey, bool overwrite = false) { return new WaitForResult(this, AssetLoader.PrepareAssetAsync(assetName, uniqueKey, overwrite)); } protected WaitForResult WaitForAsset(string assetName, bool overwrite = false) { return WaitForAsset(assetName, assetName, overwrite); } protected abstract IList<WaitForResult> RequestDependentAssets(); } }
34.294872
188
0.674486
[ "MIT" ]
dahburj/MediaPipeUnityPlugin
Assets/MediaPipeUnity/Samples/Common/Scripts/GraphRunner.cs
10,700
C#
using Contoso.Apps.SportsLeague.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace Contoso.Apps.SportsLeague.Data.Logic { public class ShoppingCartActions { private readonly ProductContext _db; public ShoppingCartActions(ProductContext context, string cartId) { _db = context; this.ShoppingCartId = cartId; } public string ShoppingCartId { get; private set; } public async Task AddToCart(int id) { // Retrieve the product from the database. //ShoppingCartId = GetCartId(); var cartItem = _db.ShoppingCartItems.SingleOrDefault( c => c.CartId == ShoppingCartId && c.ProductId == id); if (cartItem == null) { // Create a new cart item if no cart item exists. cartItem = new CartItem { ItemId = Guid.NewGuid().ToString(), ProductId = id, CartId = ShoppingCartId, Product = _db.Products.SingleOrDefault( p => p.ProductID == id), Quantity = 1, DateCreated = DateTime.Now }; await _db.ShoppingCartItems.AddAsync(cartItem); } else { // If the item does exist in the cart, // then add one to the quantity. cartItem.Quantity++; } await _db.SaveChangesAsync(); } public List<CartItem> GetCartItems() { //ShoppingCartId = GetCartId(); return (from c in _db.ShoppingCartItems.Include("Product") where c.CartId == ShoppingCartId select c).ToList(); } public decimal GetTotal() { //ShoppingCartId = GetCartId(); // Multiply product price by quantity of that product to get // the current price for each of those products in the cart. // Sum all product price totals to get the cart total. decimal? total = decimal.Zero; total = (decimal?)(from cartItems in _db.ShoppingCartItems where cartItems.CartId == ShoppingCartId select (int?)cartItems.Quantity * cartItems.Product.UnitPrice).Sum(); return total ?? decimal.Zero; } public async Task UpdateShoppingCartDatabase(String cartId, ShoppingCartUpdates[] CartItemUpdates) { try { int CartItemCount = CartItemUpdates.Count(); List<CartItem> myCart = GetCartItems(); foreach (var cartItem in myCart) { // Iterate through all rows within shopping cart list for (int i = 0; i < CartItemCount; i++) { if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId) { if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true) { await RemoveItem(cartId, cartItem.ProductId); } else { await UpdateItem(cartId, cartItem.ProductId, CartItemUpdates[i].PurchaseQuantity); } } } } } catch (Exception exp) { throw new Exception("ERROR: Unable to Update Cart Database - " + exp.Message.ToString(), exp); } } public async Task RemoveItem(string removeCartID, int removeProductID) { try { var myItem = (from c in _db.ShoppingCartItems where c.CartId == removeCartID && c.Product.ProductID == removeProductID select c).FirstOrDefault(); if (myItem != null) { // Remove Item. _db.ShoppingCartItems.Remove(myItem); await _db.SaveChangesAsync(); } } catch (Exception exp) { throw new Exception("ERROR: Unable to Remove Cart Item - " + exp.Message.ToString(), exp); } } public async Task UpdateItem(string updateCartID, int updateProductID, int quantity) { try { var myItem = (from c in _db.ShoppingCartItems where c.CartId == updateCartID && c.Product.ProductID == updateProductID select c).FirstOrDefault(); if (myItem != null) { myItem.Quantity = quantity; await _db.SaveChangesAsync(); } } catch (Exception exp) { throw new Exception("ERROR: Unable to Update Cart Item - " + exp.Message.ToString(), exp); } } public async Task EmptyCart() { //ShoppingCartId = GetCartId(); var cartItems = _db.ShoppingCartItems.Where( c => c.CartId == ShoppingCartId); foreach (var cartItem in cartItems) { _db.ShoppingCartItems.Remove(cartItem); } // Save changes. await _db.SaveChangesAsync(); } public int GetCount() { //ShoppingCartId = GetCartId(); // Get the count of each item in the cart and sum them up var count = (from cartItems in _db.ShoppingCartItems where cartItems.CartId == ShoppingCartId select (int?)cartItems.Quantity).Sum(); // Return 0 if all entries are null return count ?? 0; } public struct ShoppingCartUpdates { public int ProductId; public int PurchaseQuantity; public bool RemoveItem; } } }
35.644444
162
0.488778
[ "MIT" ]
rfcm83/Modern-Cloud-Apps
Hands-on lab/Solution/Contoso Sports League/Contoso.Apps.SportsLeague.Data/Logic/ShoppingCartActions.cs
6,418
C#
/* * Copyright 2018 faddenSoft * * 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.Collections.ObjectModel; using System.Linq; namespace CommonUtil { public class Container { /// <summary> /// Compares two lists of strings to see if their contents are equal. The lists /// must contain the same strings, in the same order. /// </summary> /// <param name="l1">List #1.</param> /// <param name="l2">List #2.</param> /// <param name="comparer">String comparer (e.g. StringComparer.InvariantCulture). If /// null, the default string comparer is used.</param> /// <returns>True if the lists are equal.</returns> public static bool StringListEquals(IList<string> l1, IList<string>l2, StringComparer comparer) { // Quick check for reference equality. if (l1 == l2) { return true; } return Enumerable.SequenceEqual<string>(l1, l2, comparer); } /// <summary> /// Makes a deep copy of a string list. /// </summary> /// <param name="src">String list to copy.</param> /// <returns>New string list.</returns> public static List<string> CopyStringList(IList<string> src) { List<string> dst = new List<string>(src.Count); foreach (string str in src) { dst.Add(str); } return dst; } /// <summary> /// Compares two Dictionaries to see if their contents are equal. Key and value types /// must have correctly-implemented equality checks. (I contend this works incorrectly /// for float -- 5.0f is equal to the integer 5.) /// </summary> /// <remarks> /// https://stackoverflow.com/q/3804367/294248 /// /// TODO: make this work right for float/int comparisons /// </remarks> /// <typeparam name="TKey">Dictionary key type.</typeparam> /// <typeparam name="TValue">Dictionary value type.</typeparam> /// <param name="dict1">Dictionary #1.</param> /// <param name="dict2">Dictionary #2.</param> /// <returns>True if equal, false if not.</returns> public static bool CompareDicts<TKey, TValue>( Dictionary<TKey, TValue> dict1, Dictionary<TKey, TValue> dict2) { if (dict1 == dict2) { return true; } if (dict1 == null || dict2 == null) { return false; } if (dict1.Count != dict2.Count) { return false; } #if false var valueComparer = EqualityComparer<TValue>.Default; foreach (var kvp in dict1) { TValue value2; if (!dict2.TryGetValue(kvp.Key, out value2)) return false; if (!valueComparer.Equals(kvp.Value, value2)) return false; } return true; #else // Check to see if there are any elements in the first that are not in the second. return !dict1.Except(dict2).Any(); #endif } public static bool CompareDicts<TKey, TValue>( ReadOnlyDictionary<TKey, TValue> dict1, ReadOnlyDictionary<TKey, TValue> dict2) { if (dict1 == dict2) { return true; } if (dict1 == null || dict2 == null) { return false; } if (dict1.Count != dict2.Count) { return false; } // Check to see if there are any elements in the first that are not in the second. return !dict1.Except(dict2).Any(); } } }
38.044248
97
0.569667
[ "Apache-2.0" ]
absindx/6502bench
CommonUtil/Container.cs
4,301
C#
using System; namespace HotBrokerBus.Abstractions.Middleware { public class BusMiddlewareComponent : IBusMiddlewareComponent { public BusMiddlewareComponent(string name, BusMiddlewarePriority priority, Type component) { Name = name; Priority = priority; Component = component; } public string Name { get; } public BusMiddlewarePriority Priority { get; } public Type Component { get; } public BusMiddlewareExecutionDelegate Next { get; set; } public BusMiddlewareExecutionDelegate Process { get; set; } } }
23.642857
67
0.613293
[ "MIT" ]
Kakktuss/HotBrokerBus
src/HotBrokerBus.Core/Middleware/BusMiddlewareComponent.cs
664
C#
using System; using System.Net.Sockets; using NUnit.Framework; using StatsdClient; namespace Tests { [TestFixture] public class UDPSmokeTests { [Test] public void Sends_a_counter() { try { var client = new StatsdUDP(name: "127.0.0.1", port: 8126); client.Send("socket2:1|c"); } catch(SocketException ex) { Assert.Fail("Socket Exception, have you set up your Statsd name and port? Error: {0}", ex.Message); } } } }
23.423077
116
0.495895
[ "MIT" ]
Nasdaq/dogstatsd-csharp-client
tests/StatsdClient.Tests/UDPSmokeTests.cs
611
C#
namespace _12.Google { public class Company { private string name; private decimal salary; private string department; public Company(string name, string department, decimal salary) { this.Name = name; this.Department = department; this.Salary = salary; } public string Name { get; set; } public string Department { get; set; } public decimal Salary { get; set; } public override string ToString() => $"{this.Name} {this.Department} {this.Salary:F2}"; } }
25.458333
96
0.551555
[ "MIT" ]
stoyanov7/SoftwareUniversity
C#Development/C#OOPBasics/ DefiningClasses-Exercise/12.Google/12.Google/Company.cs
613
C#
using System.Web; using System.Web.Mvc; namespace PasswordValidator.Demo.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
19.538462
76
0.732283
[ "Unlicense" ]
colinangusmackay/Xander.PasswordValidator
src/Demo/Xander.PasswordValidator/PasswordValidator.Demo.Web/App_Start/FilterConfig.cs
256
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/mmdeviceapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public enum EDataFlow { eRender = 0, eCapture = (eRender + 1), eAll = (eCapture + 1), EDataFlow_enum_count = (eAll + 1), } }
30.4375
145
0.673511
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/mmdeviceapi/EDataFlow.cs
489
C#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using ImageMagick; using Xunit; #if Q8 using QuantumType = System.Byte; #elif Q16 using QuantumType = System.UInt16; #elif Q16HDRI using QuantumType = System.Single; #else #error Not implemented! #endif namespace Magick.NET.Tests { public partial class ColorHSLTests : ColorBaseTests<ColorHSL> { public class TheFromMagickColorMethod { [Fact] public void ShouldInitializeTheProperties() { var color = new MagickColor(Quantum.Max, Quantum.Max, (QuantumType)(Quantum.Max * 0.02)); var hslColor = ColorHSL.FromMagickColor(color); Assert.InRange(hslColor.Hue, 0.16, 0.17); Assert.InRange(hslColor.Lightness, 0.5, 0.6); Assert.InRange(hslColor.Saturation, 0.10, 1.1); } } } }
26.583333
105
0.633229
[ "Apache-2.0" ]
AFWberlin/Magick.NET
tests/Magick.NET.Tests/Colors/ColorHSLTests/TheFromMagickColorMethod.cs
959
C#
using Expressive.Expressions; using Expressive.Operators; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Linq; namespace Expressive.Tests.Operators { [TestClass] public abstract class OperatorBaseTests { internal abstract IOperator Operator { get; } protected abstract Type ExpectedExpressionType { get; } internal abstract OperatorPrecedence ExpectedOperatorPrecedence { get; } #pragma warning disable CA1819 // Properties should not return arrays protected abstract string[] ExpectedTags { get; } #pragma warning restore CA1819 // Properties should not return arrays [TestMethod] public void TestTags() { var operatorTags = this.Operator.Tags.ToArray(); Assert.AreEqual(this.ExpectedTags.Length, operatorTags.Length); for (var i = 0; i < this.ExpectedTags.Length; i++) { Assert.AreEqual(this.ExpectedTags[i], operatorTags[i]); } } [TestMethod] public void TestBuildExpression() { var op = this.Operator; var expression = op.BuildExpression( new Token("1", 1), new[] { Mock.Of<IExpression>(e => e.Evaluate(It.IsAny<IDictionary<string, object>>()) == (object) null), Mock.Of<IExpression>(e => e.Evaluate(It.IsAny<IDictionary<string, object>>()) == (object) null) }, new Context(ExpressiveOptions.None)); Assert.IsInstanceOfType(expression, this.ExpectedExpressionType); } [TestMethod] public void TestCanGetCaptiveTokens() { var op = this.Operator; Assert.IsTrue(op.CanGetCaptiveTokens(new Token("1", 0), new Token("+", 1), new Queue<Token>())); } [TestMethod] public virtual void TestGetCaptiveTokens() { var op = this.Operator; var token = new Token("+", 1); Assert.AreEqual(token, op.GetCaptiveTokens(new Token("1", 0), token, new Queue<Token>()).Single()); } [TestMethod] public virtual void TestGetInnerCaptiveTokens() { var op = this.Operator; var tokens = new[] { new Token("+", 1), new Token("(", 2), new Token("1", 3), new Token("-", 4), new Token("4", 5), new Token(")", 6), }; Assert.AreEqual(0, op.GetInnerCaptiveTokens(tokens).Length); } [TestMethod] public void TestGetPrecedence() { var op = this.Operator; Assert.AreEqual(this.ExpectedOperatorPrecedence, op.GetPrecedence(null)); } } }
29.414141
116
0.560783
[ "MIT" ]
antoniaelek/expressive
Source/Expressive.Tests/Operators/OperatorBaseTests.cs
2,914
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.Health.Fhir.SqlServer.Features.ChangeFeed; using Microsoft.Health.SqlServer; using Microsoft.Health.SqlServer.Configs; using Xunit; namespace Microsoft.Health.Fhir.SqlServer.UnitTests.Features.ChangeFeed { /// <summary> /// Unit tests to validates input parameters of a GetRecordsAsync function. /// </summary> public class SqlServerFhirResourceChangeDataStoreTests { private readonly SqlServerFhirResourceChangeDataStore resourceChangeDataStore; public SqlServerFhirResourceChangeDataStoreTests() { var config = Options.Create(new SqlServerDataStoreConfiguration { ConnectionString = string.Empty }); var connectionStringProvider = new DefaultSqlConnectionStringProvider(config); var connectionFactory = new DefaultSqlConnectionFactory(connectionStringProvider); resourceChangeDataStore = new SqlServerFhirResourceChangeDataStore(connectionFactory, NullLogger<SqlServerFhirResourceChangeDataStore>.Instance); } [Fact] public async Task GivenTheStartIdLessThanOne_WhenGetResourceChanges_ThenExceptionShouldBeThrown() { var expectedStartString = "Value '-1' is not greater than or equal to limit '1'. (Parameter 'startId')"; var exception = await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () => await resourceChangeDataStore.GetRecordsAsync(-1, 200, CancellationToken.None)); Assert.StartsWith(expectedStartString, exception.Message); } [Fact] public async Task GivenThePageSizeLessThanOne_WhenGetResourceChanges_ThenExceptionShouldBeThrown() { var expectedStartString = "Value '-1' is not greater than or equal to limit '1'. (Parameter 'pageSize')"; var exception = await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () => await resourceChangeDataStore.GetRecordsAsync(1, -1, CancellationToken.None)); Assert.StartsWith(expectedStartString, exception.Message); } [Fact] public async Task GivenThePageSizeLessThanOne_WhenGetResourceChanges_ThenArgumentOutOfRangeExceptionShouldBeThrown() { try { await resourceChangeDataStore.GetRecordsAsync(1, -1, CancellationToken.None); } catch (Exception ex) { Assert.Equal(nameof(ArgumentOutOfRangeException), ex.GetType().Name); } } [Fact] public async Task GivenEmptyConnectionString_WhenGetResourceChanges_ThenInvalidOperationExceptionShouldBeThrown() { try { await resourceChangeDataStore.GetRecordsAsync(1, 200, CancellationToken.None); } catch (Exception ex) { Assert.Equal(nameof(InvalidOperationException), ex.GetType().Name); } } } }
45.381579
174
0.658452
[ "MIT" ]
Lukas1v/fhir-server
src/Microsoft.Health.Fhir.SqlServer.UnitTests/Features/ChangeFeed/SqlServerFhirResourceChangeDataStoreTests.cs
3,451
C#