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 |
|---|---|---|---|---|---|---|---|---|
// **********************************************************************************
// Copyright (c) 2015-2021, Dmitry Merzlyakov. All rights reserved.
// Licensed under the FreeBSD Public License. See LICENSE file included with the distribution for details and disclaimer.
//
// This file is part of NLedger that is a .Net port of C++ Ledger tool (ledger-cli.org). Original code is licensed under:
// Copyright (c) 2003-2021, John Wiegley. All rights reserved.
// See LICENSE.LEDGER file included with the distribution for details and disclaimer.
// **********************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NLedger.Utility.Rnd
{
public class BoolGenerator : IntegerGenerator
{
public BoolGenerator()
: this(null)
{ }
public BoolGenerator(Random random)
: base(random, 0, 1)
{ }
public new bool Value()
{
return base.Value() == 1;
}
}
}
| 34.363636 | 122 | 0.547619 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | VagyokC4/nledger | Source/NLedger/Utility/Rnd/BoolGenerator.cs | 1,136 | C# |
namespace ClassLib007
{
public class Class042
{
public static string Property => "ClassLib007";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib007/Class042.cs | 120 | C# |
using EPAS.DataEntity.Entity.Common;
using System.ComponentModel;
namespace EPAS.DataEntity.Enum
{
//出入库策略
public enum IOStrategy
{
[DescriptionAttribute("zh-CN,无策略;en-US,NoStrategy;")]
NoStrategy = 0,
[DescriptionAttribute("zh-CN,先进先出;en-US,FIFO;")]
FIFO = 1
}
}
| 14.347826 | 61 | 0.609091 | [
"MPL-2.0"
] | whw0828/EPASServer | EPASFramework/EPAS.DataEntity/Enum/IOStrategy.cs | 356 | C# |
using System;
namespace JSONAPI.Tests.Models
{
enum SampleEnum
{
Value1 = 1,
Value2 = 2
}
class Sample
{
public string Id { get; set; }
public Boolean BooleanField { get; set; }
public Boolean? NullableBooleanField { get; set; }
public SByte SByteField { get; set; }
public SByte? NullableSByteField { get; set; }
public Byte ByteField { get; set; }
public Byte? NullableByteField { get; set; }
public Int16 Int16Field { get; set; }
public Int16? NullableInt16Field { get; set; }
public UInt16 UInt16Field { get; set; }
public UInt16? NullableUInt16Field { get; set; }
public Int32 Int32Field { get; set; }
public Int32? NullableInt32Field { get; set; }
public UInt32 UInt32Field { get; set; }
public UInt32? NullableUInt32Field { get; set; }
public Int64 Int64Field { get; set; }
public Int64? NullableInt64Field { get; set; }
public UInt64 UInt64Field { get; set; }
public UInt64? NullableUInt64Field { get; set; }
public Double DoubleField { get; set; }
public Double? NullableDoubleField { get; set; }
public Single SingleField { get; set; }
public Single? NullableSingleField { get; set; }
public Decimal DecimalField { get; set; }
public Decimal? NullableDecimalField { get; set; }
public DateTime DateTimeField { get; set; }
public DateTime? NullableDateTimeField { get; set; }
public DateTimeOffset DateTimeOffsetField { get; set; }
public DateTimeOffset? NullableDateTimeOffsetField { get; set; }
public Guid GuidField { get; set; }
public Guid? NullableGuidField { get; set; }
public string StringField { get; set; }
public SampleEnum EnumField { get; set; }
public SampleEnum? NullableEnumField { get; set; }
}
}
| 39.571429 | 72 | 0.619907 | [
"MIT"
] | csantero/JSONAPI.NET | JSONAPI.Tests/Models/Sample.cs | 1,941 | C# |
namespace PT_Camping.Views.UserControls
{
partial class EmployeesUserControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.employeesListView = new System.Windows.Forms.ListView();
this.addEmployeeButton = new System.Windows.Forms.Button();
this.detailsPanel = new System.Windows.Forms.Panel();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.addEmployeePhotoPictureBox = new System.Windows.Forms.PictureBox();
this.dismissButton = new System.Windows.Forms.Button();
this.nameTextBox = new System.Windows.Forms.TextBox();
this.nameLabel = new System.Windows.Forms.Label();
this.loginTextBox = new System.Windows.Forms.TextBox();
this.emailTextBox = new System.Windows.Forms.TextBox();
this.phoneTextBox = new System.Windows.Forms.TextBox();
this.addressTextBox = new System.Windows.Forms.TextBox();
this.birthDateTextBox = new System.Windows.Forms.TextBox();
this.surnameTextBox = new System.Windows.Forms.TextBox();
this.editButton = new System.Windows.Forms.Button();
this.detailsTitleBarPanel = new System.Windows.Forms.Panel();
this.detailsTitle = new System.Windows.Forms.Label();
this.permissionButton = new System.Windows.Forms.Button();
this.loginLabel = new System.Windows.Forms.Label();
this.emailLabel = new System.Windows.Forms.Label();
this.phoneLabel = new System.Windows.Forms.Label();
this.addressLabel = new System.Windows.Forms.Label();
this.birthDateLabel = new System.Windows.Forms.Label();
this.resetButton = new System.Windows.Forms.Button();
this.surnameLabel = new System.Windows.Forms.Label();
this.passButton = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
this.detailsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.pictureBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.addEmployeePhotoPictureBox)).BeginInit();
this.detailsTitleBarPanel.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel
//
this.tableLayoutPanel.ColumnCount = 5;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 5F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 5F));
this.tableLayoutPanel.Controls.Add(this.employeesListView, 1, 1);
this.tableLayoutPanel.Controls.Add(this.addEmployeeButton, 1, 2);
this.tableLayoutPanel.Controls.Add(this.detailsPanel, 3, 1);
this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel.Location = new System.Drawing.Point(0, 50);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowCount = 4;
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 8F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 72F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 15F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 5F));
this.tableLayoutPanel.Size = new System.Drawing.Size(900, 550);
this.tableLayoutPanel.TabIndex = 11;
//
// employeesListView
//
this.employeesListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.employeesListView.FullRowSelect = true;
this.employeesListView.GridLines = true;
this.employeesListView.HideSelection = false;
this.employeesListView.Location = new System.Drawing.Point(48, 47);
this.employeesListView.MultiSelect = false;
this.employeesListView.Name = "employeesListView";
this.employeesListView.Scrollable = false;
this.employeesListView.Size = new System.Drawing.Size(354, 390);
this.employeesListView.TabIndex = 14;
this.employeesListView.UseCompatibleStateImageBehavior = false;
this.employeesListView.View = System.Windows.Forms.View.List;
this.employeesListView.SelectedIndexChanged += new System.EventHandler(this.EmployeeListView_SelectedIndexChanged);
this.employeesListView.Resize += new System.EventHandler(this.EmployeeListView_Resize);
//
// addEmployeeButton
//
this.addEmployeeButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.addEmployeeButton.AutoSize = true;
this.addEmployeeButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.addEmployeeButton.Location = new System.Drawing.Point(165, 463);
this.addEmployeeButton.Name = "addEmployeeButton";
this.addEmployeeButton.Size = new System.Drawing.Size(120, 35);
this.addEmployeeButton.TabIndex = 15;
this.addEmployeeButton.Text = "Nouvel employé";
this.addEmployeeButton.UseVisualStyleBackColor = true;
this.addEmployeeButton.Click += new System.EventHandler(this.AddEmployeeButton_Click);
//
// detailsPanel
//
this.detailsPanel.AutoSize = true;
this.detailsPanel.BackColor = System.Drawing.Color.White;
this.detailsPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.detailsPanel.Controls.Add(this.passButton);
this.detailsPanel.Controls.Add(this.pictureBox);
this.detailsPanel.Controls.Add(this.dismissButton);
this.detailsPanel.Controls.Add(this.nameTextBox);
this.detailsPanel.Controls.Add(this.nameLabel);
this.detailsPanel.Controls.Add(this.loginTextBox);
this.detailsPanel.Controls.Add(this.emailTextBox);
this.detailsPanel.Controls.Add(this.phoneTextBox);
this.detailsPanel.Controls.Add(this.addressTextBox);
this.detailsPanel.Controls.Add(this.birthDateTextBox);
this.detailsPanel.Controls.Add(this.surnameTextBox);
this.detailsPanel.Controls.Add(this.editButton);
this.detailsPanel.Controls.Add(this.detailsTitleBarPanel);
this.detailsPanel.Controls.Add(this.permissionButton);
this.detailsPanel.Controls.Add(this.loginLabel);
this.detailsPanel.Controls.Add(this.emailLabel);
this.detailsPanel.Controls.Add(this.phoneLabel);
this.detailsPanel.Controls.Add(this.addressLabel);
this.detailsPanel.Controls.Add(this.birthDateLabel);
this.detailsPanel.Controls.Add(this.resetButton);
this.detailsPanel.Controls.Add(this.surnameLabel);
this.detailsPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.detailsPanel.Location = new System.Drawing.Point(498, 47);
this.detailsPanel.Name = "detailsPanel";
this.detailsPanel.Size = new System.Drawing.Size(354, 390);
this.detailsPanel.TabIndex = 16;
//
// pictureBox
//
this.pictureBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.pictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBox.Controls.Add(this.addEmployeePhotoPictureBox);
this.pictureBox.ErrorImage = global::PT_Camping.Properties.Resources.ic_contact_default;
this.pictureBox.Image = global::PT_Camping.Properties.Resources.ic_contact_default;
this.pictureBox.Location = new System.Drawing.Point(144, 30);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(70, 80);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox.TabIndex = 22;
this.pictureBox.TabStop = false;
//
// addEmployeePhotoPictureBox
//
this.addEmployeePhotoPictureBox.BackColor = System.Drawing.Color.Transparent;
this.addEmployeePhotoPictureBox.Cursor = System.Windows.Forms.Cursors.Hand;
this.addEmployeePhotoPictureBox.ErrorImage = global::PT_Camping.Properties.Resources.ic_contact_default;
this.addEmployeePhotoPictureBox.Image = global::PT_Camping.Properties.Resources.ic_add_a_photo;
this.addEmployeePhotoPictureBox.Location = new System.Drawing.Point(2, 58);
this.addEmployeePhotoPictureBox.Name = "addEmployeePhotoPictureBox";
this.addEmployeePhotoPictureBox.Size = new System.Drawing.Size(20, 20);
this.addEmployeePhotoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.addEmployeePhotoPictureBox.TabIndex = 27;
this.addEmployeePhotoPictureBox.TabStop = false;
this.addEmployeePhotoPictureBox.Click += new System.EventHandler(this.AddEmployeePhotoPictureBox_Click);
//
// dismissButton
//
this.dismissButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.dismissButton.AutoSize = true;
this.dismissButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.dismissButton.Location = new System.Drawing.Point(235, 350);
this.dismissButton.Name = "dismissButton";
this.dismissButton.Size = new System.Drawing.Size(90, 30);
this.dismissButton.TabIndex = 23;
this.dismissButton.Text = "Licencier";
this.dismissButton.UseVisualStyleBackColor = true;
this.dismissButton.Click += new System.EventHandler(this.DismissEmployeeButton_Click);
//
// nameTextBox
//
this.nameTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.nameTextBox.Location = new System.Drawing.Point(179, 154);
this.nameTextBox.MaxLength = 25;
this.nameTextBox.Name = "nameTextBox";
this.nameTextBox.ReadOnly = true;
this.nameTextBox.ShortcutsEnabled = false;
this.nameTextBox.Size = new System.Drawing.Size(120, 20);
this.nameTextBox.TabIndex = 16;
//
// nameLabel
//
this.nameLabel.Anchor = System.Windows.Forms.AnchorStyles.None;
this.nameLabel.AutoSize = true;
this.nameLabel.Location = new System.Drawing.Point(56, 157);
this.nameLabel.Name = "nameLabel";
this.nameLabel.Size = new System.Drawing.Size(43, 13);
this.nameLabel.TabIndex = 19;
this.nameLabel.Text = "Prénom";
//
// loginTextBox
//
this.loginTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.loginTextBox.Location = new System.Drawing.Point(179, 304);
this.loginTextBox.MaxLength = 40;
this.loginTextBox.Name = "loginTextBox";
this.loginTextBox.ReadOnly = true;
this.loginTextBox.ShortcutsEnabled = false;
this.loginTextBox.Size = new System.Drawing.Size(120, 20);
this.loginTextBox.TabIndex = 21;
//
// emailTextBox
//
this.emailTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.emailTextBox.Location = new System.Drawing.Point(179, 278);
this.emailTextBox.MaxLength = 50;
this.emailTextBox.Name = "emailTextBox";
this.emailTextBox.ReadOnly = true;
this.emailTextBox.ShortcutsEnabled = false;
this.emailTextBox.Size = new System.Drawing.Size(120, 20);
this.emailTextBox.TabIndex = 20;
//
// phoneTextBox
//
this.phoneTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.phoneTextBox.Location = new System.Drawing.Point(179, 252);
this.phoneTextBox.MaxLength = 10;
this.phoneTextBox.Name = "phoneTextBox";
this.phoneTextBox.ReadOnly = true;
this.phoneTextBox.ShortcutsEnabled = false;
this.phoneTextBox.Size = new System.Drawing.Size(120, 20);
this.phoneTextBox.TabIndex = 19;
this.phoneTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.PhoneTextBox_KeyPress);
//
// addressTextBox
//
this.addressTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.addressTextBox.Location = new System.Drawing.Point(179, 206);
this.addressTextBox.MaxLength = 250;
this.addressTextBox.Multiline = true;
this.addressTextBox.Name = "addressTextBox";
this.addressTextBox.ReadOnly = true;
this.addressTextBox.ShortcutsEnabled = false;
this.addressTextBox.Size = new System.Drawing.Size(120, 40);
this.addressTextBox.TabIndex = 18;
//
// birthDateTextBox
//
this.birthDateTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.birthDateTextBox.Location = new System.Drawing.Point(179, 180);
this.birthDateTextBox.Name = "birthDateTextBox";
this.birthDateTextBox.ReadOnly = true;
this.birthDateTextBox.ShortcutsEnabled = false;
this.birthDateTextBox.Size = new System.Drawing.Size(120, 20);
this.birthDateTextBox.TabIndex = 17;
//
// surnameTextBox
//
this.surnameTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.surnameTextBox.Location = new System.Drawing.Point(179, 128);
this.surnameTextBox.MaxLength = 25;
this.surnameTextBox.Name = "surnameTextBox";
this.surnameTextBox.ReadOnly = true;
this.surnameTextBox.ShortcutsEnabled = false;
this.surnameTextBox.Size = new System.Drawing.Size(120, 20);
this.surnameTextBox.TabIndex = 15;
//
// editButton
//
this.editButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.editButton.BackgroundImage = global::PT_Camping.Properties.Resources.ic_edit;
this.editButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.editButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.editButton.Location = new System.Drawing.Point(319, 46);
this.editButton.Name = "editButton";
this.editButton.Size = new System.Drawing.Size(30, 30);
this.editButton.TabIndex = 14;
this.editButton.UseVisualStyleBackColor = true;
this.editButton.Click += new System.EventHandler(this.EditButton_Click);
//
// detailsTitleBarPanel
//
this.detailsTitleBarPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(63)))), ((int)(((byte)(81)))), ((int)(((byte)(181)))));
this.detailsTitleBarPanel.Controls.Add(this.detailsTitle);
this.detailsTitleBarPanel.Dock = System.Windows.Forms.DockStyle.Top;
this.detailsTitleBarPanel.Location = new System.Drawing.Point(0, 0);
this.detailsTitleBarPanel.Name = "detailsTitleBarPanel";
this.detailsTitleBarPanel.Size = new System.Drawing.Size(352, 40);
this.detailsTitleBarPanel.TabIndex = 9;
//
// detailsTitle
//
this.detailsTitle.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.detailsTitle.AutoSize = true;
this.detailsTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.detailsTitle.ForeColor = System.Drawing.Color.White;
this.detailsTitle.Location = new System.Drawing.Point(124, 10);
this.detailsTitle.Name = "detailsTitle";
this.detailsTitle.Size = new System.Drawing.Size(113, 20);
this.detailsTitle.TabIndex = 0;
this.detailsTitle.Text = "Détail employé";
//
// permissionButton
//
this.permissionButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.permissionButton.AutoSize = true;
this.permissionButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.permissionButton.Location = new System.Drawing.Point(30, 350);
this.permissionButton.Name = "permissionButton";
this.permissionButton.Size = new System.Drawing.Size(90, 30);
this.permissionButton.TabIndex = 22;
this.permissionButton.Text = "Permissions";
this.permissionButton.UseVisualStyleBackColor = true;
this.permissionButton.Click += new System.EventHandler(this.PermissionButton_Click);
//
// loginLabel
//
this.loginLabel.Anchor = System.Windows.Forms.AnchorStyles.None;
this.loginLabel.AutoSize = true;
this.loginLabel.Location = new System.Drawing.Point(56, 307);
this.loginLabel.Name = "loginLabel";
this.loginLabel.Size = new System.Drawing.Size(33, 13);
this.loginLabel.TabIndex = 6;
this.loginLabel.Text = "Login";
//
// emailLabel
//
this.emailLabel.Anchor = System.Windows.Forms.AnchorStyles.None;
this.emailLabel.AutoSize = true;
this.emailLabel.Location = new System.Drawing.Point(56, 281);
this.emailLabel.Name = "emailLabel";
this.emailLabel.Size = new System.Drawing.Size(32, 13);
this.emailLabel.TabIndex = 5;
this.emailLabel.Text = "Email";
//
// phoneLabel
//
this.phoneLabel.Anchor = System.Windows.Forms.AnchorStyles.None;
this.phoneLabel.AutoSize = true;
this.phoneLabel.Location = new System.Drawing.Point(56, 255);
this.phoneLabel.Name = "phoneLabel";
this.phoneLabel.Size = new System.Drawing.Size(58, 13);
this.phoneLabel.TabIndex = 4;
this.phoneLabel.Text = "Téléphone";
//
// addressLabel
//
this.addressLabel.Anchor = System.Windows.Forms.AnchorStyles.None;
this.addressLabel.AutoSize = true;
this.addressLabel.Location = new System.Drawing.Point(56, 209);
this.addressLabel.Name = "addressLabel";
this.addressLabel.Size = new System.Drawing.Size(45, 13);
this.addressLabel.TabIndex = 3;
this.addressLabel.Text = "Adresse";
//
// birthDateLabel
//
this.birthDateLabel.Anchor = System.Windows.Forms.AnchorStyles.None;
this.birthDateLabel.AutoSize = true;
this.birthDateLabel.Location = new System.Drawing.Point(56, 183);
this.birthDateLabel.Name = "birthDateLabel";
this.birthDateLabel.Size = new System.Drawing.Size(98, 13);
this.birthDateLabel.TabIndex = 2;
this.birthDateLabel.Text = "Date de Naissance";
//
// resetButton
//
this.resetButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.resetButton.BackgroundImage = global::PT_Camping.Properties.Resources.ic_undo;
this.resetButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.resetButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.resetButton.Location = new System.Drawing.Point(283, 46);
this.resetButton.Name = "resetButton";
this.resetButton.Size = new System.Drawing.Size(30, 30);
this.resetButton.TabIndex = 26;
this.resetButton.UseVisualStyleBackColor = true;
this.resetButton.Visible = false;
this.resetButton.Click += new System.EventHandler(this.ResetButton_Click);
//
// surnameLabel
//
this.surnameLabel.Anchor = System.Windows.Forms.AnchorStyles.None;
this.surnameLabel.AutoSize = true;
this.surnameLabel.Location = new System.Drawing.Point(56, 131);
this.surnameLabel.Name = "surnameLabel";
this.surnameLabel.Size = new System.Drawing.Size(29, 13);
this.surnameLabel.TabIndex = 1;
this.surnameLabel.Text = "Nom";
//
// passButton
//
this.passButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.passButton.AutoSize = true;
this.passButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.passButton.Location = new System.Drawing.Point(133, 350);
this.passButton.Name = "passButton";
this.passButton.Size = new System.Drawing.Size(90, 30);
this.passButton.TabIndex = 27;
this.passButton.Text = "Mot de passe";
this.passButton.UseVisualStyleBackColor = true;
this.passButton.Click += new System.EventHandler(this.PassButton_Click);
//
// EmployeesUserControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel);
this.Name = "EmployeesUserControl";
this.Controls.SetChildIndex(this.tableLayoutPanel, 0);
this.Controls.SetChildIndex(this.appBarTitle, 0);
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
this.detailsPanel.ResumeLayout(false);
this.detailsPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.pictureBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.addEmployeePhotoPictureBox)).EndInit();
this.detailsTitleBarPanel.ResumeLayout(false);
this.detailsTitleBarPanel.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.ListView employeesListView;
private System.Windows.Forms.Panel detailsPanel;
private System.Windows.Forms.TextBox nameTextBox;
private System.Windows.Forms.Label nameLabel;
private System.Windows.Forms.TextBox loginTextBox;
private System.Windows.Forms.TextBox emailTextBox;
private System.Windows.Forms.TextBox phoneTextBox;
private System.Windows.Forms.TextBox addressTextBox;
private System.Windows.Forms.TextBox birthDateTextBox;
private System.Windows.Forms.TextBox surnameTextBox;
private System.Windows.Forms.Button resetButton;
private System.Windows.Forms.Button editButton;
private System.Windows.Forms.Panel detailsTitleBarPanel;
private System.Windows.Forms.Label detailsTitle;
private System.Windows.Forms.Button permissionButton;
private System.Windows.Forms.Label loginLabel;
private System.Windows.Forms.Label emailLabel;
private System.Windows.Forms.Label phoneLabel;
private System.Windows.Forms.Label addressLabel;
private System.Windows.Forms.Label birthDateLabel;
private System.Windows.Forms.Label surnameLabel;
private System.Windows.Forms.Button dismissButton;
private System.Windows.Forms.Button addEmployeeButton;
private System.Windows.Forms.PictureBox pictureBox;
private System.Windows.Forms.PictureBox addEmployeePhotoPictureBox;
private System.Windows.Forms.Button passButton;
}
}
| 55.910064 | 172 | 0.64098 | [
"Apache-2.0"
] | Minestro/DUTS4-PT-Camping | PT_Camping/Views/UserControls/EmployeesUserControl.Designer.cs | 26,118 | C# |
namespace Library_MS
{
partial class return_books
{
/// <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()
{
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.textbox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.lbl_booksName = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.lbl_issueDate = new System.Windows.Forms.Label();
this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
this.button2 = new System.Windows.Forms.Button();
this.panel3 = new System.Windows.Forms.Panel();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.button1);
this.panel1.Controls.Add(this.textbox1);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(47, 63);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(383, 255);
this.panel1.TabIndex = 0;
//
// panel2
//
this.panel2.Controls.Add(this.button2);
this.panel2.Controls.Add(this.dateTimePicker1);
this.panel2.Controls.Add(this.lbl_issueDate);
this.panel2.Controls.Add(this.lbl_booksName);
this.panel2.Controls.Add(this.label4);
this.panel2.Controls.Add(this.label5);
this.panel2.Controls.Add(this.label3);
this.panel2.Location = new System.Drawing.Point(517, 426);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(932, 175);
this.panel2.TabIndex = 0;
this.panel2.Visible = false;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.MenuHighlight;
this.label1.Location = new System.Drawing.Point(29, 40);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(333, 31);
this.label1.TabIndex = 0;
this.label1.Text = "Enter Enrollment Number :";
//
// textbox1
//
this.textbox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textbox1.Location = new System.Drawing.Point(49, 99);
this.textbox1.Multiline = true;
this.textbox1.Name = "textbox1";
this.textbox1.Size = new System.Drawing.Size(269, 54);
this.textbox1.TabIndex = 1;
//
// button1
//
this.button1.BackColor = System.Drawing.Color.White;
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.ForeColor = System.Drawing.Color.DodgerBlue;
this.button1.Location = new System.Drawing.Point(117, 187);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(108, 44);
this.button1.TabIndex = 2;
this.button1.Text = "Search";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(28, 21);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(135, 25);
this.label3.TabIndex = 0;
this.label3.Text = "Books Name :";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(28, 108);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(186, 25);
this.label4.TabIndex = 1;
this.label4.Text = "Select Return Date :";
//
// lbl_booksName
//
this.lbl_booksName.AutoSize = true;
this.lbl_booksName.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl_booksName.Location = new System.Drawing.Point(185, 21);
this.lbl_booksName.Name = "lbl_booksName";
this.lbl_booksName.Size = new System.Drawing.Size(0, 25);
this.lbl_booksName.TabIndex = 2;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(371, 21);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(116, 25);
this.label5.TabIndex = 0;
this.label5.Text = "Issue Date :";
//
// lbl_issueDate
//
this.lbl_issueDate.AutoSize = true;
this.lbl_issueDate.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbl_issueDate.Location = new System.Drawing.Point(525, 21);
this.lbl_issueDate.Name = "lbl_issueDate";
this.lbl_issueDate.Size = new System.Drawing.Size(0, 25);
this.lbl_issueDate.TabIndex = 4;
//
// dateTimePicker1
//
this.dateTimePicker1.Location = new System.Drawing.Point(262, 108);
this.dateTimePicker1.Name = "dateTimePicker1";
this.dateTimePicker1.Size = new System.Drawing.Size(200, 22);
this.dateTimePicker1.TabIndex = 5;
//
// button2
//
this.button2.BackColor = System.Drawing.Color.White;
this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.ForeColor = System.Drawing.SystemColors.MenuHighlight;
this.button2.Location = new System.Drawing.Point(583, 92);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(107, 43);
this.button2.TabIndex = 6;
this.button2.Text = "Return";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// panel3
//
this.panel3.Controls.Add(this.dataGridView1);
this.panel3.Location = new System.Drawing.Point(517, 44);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(932, 329);
this.panel3.TabIndex = 2;
this.panel3.Visible = false;
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(33, 19);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersWidth = 51;
this.dataGridView1.RowTemplate.Height = 24;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(866, 267);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
//
// return_books
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1514, 635);
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "return_books";
this.Text = "return_books";
this.Load += new System.EventHandler(this.return_books_Load);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textbox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.DateTimePicker dateTimePicker1;
private System.Windows.Forms.Label lbl_issueDate;
private System.Windows.Forms.Label lbl_booksName;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.DataGridView dataGridView1;
}
} | 49.309322 | 173 | 0.597147 | [
"Apache-2.0"
] | SanjulaD/Library-Management-System | return_books.Designer.cs | 11,639 | C# |
using System.Collections.Generic;
namespace HCEngine.DefaultImplementations
{
/// <summary>
/// Source reader which buffers the result of another source reader when needed and can loop over the buffer.
/// </summary>
public class LoopedSourceReader : ISourceReader
{
private int m_Current;
private readonly ISourceReader m_Parent;
private List<Snapshot> m_Read;
/// <summary>
/// Constructor
/// </summary>
/// <param name="parent">The source reader to buffer. The current keyword will be the first of the loop.</param>
public LoopedSourceReader(ISourceReader parent)
{
m_Parent = parent;
m_Read = new List<Snapshot>();
m_Current = 0;
AddSnapshot();
}
/// <summary>
/// <see cref="ISourceReader.Column" />
/// </summary>
public int Column => m_Read[m_Current].Column;
/// <summary>
/// <see cref="ISourceReader.LastKeyword" />
/// </summary>
public string LastKeyword => m_Read[m_Current].LastKeyword;
/// <summary>
/// <see cref="ISourceReader.Line" />
/// </summary>
public int Line => m_Read[m_Current].Line;
/// <summary>
/// <see cref="ISourceReader.LineOfCode" />
/// </summary>
public string LineOfCode => m_Read[m_Current].LineOfCode;
/// <summary>
/// <see cref="ISourceReader.ReadingComplete" />
/// </summary>
public bool ReadingComplete => m_Read[m_Current].ReadingComplete;
/// <summary>
/// <see cref="ISourceReader.Initialize(string)" />
/// </summary>
public void Initialize(string source)
{
m_Parent.Initialize(source);
m_Read = new List<Snapshot>();
AddSnapshot();
}
/// <summary>
/// <see cref="ISourceReader.ReadNext" />
/// </summary>
public void ReadNext()
{
++m_Current;
if (m_Current >= m_Read.Count)
{
m_Parent.ReadNext();
AddSnapshot();
}
}
/// <summary>
/// Resets the reader to its position when instantiated.
/// </summary>
public void Reset()
{
m_Current = 0;
}
/// <summary>
/// Removes the first snapshot (useful to prepare a looped reader before the reader is at the correct position)
/// </summary>
public void ForgetFirst()
{
m_Read.RemoveAt(0);
}
/// <summary>
/// Adds a snapshot without moving the current index. Useful when the looped reader was prepared before the reader was
/// at the correct position.
/// </summary>
public void AddSnapshot()
{
m_Read.Add(new Snapshot(m_Parent));
}
private class Snapshot
{
public Snapshot(ISourceReader toSnap)
{
LastKeyword = toSnap.LastKeyword;
Column = toSnap.Column;
Line = toSnap.Line;
LineOfCode = toSnap.LineOfCode;
ReadingComplete = toSnap.ReadingComplete;
}
public string LastKeyword { get; }
public int Column { get; }
public int Line { get; }
public string LineOfCode { get; }
public bool ReadingComplete { get; }
}
}
} | 29.442623 | 130 | 0.522272 | [
"MIT"
] | IfElseSwitch/hc-engine | HCEngine/HCEngine/DefaultImplementations/LoopedSourceReader.cs | 3,594 | C# |
namespace Incoding.CQRS
{
#region << Using >>
using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Incoding.Block.IoC;
using Incoding.Data;
using Incoding.Maybe;
using Incoding.Quality;
using Newtonsoft.Json;
#endregion
public abstract class MessageBase : IMessage
{
#region Fields
Lazy<IRepository> lazyRepository;
Lazy<MessageDispatcher> messageDispatcher;
#endregion
#region Properties
[IgnoreCompare("System"), JsonIgnore, IgnoreDataMember]
protected IRepository Repository { get { return lazyRepository.Value; } }
[IgnoreCompare("System"), JsonIgnore, IgnoreDataMember]
protected MessageDispatcher Dispatcher { get { return messageDispatcher.Value; } }
#endregion
#region IMessage<TResult> Members
[IgnoreCompare("Design fixed"), JsonIgnore, IgnoreDataMember]
public virtual object Result { get; protected set; }
[IgnoreCompare("Design fixed"), IgnoreDataMember]
public virtual MessageExecuteSetting Setting { get; set; }
public virtual void OnExecute(IDispatcher current, Lazy<IUnitOfWork> unitOfWork)
{
Result = null;
lazyRepository = new Lazy<IRepository>(() => unitOfWork.Value.GetRepository());
messageDispatcher = new Lazy<MessageDispatcher>(() => new MessageDispatcher(current, Setting));
Execute();
}
#endregion
#region Api Methods
protected abstract void Execute();
#endregion
#region Nested classes
protected class AsyncMessageDispatcher
{
#region Fields
readonly MessageDispatcher dispatcher;
#endregion
#region Constructors
public AsyncMessageDispatcher(MessageDispatcher dispatcher)
{
this.dispatcher = dispatcher;
}
#endregion
#region Api Methods
public Task<TQueryResult> Query<TQueryResult>(QueryBase<TQueryResult> query, Action<MessageExecuteSetting> configuration = null) where TQueryResult : class
{
return Task<TQueryResult>.Factory.StartNew(() => dispatcher.Query(query, configuration));
}
public Task<object> Push(CommandBase command, Action<MessageExecuteSetting> configuration = null)
{
return Task.Factory.StartNew(() =>
{
dispatcher.Push(command, configuration);
return command.Result;
});
}
#endregion
}
protected class MessageDispatcher
{
#region Fields
readonly IDispatcher dispatcher;
readonly MessageExecuteSetting outerSetting;
#endregion
#region Constructors
public MessageDispatcher(IDispatcher dispatcher, MessageExecuteSetting setting)
{
Guard.NotNull("dispatcher", dispatcher, errorMessage: "External dispatcher should not be null on internal dispatcher creation");
this.dispatcher = dispatcher;
outerSetting = setting;
}
#endregion
#region Api Methods
public AsyncMessageDispatcher Async()
{
return new AsyncMessageDispatcher(this);
}
public IDispatcher New()
{
return IoCFactory.Instance.TryResolve<IDispatcher>();
}
public TQueryResult Query<TQueryResult>(QueryBase<TQueryResult> query, Action<MessageExecuteSetting> configuration = null)
{
configuration.Do(action => action(outerSetting));
return dispatcher.Query(query, outerSetting);
}
public void Push(CommandBase command, Action<MessageExecuteSetting> configuration = null)
{
configuration.Do(action => action(outerSetting));
dispatcher.Push(command, outerSetting);
}
public TResult Push<TResult>(CommandBase command, Action<MessageExecuteSetting> configuration = null)
{
configuration.Do(action => action(outerSetting));
dispatcher.Push(command, outerSetting);
return (TResult)command.Result;
}
#endregion
}
#endregion
}
} | 29.898734 | 167 | 0.573666 | [
"Apache-2.0"
] | Incoding-Software/Incoding-Framework | src/Incoding/CQRS/Core/MessageBase.cs | 4,726 | 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("Serilog.Sinks.RollingFileV2.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Serilog.Sinks.RollingFileV2.Tests")]
[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("aefe89c6-7775-4c5b-9094-aa798019dfa7")]
// 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.891892 | 84 | 0.748436 | [
"Apache-2.0"
] | dazinator/sinks-rollingfile | test/Serilog.Sinks.RollingFileAlternate.Tests/Properties/AssemblyInfo.cs | 1,442 | C# |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Definitions.Dutch;
namespace Microsoft.Recognizers.Text.Number.Dutch
{
public class IntegerExtractor : BaseNumberExtractor
{
internal sealed override ImmutableDictionary<Regex, TypeTag> Regexes { get; }
protected sealed override string ExtractType { get; } = Constants.SYS_NUM_INTEGER; // "Integer";
private static readonly ConcurrentDictionary<string, IntegerExtractor> Instances = new ConcurrentDictionary<string, IntegerExtractor>();
public static IntegerExtractor GetInstance(string placeholder = NumbersDefinitions.PlaceHolderDefault) {
if (!Instances.ContainsKey(placeholder)) {
var instance = new IntegerExtractor(placeholder);
Instances.TryAdd(placeholder, instance);
}
return Instances[placeholder];
}
private IntegerExtractor(string placeholder = NumbersDefinitions.PlaceHolderDefault)
{
var regexes = new Dictionary<Regex, TypeTag> {
{
new Regex(NumbersDefinitions.NumbersWithPlaceHolder(placeholder),
RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}, {
new Regex(NumbersDefinitions.NumbersWithSuffix, RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}, {
new Regex(NumbersDefinitions.RoundNumberIntegerRegexWithLocks,
RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}, {
new Regex(NumbersDefinitions.NumbersWithDozenSuffix,
RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}, {
new Regex(NumbersDefinitions.AllIntRegexWithLocks,
RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.DUTCH)
}, {
new Regex(NumbersDefinitions.AllIntRegexWithDozenSuffixLocks,
RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.DUTCH)
}, {
GenerateLongFormatNumberRegexes(LongFormatType.IntegerNumComma, placeholder), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}, {
GenerateLongFormatNumberRegexes(LongFormatType.IntegerNumBlank, placeholder), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}, {
GenerateLongFormatNumberRegexes(LongFormatType.IntegerNumNoBreakSpace, placeholder), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}, {
GenerateLongFormatNumberRegexes(LongFormatType.IntegerNumDot, placeholder), RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX)
}
};
Regexes = regexes.ToImmutableDictionary();
}
}
} | 58.451613 | 190 | 0.686534 | [
"MIT"
] | Josverl/Recognizers-Text | .NET/Microsoft.Recognizers.Text.Number/Dutch/Extractors/IntegerExtractor.cs | 3,626 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Touchdown.Core;
using Touchdown.SensorAbstraction;
using System.Threading.Tasks;
namespace Touchdown.Win.UI.UserControls.InitWizzard {
public partial class TouchAreaSelectionControl : Touchdown.Win.UI.UserControls.InitWizzard.InitKinectWizzardControl {
private Bitmap originalImage;
private Rectangle selection;
public TouchAreaSelectionControl(Button next) : base(next) {
InitializeComponent();
this.lblHeadline.Text = "Touch Area Selection";
this.lblDescription.Text = "Select the area that should be observed by the library";
numX.Enabled = false;
numY.Enabled = false;
numWidth.Enabled = false;
numHeight.Enabled = false;
numY.ValueChanged += AreaChanged;
numX.ValueChanged += AreaChanged;
numWidth.ValueChanged += AreaChanged;
numHeight.ValueChanged += AreaChanged;
}
public override void SetWizzardInfo(Dictionary<string, object> info) {
base.SetWizzardInfo(info);
var depthFrame = info[INFOKEY_BACKGROUND_MODEL] as DepthFrame;
var sensor = info[INFOKEY_SENSOR] as IKinectSensorProvider;
originalImage = depthFrame.CreateBitmap();
pbChooseArea.Image = originalImage;
selection = new Rectangle(0, 0, originalImage.Width, originalImage.Height);
SetSpinEditValues();
numX.Value = selection.X;
numY.Value = selection.Y;
numWidth.Value = selection.Width;
numHeight.Value = selection.Height;
}
public override void AddOrUpdateWizzardInfo(Dictionary<string, object> info) {
base.AddOrUpdateWizzardInfo(info);
var wholeFrame = info[INFOKEY_BACKGROUND_MODEL] as DepthFrame;
if (rbSpecificArea.Checked) {
info.AddOrUpdate(INFOKEY_TOUCHAREA, selection);
int[] newModel = new int[selection.Width*selection.Height];
Parallel.For(0, wholeFrame.Height, y=>{
for(int x = 0; x < wholeFrame.Width; ++x){
if (y > selection.Top && y < selection.Bottom){
if (x > selection.Left && x < selection.Right){
int index = y*wholeFrame.Width+x;
int newX = x - selection.X;
int newY = y - selection.Y;
int newIndex = newY*selection.Width+newX;
newModel[newIndex] = wholeFrame.DistanceInMM[index];
}
}
}
});
var newFrame = new DepthFrame(DateTime.Now, newModel, selection.Width, selection.Height);
info.AddOrUpdate(INFOKEY_BACKGROUND_MODEL, newFrame);
} else {
var area = new Rectangle(0, 0, wholeFrame.Width, wholeFrame.Height);
info.AddOrUpdate(INFOKEY_TOUCHAREA, area);
}
}
private void SetSpinEditValues() {
numWidth.Minimum = 1;
numWidth.Maximum = originalImage.Width - selection.X;
numHeight.Minimum = 1;
numHeight.Maximum = originalImage.Height - selection.Y;
numX.Minimum = 0;
numX.Maximum = originalImage.Width;
numY.Minimum = 0;
numY.Maximum = originalImage.Height;
}
private void AreaChanged(object sender, System.EventArgs e){
selection = new Rectangle((int)numX.Value, (int)numY.Value, (int)numWidth.Value, (int)numHeight.Value);
SetSpinEditValues();
Bitmap newBitmap = new Bitmap(originalImage);
using (Graphics g = Graphics.FromImage(newBitmap)) {
using(Brush b = new SolidBrush(Color.Red)){
using (Pen p = new Pen(b, 2)){
g.DrawRectangle(p, selection);
}
}
}
pbChooseArea.Image = newBitmap;
}
private void rbSpecificArea_CheckedChanged(object sender, EventArgs e) {
numX.Enabled = rbSpecificArea.Checked;
numY.Enabled = rbSpecificArea.Checked;
numWidth.Enabled = rbSpecificArea.Checked;
numHeight.Enabled = rbSpecificArea.Checked;
numX.Value = 100;
numY.Value = 50;
numWidth.Value = 480;
numHeight.Value = 380;
}
private void btnReset_Click(object sender, EventArgs e) {
numX.Value = 100;
numY.Value = 50;
numWidth.Value = 480;
numHeight.Value = 380;
}
}
}
| 29.488889 | 118 | 0.709872 | [
"Apache-2.0"
] | papauorg/touchdown | src/Touchdown.Win.UI/UserControls/InitWizzard/TouchAreaSelectionControl.cs | 3,983 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace NoRainForum.Computer.FrontWeb
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseIISIntegration()
.UseStartup<Startup>();
}
}
| 30.02439 | 127 | 0.596263 | [
"Apache-2.0"
] | MapleWithoutWords/NoRainForum-MicroService | NoRainForum/NoRainForum.Computer.FrontWeb/Program.cs | 1,233 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Geta.InstantTemplates.Sample.Models.Pages;
using EPiServer;
using EPiServer.Core;
using EPiServer.Filters;
using EPiServer.Shell.Configuration;
using EPiServer.Web;
namespace Geta.InstantTemplates.Sample.Business
{
public class ContentLocator
{
private readonly IContentLoader _contentLoader;
private readonly IContentProviderManager _providerManager;
private readonly IPageCriteriaQueryService _pageCriteriaQueryService;
public ContentLocator(IContentLoader contentLoader, IContentProviderManager providerManager, IPageCriteriaQueryService pageCriteriaQueryService)
{
_contentLoader = contentLoader;
_providerManager = providerManager;
_pageCriteriaQueryService = pageCriteriaQueryService;
}
public virtual IEnumerable<T> GetAll<T>(ContentReference rootLink)
where T : PageData
{
var children = _contentLoader.GetChildren<PageData>(rootLink);
foreach (var child in children)
{
var childOfRequestedTyped = child as T;
if (childOfRequestedTyped != null)
{
yield return childOfRequestedTyped;
}
foreach (var descendant in GetAll<T>(child.ContentLink))
{
yield return descendant;
}
}
}
/// <summary>
/// Returns pages of a specific page type
/// </summary>
/// <param name="pageLink"></param>
/// <param name="recursive"></param>
/// <param name="pageTypeId">ID of the page type to filter by</param>
/// <returns></returns>
public IEnumerable<PageData> FindPagesByPageType(PageReference pageLink, bool recursive, int pageTypeId)
{
if (ContentReference.IsNullOrEmpty(pageLink))
{
throw new ArgumentNullException("pageLink", "No page link specified, unable to find pages");
}
var pages = recursive
? FindPagesByPageTypeRecursively(pageLink, pageTypeId)
: _contentLoader.GetChildren<PageData>(pageLink);
return pages;
}
// Type specified through page type ID
private IEnumerable<PageData> FindPagesByPageTypeRecursively(PageReference pageLink, int pageTypeId)
{
var criteria = new PropertyCriteriaCollection
{
new PropertyCriteria
{
Name = "PageTypeID",
Type = PropertyDataType.PageType,
Condition = CompareCondition.Equal,
Value = pageTypeId.ToString(CultureInfo.InvariantCulture)
}
};
// Include content providers serving content beneath the page link specified for the search
if (_providerManager.ProviderMap.CustomProvidersExist)
{
var contentProvider = _providerManager.ProviderMap.GetProvider(pageLink);
if (contentProvider.HasCapability(ContentProviderCapabilities.Search))
{
criteria.Add(new PropertyCriteria
{
Name = "EPI:MultipleSearch",
Value = contentProvider.ProviderKey
});
}
}
return _pageCriteriaQueryService.FindPagesWithCriteria(pageLink, criteria);
}
/// <summary>
/// Returns all contact pages beneath the main contacts container
/// </summary>
/// <returns></returns>
public IEnumerable<ContactPage> GetContactPages()
{
var contactsRootPageLink = _contentLoader.Get<StartPage>(SiteDefinition.Current.StartPage).ContactsPageLink;
if (ContentReference.IsNullOrEmpty(contactsRootPageLink))
{
throw new MissingConfigurationException("No contact page root specified in site settings, unable to retrieve contact pages");
}
return _contentLoader.GetChildren<ContactPage>(contactsRootPageLink).OrderBy(p => p.PageName);
}
}
}
| 39.330435 | 152 | 0.58103 | [
"Apache-2.0"
] | Geta/InstantTemplates | samples/Geta.InstantTemplates.Sample/Business/ContentLocator.cs | 4,523 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Portal
{
public interface IPackageSettingsEditorControl
{
void BindSettings(PackageSettings settings);
void SaveSettings(PackageSettings settings);
}
}
| 44.734694 | 84 | 0.729015 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/Code/ProviderControls/IPackageSettingsEditorControl.cs | 2,192 | C# |
using System;
namespace Tizen.NUI.Binding
{
[TypeConverter(typeof(FlowDirectionConverter))]
internal enum FlowDirection
{
MatchParent = 0,
LeftToRight = 1,
RightToLeft = 2,
}
[Xaml.TypeConversion(typeof(FlowDirection))]
internal class FlowDirectionConverter : TypeConverter
{
public override object ConvertFromInvariantString(string value)
{
if (value != null) {
if (Enum.TryParse(value, out FlowDirection direction))
return direction;
if (value.Equals("ltr", StringComparison.OrdinalIgnoreCase))
return FlowDirection.LeftToRight;
if (value.Equals("rtl", StringComparison.OrdinalIgnoreCase))
return FlowDirection.RightToLeft;
if (value.Equals("inherit", StringComparison.OrdinalIgnoreCase))
return FlowDirection.MatchParent;
}
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", value, typeof(FlowDirection)));
}
}
} | 28.65625 | 119 | 0.739368 | [
"Apache-2.0"
] | mk5004lee/TizenFX | src/Tizen.NUI/src/internal/XamlBinding/FlowDirection.cs | 917 | C# |
namespace MassTransit.RabbitMqTransport.Integration
{
using System.Threading;
using System.Threading.Tasks;
using Contexts;
using GreenPipes;
using GreenPipes.Agents;
using GreenPipes.Internals.Extensions;
using Internals.Extensions;
using RabbitMQ.Client;
public class ScopeModelContextFactory :
IPipeContextFactory<ModelContext>
{
readonly IModelContextSupervisor _supervisor;
public ScopeModelContextFactory(IModelContextSupervisor supervisor)
{
_supervisor = supervisor;
}
IPipeContextAgent<ModelContext> IPipeContextFactory<ModelContext>.CreateContext(ISupervisor supervisor)
{
IAsyncPipeContextAgent<ModelContext> asyncContext = supervisor.AddAsyncContext<ModelContext>();
var context = CreateModel(asyncContext, supervisor.Stopped);
void HandleShutdown(object sender, ShutdownEventArgs args)
{
if (args.Initiator != ShutdownInitiator.Application)
asyncContext.Stop(args.ReplyText);
}
context.ContinueWith(task =>
{
task.Result.Model.ModelShutdown += HandleShutdown;
asyncContext.Completed.ContinueWith(_ => task.Result.Model.ModelShutdown -= HandleShutdown);
}, TaskContinuationOptions.OnlyOnRanToCompletion);
return asyncContext;
}
IActivePipeContextAgent<ModelContext> IPipeContextFactory<ModelContext>.CreateActiveContext(ISupervisor supervisor,
PipeContextHandle<ModelContext> context, CancellationToken cancellationToken)
{
return supervisor.AddActiveContext(context, CreateSharedModel(context.Context, cancellationToken));
}
static async Task<ModelContext> CreateSharedModel(Task<ModelContext> context, CancellationToken cancellationToken)
{
return context.IsCompletedSuccessfully()
? new SharedModelContext(context.Result, cancellationToken)
: new SharedModelContext(await context.OrCanceled(cancellationToken).ConfigureAwait(false), cancellationToken);
}
Task<ModelContext> CreateModel(IAsyncPipeContextAgent<ModelContext> asyncContext, CancellationToken cancellationToken)
{
static Task<ModelContext> CreateModelContext(ModelContext context, CancellationToken createCancellationToken)
{
return Task.FromResult<ModelContext>(new SharedModelContext(context, createCancellationToken));
}
return _supervisor.CreateAgent(asyncContext, CreateModelContext, cancellationToken);
}
}
}
| 39.202899 | 127 | 0.693161 | [
"ECL-2.0",
"Apache-2.0"
] | CodeNotFoundException/MassTransit | src/MassTransit.RabbitMqTransport/Integration/ScopeModelContextFactory.cs | 2,705 | C# |
using System;
namespace S7evemetry.Core.Enums.F1
{
/// <summary>
/// Bit flags specifying which buttons are being pressed currently
/// </summary>
[Flags]
public enum Buttons
{
/// <summary>
/// No buttons pressed
/// </summary>
None = 0x0000,
/// <summary>
/// 0x0001 Cross or A
/// </summary>
A = 0x0001,
/// <summary>
/// 0x0002 Triangle or Y
/// </summary>
Y = 0x0002,
/// <summary>
/// 0x0004 Circle or B
/// </summary>
B = 0x0004,
/// <summary>
/// 0x0008 Square or X
/// </summary>
X = 0x0008,
/// <summary>
/// 0x0010 D-pad Left
/// </summary>
DLeft = 0x0010,
/// <summary>
/// 0x0020 D-pad Right
/// </summary>
DRight = 0x0020,
/// <summary>
/// 0x0040 D-pad Up
/// </summary>
DUp = 0x0040,
/// <summary>
/// 0x0080 D-pad Down
/// </summary>
DDown = 0x0080,
/// <summary>
/// 0x0100 Options or Menu
/// </summary>
Menu = 0x0100,
/// <summary>
/// 0x0200 L1 or LB
/// </summary>
LB = 0x0200,
/// <summary>
/// 0x0400 R1 or RB
/// </summary>
RB = 0x0400,
/// <summary>
/// 0x0800 L2 or LT
/// </summary>
LT = 0x0800,
/// <summary>
/// 0x1000 R2 or RT
/// </summary>
RT = 0x1000,
/// <summary>
/// 0x2000 Left Stick Click
/// </summary>
LeftStick = 0x2000,
/// <summary>
/// 0x4000 Right Stick Click
/// </summary>
RightStick = 0x4000
}
}
| 19.586957 | 70 | 0.415649 | [
"MIT"
] | LuckyNoS7evin/s7evemetry | src/S7evemetry.Core/Enums/F1/Buttons.cs | 1,804 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Albarnie.Interaction2D
{
public interface IInteractable2D
{
float InteractionTime { get; }
Transform GetTransform();
void OnFinishInteract(Interaction2D user);
void OnStartInteract(Interaction2D user);
void OnCancelInteract(Interaction2D user);
void OnBeginFocus(Interaction2D user);
void OnEndFocus(Interaction2D user);
}
} | 25.526316 | 50 | 0.71134 | [
"MIT"
] | Albarnie/Interaction-2D | Scripts/IInteractable2D.cs | 487 | 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("MealPlanOrder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MealPlanOrder")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fc017510-7fa1-4fbd-98aa-2a923edc4615")]
// 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.648649 | 85 | 0.729371 | [
"MIT"
] | nvimai/COMP1030-Assignment2-MealPlanOrder | SourceCode/MealPlanOrder/Properties/AssemblyInfo.cs | 1,433 | C# |
using System;
namespace Stack
{
/// <summary>
/// 栈接口 实现顺序栈 链式栈
/// </summary>
/// <typeparam name="T"></typeparam>
interface IStack<T>
{
/// <summary>
/// 清空栈
/// </summary>
void Clear();
/// <summary>
/// 判断元素是否在栈内
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
bool Contains(T t);
/// <summary>
/// 返回在栈顶部的对象,但不移除它。
/// </summary>
/// <returns></returns>
T Peek();
/// <summary>
/// 出栈
/// </summary>
/// <returns></returns>
T Pop();
/// <summary>
/// 入栈
/// </summary>
/// <param name="t"></param>
void Push(T t);
/// <summary>
/// 栈是否为空
/// </summary>
/// <returns></returns>
bool IsEmpty();
}
}
| 18.6875 | 40 | 0.386845 | [
"BSD-3-Clause"
] | xjlonly/DataStructure | Stack/IStack.cs | 993 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace mantis_tests
{
[TestFixture]
public class ProjectCreationTests : AuthTestBase
{
[Test]
public void ProjectCreationTest()
{
Mantis.ProjectData project = new Mantis.ProjectData();
app.Navigator.GoToProjectPage();
List<Mantis.ProjectData> oldprojects = app.API.GetProjectList(new AccountData("administrator", "root"));
app.API.CreateNewProject(new AccountData("administrator", "root"),new ProjectData(GenerateRandomString(10)));
Assert.AreEqual(oldprojects.Count + 1, app.Project.GetProjectCount());
List<Mantis.ProjectData> newprojects = app.API.GetProjectList(new AccountData("administrator", "root"));
oldprojects.Add(project);
oldprojects.Sort();
newprojects.Sort();
Assert.AreEqual(oldprojects,newprojects);
}
}
}
| 29.771429 | 121 | 0.663148 | [
"Apache-2.0"
] | DievaAlexandra/csharp_training | mantis_tests/mantis_tests/Tests/ProjectCreationTests.cs | 1,044 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using taskt.Core.Automation.Commands;
using static taskt.Core.Automation.User32.User32Functions;
namespace taskt.UI.Forms
{
public partial class frmSequenceRecorder : UIForm
{
public static List<Core.Automation.Commands.ScriptCommand> commandList;
public frmScriptBuilder callBackForm { get; set; }
private bool isRecording { get; set; }
public frmSequenceRecorder()
{
InitializeComponent();
}
private void btnStartRecording_Click(object sender, EventArgs e)
{
}
void OnHookStopped(object sender, EventArgs e)
{
// isRecording = false;
GlobalHook.HookStopped -= new EventHandler(OnHookStopped);
//if (!isRecording)
//{
// return;
//}
pnlOptions.Show();
lblRecording.Hide();
FinalizeRecording();
}
private void FinalizeRecording()
{
var commandList = GlobalHook.generatedCommands;
var outputList = new List<Core.Automation.Commands.ScriptCommand>();
if (chkGroupIntoSequence.Checked)
{
var newSequence = new Core.Automation.Commands.SequenceCommand();
foreach (Core.Automation.Commands.ScriptCommand cmd in commandList)
{
newSequence.v_scriptActions.Add(cmd);
}
if (newSequence.v_scriptActions.Count > 0)
outputList.Add(newSequence);
}
else if (chkGroupMovesIntoSequences.Checked)
{
var newSequence = new Core.Automation.Commands.SequenceCommand();
foreach (Core.Automation.Commands.ScriptCommand cmd in commandList)
{
if (cmd is Core.Automation.Commands.SendMouseMoveCommand)
{
var sendMouseCmd = (Core.Automation.Commands.SendMouseMoveCommand)cmd;
if (sendMouseCmd.v_MouseClick != "None")
{
outputList.Add(newSequence);
newSequence = new Core.Automation.Commands.SequenceCommand();
outputList.Add(cmd);
}
else
{
newSequence.v_scriptActions.Add(cmd);
}
}
else if (cmd is SendKeysCommand)
{
outputList.Add(newSequence);
newSequence = new Core.Automation.Commands.SequenceCommand();
outputList.Add(cmd);
}
else
{
newSequence.v_scriptActions.Add(cmd);
}
}
if (newSequence.v_scriptActions.Count > 0)
outputList.Add(newSequence);
}
else
{
outputList = commandList;
}
var commentCommand = new Core.Automation.Commands.CommentCommand();
commentCommand.v_Comment = "Sequence Recorded " + DateTime.Now.ToString();
outputList.Insert(0, commentCommand);
foreach (var cmd in outputList)
{
callBackForm.AddCommandToListView(cmd);
}
this.Close();
}
private void btnStopRecording_Click(object sender, EventArgs e)
{
GlobalHook.StopHook();
//FinalizeRecording();
}
private void frmSequenceRecorder_Load(object sender, EventArgs e)
{
}
private void chkGroupIntoSequences_CheckedChanged(object sender, EventArgs e)
{
}
private void chkCaptureMouse_CheckedChanged(object sender, EventArgs e)
{
chkGroupMovesIntoSequences.Checked = chkCaptureMouse.Checked;
chkGroupMovesIntoSequences.Enabled = chkGroupMovesIntoSequences.Checked;
}
private void uiBtnRecord_Click(object sender, EventArgs e)
{
if (uiBtnRecord.DisplayText == "Start")
{
this.Height = 150;
this.BringToFront();
MoveFormToBottomRight(this);
this.TopMost = true;
uiBtnRecord.Top = lblRecording.Top + 50;
pnlOptions.Hide();
lblRecording.Show();
int.TryParse(txtHookResolution.Text, out int samplingResolution);
GlobalHook.HookStopped += new EventHandler(OnHookStopped);
GlobalHook.StartScreenRecordingHook(chkCaptureClicks.Checked, chkCaptureMouse.Checked, chkGroupMovesIntoSequences.Checked, chkCaptureKeyboard.Checked, chkCaptureWindowEvents.Checked, chkActivateTopLeft.Checked, chkTrackWindowSize.Checked, chkTrackWindowsOpenLocation.Checked, samplingResolution, txtHookStop.Text);
lblRecording.Text = "Press '" + txtHookStop.Text + "' key to stop recording!";
// WindowHook.StartHook();
commandList = new List<Core.Automation.Commands.ScriptCommand>();
uiBtnRecord.DisplayText = "Stop";
uiBtnRecord.Image = taskt.Properties.Resources.various_stop_button;
}
else
{
GlobalHook.StopHook();
}
}
private void chkActivateTopLeft_CheckedChanged(object sender, EventArgs e)
{
if (chkActivateTopLeft.Checked)
chkTrackWindowsOpenLocation.Checked = false;
}
private void chkTrackWindowsOpenLocation_CheckedChanged(object sender, EventArgs e)
{
if (chkTrackWindowsOpenLocation.Checked)
chkActivateTopLeft.Checked = false;
}
}
}
| 27.447826 | 330 | 0.554887 | [
"Apache-2.0"
] | Faro1991/taskt | taskt/UI/Forms/frmSequenceRecorder.cs | 6,315 | C# |
using System;
using Lykke.AlgoStore.CSharp.AlgoTemplate.Models.Models;
using Lykke.AlgoStore.CSharp.AlgoTemplate.Models.Repositories;
using Moq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xunit;
namespace Lykke.AlgoStore.Service.AlgoTrades.Tests.Mocks
{
public static class AlgoInstanceTradesRepositoryMock
{
public static string MockedWalletId => _mockWalletId;
public static string MockedInstanceId => _mockInstanceId;
public static string MockedOrderId => _mockOrderId;
public static double MockedAmount => _mockedAmount;
public static double MockedFee => _mockedFee;
public static double MockedPrice => _mockedPrice;
public static string MockedDateString => _mockedDateString;
private static readonly string _mockWalletId = "1ed49482-2108-4b39-97ed-61ca1f4df510";
private static readonly string _mockInstanceId = "1xd49482-2108-4b39-97ed-61ca1f4df410";
private static readonly string _mockOrderId = "32d49482-21sz-4b39-14ed-61ca1f4df510";
private static readonly double _mockedAmount = 5;
private static readonly double _mockedFee = 0.05;
private static readonly double _mockedPrice = 5000;
private static readonly string _mockedDateString = "2018-05-03";
public static IAlgoInstanceTradeRepository GetAlgoInstanceTradeRepositoryRepository()
{
var repoMock = new Mock<IAlgoInstanceTradeRepository>();
repoMock.Setup(r => r.GetAlgoInstaceTradesByTradedAssetAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>()))
.Returns(Task.FromResult(GetByTradedAsset()));
return repoMock.Object;
}
public static IAlgoInstanceTradeRepository GetAlgoInstanceTradeRepositoryRepository_ForHistoryWriter()
{
var repoMock = new Mock<IAlgoInstanceTradeRepository>();
var mockedTrade = GetTestTrade();
repoMock.Setup(r => r.GetAlgoInstanceOrderAsync(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult(GetOrder()));
repoMock.Setup(r => r.SaveAlgoInstanceTradeAsync(It.IsAny<AlgoInstanceTrade>())).Returns((AlgoInstanceTrade trade) =>
{
CheckIsEqualClientId(trade, mockedTrade);
return Task.CompletedTask;
});
return repoMock.Object;
}
private static void CheckIsEqualClientId(AlgoInstanceTrade savedTrade, AlgoInstanceTrade testTrade)
{
string first = JsonConvert.SerializeObject(savedTrade);
string second = JsonConvert.SerializeObject(testTrade);
Assert.Equal(first, second);
}
private static IEnumerable<AlgoInstanceTrade> GetByTradedAsset()
{
var result = new List<AlgoInstanceTrade>();
result.Add(new AlgoInstanceTrade()
{
Amount = _mockedAmount,
AssetId = "USD",
AssetPairId = "BTCUSD",
Fee = _mockedFee,
IsBuy = true,
Price = _mockedPrice,
WalletId = _mockWalletId,
InstanceId = _mockInstanceId,
OrderId = _mockOrderId
});
return result;
}
private static AlgoInstanceTrade GetOrder()
{
return new AlgoInstanceTrade()
{
AssetId = "USD",
AssetPairId = "BTCUSD",
IsBuy = true,
WalletId = _mockWalletId,
InstanceId = _mockInstanceId,
OrderId = _mockOrderId,
Price = _mockedPrice,
Amount = 5,
};
}
private static AlgoInstanceTrade GetTestTrade()
{
return new AlgoInstanceTrade()
{
Amount = _mockedAmount,
AssetId = "USD",
AssetPairId = "BTCUSD",
Fee = 0.05,
IsBuy = true,
Price = _mockedPrice,
WalletId = _mockWalletId,
InstanceId = _mockInstanceId,
OrderId = _mockOrderId,
DateOfTrade = Convert.ToDateTime(_mockedDateString)
};
}
}
}
| 36.957627 | 130 | 0.6072 | [
"MIT"
] | LykkeCity/Lykke.AlgoStore.Job.AlgoTrades | tests/Lykke.AlgoStore.Service.AlgoTrades.Tests/Mocks/AlgoInstanceTradesRepositoryMock.cs | 4,363 | C# |
namespace BrightstarDB.Storage
{
/// <summary>
/// Enumeration of the different types of store supported by B*
/// </summary>
internal enum StoreType
{
Standard = 0
}
} | 20.1 | 67 | 0.60199 | [
"MIT"
] | BrightstarDB/BrightstarDB | src/core/BrightstarDB.Core/Storage/StoreType.cs | 201 | C# |
/* Copyright (c) 2017 ExT (V.Sigalkin) */
using UnityEngine;
using extOSC.Core.Events;
namespace extOSC.Components.Events
{
[AddComponentMenu("extOSC/Components/Receiver/Double Event")]
public class OSCReceiverEventDouble : OSCReceiverEvent<OSCEventDouble>
{
#region Protected Methods
protected override void Invoke(OSCMessage message)
{
double value;
if (message.ToDouble(out value))
{
if (onReceive != null)
onReceive.Invoke(value);
}
}
#endregion
}
} | 22.185185 | 74 | 0.590985 | [
"MIT"
] | mpinner/RealsenseOscMulticast | UnityRealsenseOscMulticastInterface/OscMulticast/Assets/extOSC/Scripts/Compontents/Events/OSCReceiverEventDouble.cs | 599 | C# |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System;
namespace Tomlyn.Syntax
{
/// <summary>
/// A TOML key = value syntax node.
/// </summary>
public sealed class KeyValueSyntax : SyntaxNode
{
private KeySyntax _key;
private SyntaxToken _equalToken;
private ValueSyntax _value;
private SyntaxToken _endOfLineToken;
/// <summary>
/// Creates an instance of <see cref="KeyValueSyntax"/>
/// </summary>
public KeyValueSyntax() : base(SyntaxKind.KeyValue)
{
}
/// <summary>
/// Creates an instance of <see cref="KeyValueSyntax"/>
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
public KeyValueSyntax(string key, ValueSyntax value) : this()
{
if (key == null) throw new ArgumentNullException(nameof(key));
Key = new KeySyntax(key);
Value = value ?? throw new ArgumentNullException(nameof(value));
EqualToken = SyntaxFactory.Token(TokenKind.Equal);
EqualToken.AddLeadingWhitespace();
EqualToken.AddTrailingWhitespace();
EndOfLineToken = SyntaxFactory.NewLine();
}
/// <summary>
/// Creates an instance of <see cref="KeyValueSyntax"/>
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
public KeyValueSyntax(KeySyntax key, ValueSyntax value) : this()
{
Key = key ?? throw new ArgumentNullException(nameof(key));
Value = value ?? throw new ArgumentNullException(nameof(value));
EqualToken = SyntaxFactory.Token(TokenKind.Equal);
EqualToken.AddLeadingWhitespace();
EqualToken.AddTrailingWhitespace();
EndOfLineToken = SyntaxFactory.NewLine();
}
/// <summary>
/// Gets or sets the key.
/// </summary>
public KeySyntax Key
{
get => _key;
set => ParentToThis(ref _key, value);
}
/// <summary>
/// Gets or sets the `=` token
/// </summary>
public SyntaxToken EqualToken
{
get => _equalToken;
set => ParentToThis(ref _equalToken, value, TokenKind.Equal);
}
/// <summary>
/// Gets or sets the value
/// </summary>
public ValueSyntax Value
{
get => _value;
set => ParentToThis(ref _value, value);
}
/// <summary>
/// Gets or sets the new-line token.
/// </summary>
public SyntaxToken EndOfLineToken
{
get => _endOfLineToken;
set => ParentToThis(ref _endOfLineToken, value, TokenKind.NewLine, TokenKind.Eof);
}
public override int ChildrenCount => 4;
public override void Accept(SyntaxVisitor visitor)
{
visitor.Visit(this);
}
protected override SyntaxNode GetChildrenImpl(int index)
{
switch (index)
{
case 0:
return Key;
case 1:
return EqualToken;
case 2:
return Value;
default:
return EndOfLineToken;
}
}
}
} | 30.930435 | 94 | 0.538375 | [
"BSD-2-Clause"
] | 0xced/Tomlyn | src/Tomlyn/Syntax/KeyValueSyntax.cs | 3,557 | C# |
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Symbology;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace ArcGISRuntimeSDKDotNet_DesktopSamples.Samples
{
/// <summary>
/// Sample shows how to use the GeometryEngine.Relate method to test the spatial relationship of two geometries.
/// </summary>
/// <title>Relate</title>
/// <category>Geometry</category>
public partial class Relate : UserControl
{
private List<Symbol> _symbols;
/// <summary>Construct Relationship sample control</summary>
public Relate()
{
InitializeComponent();
_symbols = new List<Symbol>();
_symbols.Add(layoutGrid.Resources["PointSymbol"] as Symbol);
_symbols.Add(layoutGrid.Resources["LineSymbol"] as Symbol);
_symbols.Add(layoutGrid.Resources["FillSymbol"] as Symbol);
mapView.ExtentChanged += mapView_ExtentChanged;
}
// Start map interaction
private void mapView_ExtentChanged(object sender, EventArgs e)
{
try
{
mapView.ExtentChanged -= mapView_ExtentChanged;
btnDraw.IsEnabled = true;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Relationship Sample");
}
}
// Accepts two user shapes and adds them to the graphics layer
private async void StartDrawingButton_Click(object sender, RoutedEventArgs e)
{
try
{
btnDraw.IsEnabled = false;
btnTest.IsEnabled = false;
resultPanel.Visibility = Visibility.Collapsed;
graphicsLayer.Graphics.Clear();
// Shape One
DrawShape drawShape1 = (DrawShape)comboShapeOne.SelectedItem;
Esri.ArcGISRuntime.Geometry.Geometry shapeOne = null;
if (drawShape1 == DrawShape.Point)
shapeOne = await mapView.Editor.RequestPointAsync();
else
shapeOne = await mapView.Editor.RequestShapeAsync(drawShape1, _symbols[comboShapeOne.SelectedIndex]);
graphicsLayer.Graphics.Add(new Graphic(shapeOne, _symbols[comboShapeOne.SelectedIndex]));
// Shape Two
Esri.ArcGISRuntime.Geometry.Geometry shapeTwo = await mapView.Editor.RequestShapeAsync(
(DrawShape)comboShapeTwo.SelectedItem, _symbols[comboShapeTwo.SelectedIndex]);
graphicsLayer.Graphics.Add(new Graphic(shapeTwo, _symbols[comboShapeTwo.SelectedIndex]));
}
catch (TaskCanceledException)
{
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Relationship Sample");
}
finally
{
btnDraw.IsEnabled = true;
btnTest.IsEnabled = (graphicsLayer.Graphics.Count >= 2);
}
}
// Checks the specified relationship of the two shapes
private void RelateButton_Click(object sender, RoutedEventArgs e)
{
try
{
if (graphicsLayer.Graphics.Count < 2)
throw new ApplicationException("No shapes abailable for relationship test");
var shape1 = graphicsLayer.Graphics[0].Geometry;
var shape2 = graphicsLayer.Graphics[1].Geometry;
string relate = comboRelate.Text;
if (relate.Length < 9)
throw new ApplicationException("DE-9IM relate string must be 9 characters");
relate = relate.Substring(0, 9);
bool isRelated = GeometryEngine.Relate(shape1, shape2, relate);
resultPanel.Visibility = Visibility.Visible;
resultPanel.Background = new SolidColorBrush((isRelated) ? Color.FromArgb(0x66, 0, 0xFF, 0) : Color.FromArgb(0x66, 0xFF, 0, 0));
resultPanel.DataContext = string.Format("Relationship: '{0}' is {1}", relate, isRelated.ToString());
}
catch (Exception ex)
{
resultPanel.Visibility = Visibility.Collapsed;
MessageBox.Show("Error: " + ex.Message, "Relationship Sample");
}
}
}
}
| 37.508197 | 144 | 0.59222 | [
"Apache-2.0"
] | boonyachengdu/arcgis-runtime-samples-dotnet | src/Desktop/ArcGISRuntimeSDKDotNet_DesktopSamples/Samples/Geometry/Relate.xaml.cs | 4,578 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using NDream.AirConsole;
using Newtonsoft.Json.Linq;
public class TotalDeviceText : MonoBehaviour
{
UnityEngine.UI.Text thisText;
// Use this for initialization
void Start()
{
thisText = GetComponent<UnityEngine.UI.Text>();
}
// Update is called once per frame
void Update()
{
try
{
thisText.text = "Total Device Count: " + AirConsole.instance.GetControllerDeviceIds().Count;
}
catch
{
thisText.text = "Total Device Count: 0";
}
}
}
| 20.0625 | 104 | 0.609034 | [
"MIT"
] | Caseyfam/Falling-Fighters | Assets/Scripts/Menu Scripts/Debug Scripts/TotalDeviceText.cs | 644 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Skoruba.IdentityServer4.Admin.EntityFramework.Identity.Entities.Identity;
namespace Skoruba.IdentityServer4.STS.Identity.Quickstart.Account
{
[SecurityHeaders]
public class AccountController : Controller
{
private readonly UserManager<UserIdentity> _userManager;
private readonly SignInManager<UserIdentity> _signInManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IAuthenticationSchemeProvider _schemeProvider;
private readonly IEventService _events;
public AccountController(
UserManager<UserIdentity> userManager,
SignInManager<UserIdentity> signInManager,
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IAuthenticationSchemeProvider schemeProvider,
IEventService events)
{
_userManager = userManager;
_signInManager = signInManager;
_interaction = interaction;
_clientStore = clientStore;
_schemeProvider = schemeProvider;
_events = events;
}
/// <summary>
/// Show login page
/// </summary>
[HttpGet]
public async Task<IActionResult> Login(string returnUrl)
{
// build a model so we know what to show on the login page
var vm = await BuildLoginViewModelAsync(returnUrl);
if (vm.IsExternalLoginOnly)
{
// we only have one option for logging in and it's an external provider
return await ExternalLogin(vm.ExternalLoginScheme, returnUrl);
}
return View(vm);
}
/// <summary>
/// Handle postback from username/password login
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string button)
{
if (button != "login")
{
// the user clicked the "cancel" button
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (context != null)
{
// if the user cancels, send a result back into IdentityServer as if they
// denied the consent (even if this client does not require consent).
// this will send back an access denied OIDC error response to the client.
await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}
else
{
// since we don't have a valid context, then we just go back to the home page
return Redirect("~/");
}
}
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await _userManager.FindByNameAsync(model.Username);
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName));
// make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
// the IsLocalUrl check is only necessary if you want to support additional local pages, otherwise IsValidReturnUrl is more strict
if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return Redirect("~/");
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));
ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
var vm = await BuildLoginViewModelAsync(model);
return View(vm);
}
/// <summary>
/// initiate roundtrip to external authentication provider
/// </summary>
[HttpGet]
public async Task<IActionResult> ExternalLogin(string provider, string returnUrl)
{
if (AccountOptions.WindowsAuthenticationSchemeName == provider)
{
// windows authentication needs special handling
return await ProcessWindowsLoginAsync(returnUrl);
}
else
{
// start challenge and roundtrip the return URL and
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("ExternalLoginCallback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", provider },
}
};
return Challenge(props, provider);
}
}
/// <summary>
/// Post processing of external authentication
/// </summary>
[HttpGet]
public async Task<IActionResult> ExternalLoginCallback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = await AutoProvisionUserAsync(provider, providerUserId, claims);
}
// this allows us to collect any additonal claims or properties
// for the specific prtotocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
// we must issue the cookie maually, and can't use the SignInManager because
// it doesn't expose an API to issue additional claims from the login workflow
var principal = await _signInManager.CreateUserPrincipalAsync(user);
additionalLocalClaims.AddRange(principal.Claims);
var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id.ToString();
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id.ToString(), name));
await HttpContext.SignInAsync(user.Id.ToString(), name, provider, localSignInProps, additionalLocalClaims.ToArray());
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// validate return URL and redirect back to authorization endpoint or a local page
var returnUrl = result.Properties.Items["returnUrl"];
if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("~/");
}
/// <summary>
/// Show logout page
/// </summary>
[HttpGet]
public async Task<IActionResult> Logout(string logoutId)
{
// build a model so the logout page knows what to display
var vm = await BuildLogoutViewModelAsync(logoutId);
if (vm.ShowLogoutPrompt == false)
{
// if the request for logout was properly authenticated from IdentityServer, then
// we don't need to show the prompt and can just log the user out directly.
return await Logout(vm);
}
return View(vm);
}
/// <summary>
/// Handle logout page postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout(LogoutInputModel model)
{
// build a model so the logged out page knows what to display
var vm = await BuildLoggedOutViewModelAsync(model.LogoutId);
if (User?.Identity.IsAuthenticated == true)
{
// delete local authentication cookie
await _signInManager.SignOutAsync();
// raise the logout event
await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));
}
// check if we need to trigger sign-out at an upstream identity provider
if (vm.TriggerExternalSignout)
{
// build a return URL so the upstream provider will redirect back
// to us after the user has logged out. this allows us to then
// complete our single sign-out processing.
string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
// this triggers a redirect to the external provider for sign-out
return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
}
return View("LoggedOut", vm);
}
/*****************************************/
/* helper APIs for the AccountController */
/*****************************************/
private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
{
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null)
{
// this is meant to short circuit the UI and only trigger the one external IdP
return new LoginViewModel
{
EnableLocalLogin = false,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
ExternalProviders = new ExternalProvider[] { new ExternalProvider { AuthenticationScheme = context.IdP } }
};
}
var schemes = await _schemeProvider.GetAllSchemesAsync();
var providers = schemes
.Where(x => x.DisplayName != null ||
(x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
)
.Select(x => new ExternalProvider
{
DisplayName = x.DisplayName,
AuthenticationScheme = x.Name
}).ToList();
var allowLocal = true;
if (context?.ClientId != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);
if (client != null)
{
allowLocal = client.EnableLocalLogin;
if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
{
providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
}
}
}
return new LoginViewModel
{
AllowRememberLogin = AccountOptions.AllowRememberLogin,
EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
ExternalProviders = providers.ToArray()
};
}
private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model)
{
var vm = await BuildLoginViewModelAsync(model.ReturnUrl);
vm.Username = model.Username;
vm.RememberLogin = model.RememberLogin;
return vm;
}
private async Task<LogoutViewModel> BuildLogoutViewModelAsync(string logoutId)
{
var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt };
if (User?.Identity.IsAuthenticated != true)
{
// if the user is not authenticated, then just show logged out page
vm.ShowLogoutPrompt = false;
return vm;
}
var context = await _interaction.GetLogoutContextAsync(logoutId);
if (context?.ShowSignoutPrompt == false)
{
// it's safe to automatically sign-out
vm.ShowLogoutPrompt = false;
return vm;
}
// show the logout prompt. this prevents attacks where the user
// is automatically signed out by another malicious web page.
return vm;
}
private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId)
{
// get context information (client name, post logout redirect URI and iframe for federated signout)
var logout = await _interaction.GetLogoutContextAsync(logoutId);
var vm = new LoggedOutViewModel
{
AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut,
PostLogoutRedirectUri = logout?.PostLogoutRedirectUri,
ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName,
SignOutIframeUrl = logout?.SignOutIFrameUrl,
LogoutId = logoutId
};
if (User?.Identity.IsAuthenticated == true)
{
var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value;
if (idp != null && idp != global::IdentityServer4.IdentityServerConstants.LocalIdentityProvider)
{
var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp);
if (providerSupportsSignout)
{
if (vm.LogoutId == null)
{
// if there's no current logout context, we need to create one
// this captures necessary info from the current logged in user
// before we signout and redirect away to the external IdP for signout
vm.LogoutId = await _interaction.CreateLogoutContextAsync();
}
vm.ExternalAuthenticationScheme = idp;
}
}
}
return vm;
}
private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl)
{
// see if windows auth has already been requested and succeeded
var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
// we will issue the external cookie and then redirect the
// user back to the external callback, in essence, tresting windows
// auth the same as any other external authentication mechanism
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("ExternalLoginCallback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", AccountOptions.WindowsAuthenticationSchemeName },
}
};
var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
// add the groups as claims -- be careful if the number of groups is too large
if (AccountOptions.IncludeWindowsGroups)
{
var wi = wp.Identity as WindowsIdentity;
var groups = wi.Groups.Translate(typeof(NTAccount));
var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
id.AddClaims(roles);
}
await HttpContext.SignInAsync(
IdentityConstants.ExternalScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
else
{
// trigger windows auth
// since windows auth don't support the redirect uri,
// this URL is re-triggered when we call challenge
return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
}
}
private async Task<(UserIdentity user, string provider, string providerUserId, IEnumerable<Claim> claims)>
FindUserFromExternalProviderAsync(AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
var user = await _userManager.FindByLoginAsync(provider, providerUserId);
return (user, provider, providerUserId, claims);
}
private async Task<UserIdentity> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable<Claim> claims)
{
// create a list of claims that we want to transfer into our store
var filtered = new List<Claim>();
// user's display name
var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
if (name != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, name));
}
else
{
var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
if (first != null && last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
}
else if (first != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first));
}
else if (last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, last));
}
}
// email
var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
if (email != null)
{
filtered.Add(new Claim(JwtClaimTypes.Email, email));
}
var user = new UserIdentity
{
UserName = Guid.NewGuid().ToString(),
};
var identityResult = await _userManager.CreateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
if (filtered.Any())
{
identityResult = await _userManager.AddClaimsAsync(user, filtered);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
return user;
}
private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
// if the external provider issued an id_token, we'll keep it for signout
var id_token = externalResult.Properties.GetTokenValue("id_token");
if (id_token != null)
{
localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
}
private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
}
} | 44.212569 | 153 | 0.583344 | [
"MIT"
] | H-Ahmadi/GodOfWar | STS/src/Skoruba.IdentityServer4.STS.Identity/Quickstart/Account/AccountController.cs | 23,921 | C# |
//
// System.ComponentModel.InvalidEnumArgumentException test cases
//
// Authors:
// Gert Driesen (drieseng@users.sourceforge.net)
//
// (c) 2007 Gert Driesen
//
using System;
using System.ComponentModel;
using System.Globalization;
using NUnit.Framework;
namespace MonoTests.System.ComponentModel
{
[TestFixture]
public class InvalidEnumArgumentExceptionTest
{
[Test] // ctor ()
public void Constructor0 ()
{
InvalidEnumArgumentException iea = new InvalidEnumArgumentException ();
Assert.IsNull (iea.InnerException, "#1");
Assert.IsNotNull (iea.Message, "#2");
Assert.IsTrue (iea.Message.IndexOf (typeof (InvalidEnumArgumentException).FullName) != -1, "#3");
Assert.IsNull (iea.ParamName, "#4");
}
[Test] // ctor (string)
public void Constructor1 ()
{
InvalidEnumArgumentException iea;
iea = new InvalidEnumArgumentException ("msg");
Assert.IsNull (iea.InnerException, "#A1");
Assert.IsNotNull (iea.Message, "#A2");
Assert.AreEqual ("msg", iea.Message, "#A3");
Assert.IsNull (iea.ParamName, "#A4");
iea = new InvalidEnumArgumentException (string.Empty);
Assert.IsNull (iea.InnerException, "#B1");
Assert.IsNotNull (iea.Message, "#B2");
Assert.AreEqual (string.Empty, iea.Message, "#B3");
Assert.IsNull (iea.ParamName, "#B4");
iea = new InvalidEnumArgumentException ((string) null);
Assert.IsNull (iea.InnerException, "#C1");
Assert.IsNotNull (iea.Message, "#C2");
Assert.IsTrue (iea.Message.IndexOf (typeof (InvalidEnumArgumentException).FullName) != -1, "#C3");
Assert.IsNull (iea.ParamName, "#C4");
}
// TODO: ctor (SerializationInfo, StreamingContext)
[Test] // ctor (string, Exception)
public void Constructor3 ()
{
InvalidEnumArgumentException iea;
Exception inner = new Exception ("INNER");
iea = new InvalidEnumArgumentException ("msg", (Exception) null);
Assert.IsNull (iea.InnerException, "#A1");
Assert.IsNotNull (iea.Message, "#A2");
Assert.AreEqual ("msg", iea.Message, "#A3");
Assert.IsNull (iea.ParamName, "#A4");
iea = new InvalidEnumArgumentException (string.Empty, inner);
Assert.AreSame (inner, iea.InnerException, "#B1");
Assert.IsNotNull (iea.Message, "#B2");
Assert.AreEqual (string.Empty, iea.Message, "#B3");
Assert.IsNull (iea.ParamName, "#B4");
iea = new InvalidEnumArgumentException ((string) null, inner);
Assert.AreSame (inner, iea.InnerException, "#C1");
Assert.IsNotNull (iea.Message, "#C2");
Assert.IsTrue (iea.Message.IndexOf (typeof (InvalidEnumArgumentException).FullName) != -1, "#C3");
Assert.IsNull (iea.ParamName, "#C4");
}
[Test] // ctor (string, int, System.Type)
public void Constructor4 ()
{
InvalidEnumArgumentException iea;
Type enumClass = typeof (AttributeTargets);
// The value of argument 'value' (667666) is invalid for
// Enum type 'AttributeTargets'
iea = new InvalidEnumArgumentException ("arg", 667666, enumClass);
Assert.IsNull (iea.InnerException, "#A1");
Assert.IsNotNull (iea.Message, "#A2");
Assert.IsTrue (iea.Message.IndexOf ("'arg'") != -1, "#A3");
Assert.IsTrue (iea.Message.IndexOf ("(" + 667666.ToString (CultureInfo.CurrentCulture) + ")") != -1, "#A4");
Assert.IsTrue (iea.Message.IndexOf ("'" + enumClass.Name + "'") != -1, "#A5");
Assert.IsNotNull (iea.ParamName, "#A6");
Assert.AreEqual ("arg", iea.ParamName, "#A7");
// The value of argument '' (0) is invalid for
// Enum type 'AttributeTargets'
iea = new InvalidEnumArgumentException (string.Empty, 0, enumClass);
Assert.IsNull (iea.InnerException, "#B1");
Assert.IsNotNull (iea.Message, "#B2");
Assert.IsTrue (iea.Message.IndexOf ("''") != -1, "#B3");
Assert.IsTrue (iea.Message.IndexOf ("(" + 0.ToString (CultureInfo.CurrentCulture) + ")") != -1, "#B4");
Assert.IsTrue (iea.Message.IndexOf ("'" + enumClass.Name + "'") != -1, "#B5");
Assert.IsNotNull (iea.ParamName, "#B6");
Assert.AreEqual (string.Empty, iea.ParamName, "#B7");
// The value of argument '' (-56776) is invalid for Enum type
// 'AttributeTargets'
iea = new InvalidEnumArgumentException ((string) null, -56776, enumClass);
Assert.IsNull (iea.InnerException, "#C1");
Assert.IsNotNull (iea.Message, "#C2");
Assert.IsTrue (iea.Message.IndexOf ("''") != -1, "#C3");
Assert.IsTrue (iea.Message.IndexOf ("(" + (-56776).ToString (CultureInfo.CurrentCulture) + ")") != -1, "#C4");
Assert.IsTrue (iea.Message.IndexOf ("'" + enumClass.Name + "'") != -1, "#C5");
Assert.IsNull (iea.ParamName, "#C6");
// The value of argument '' (0) is invalid for Enum type
// 'AttributeTargets'
iea = new InvalidEnumArgumentException ((string) null, 0, enumClass);
Assert.IsNull (iea.InnerException, "#D1");
Assert.IsNotNull (iea.Message, "#D2");
Assert.IsTrue (iea.Message.IndexOf ("''") != -1, "#D3");
Assert.IsTrue (iea.Message.IndexOf ("(" + 0.ToString (CultureInfo.CurrentCulture) + ")") != -1, "#D4");
Assert.IsTrue (iea.Message.IndexOf ("'" + enumClass.Name + "'") != -1, "#D5");
Assert.IsNull (iea.ParamName, "#D6");
}
[Test] // ctor (string, int, System.Type)
[ExpectedException (typeof (NullReferenceException))]
public void Constructor4_EnumClass_Null ()
{
new InvalidEnumArgumentException ("param", 55, (Type) null);
}
}
}
| 38.143885 | 113 | 0.667673 | [
"Apache-2.0"
] | AvolitesMarkDaniel/mono | mcs/class/System/Test/System.ComponentModel/InvalidEnumArgumentExceptionTest.cs | 5,302 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iotsitewise-2019-12-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoTSiteWise.Model
{
/// <summary>
/// This is the response object from the BatchGetAssetPropertyAggregates operation.
/// </summary>
public partial class BatchGetAssetPropertyAggregatesResponse : AmazonWebServiceResponse
{
private List<BatchGetAssetPropertyAggregatesErrorEntry> _errorEntries = new List<BatchGetAssetPropertyAggregatesErrorEntry>();
private string _nextToken;
private List<BatchGetAssetPropertyAggregatesSkippedEntry> _skippedEntries = new List<BatchGetAssetPropertyAggregatesSkippedEntry>();
private List<BatchGetAssetPropertyAggregatesSuccessEntry> _successEntries = new List<BatchGetAssetPropertyAggregatesSuccessEntry>();
/// <summary>
/// Gets and sets the property ErrorEntries.
/// <para>
/// A list of the errors (if any) associated with the batch request. Each error entry
/// contains the <code>entryId</code> of the entry that failed.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<BatchGetAssetPropertyAggregatesErrorEntry> ErrorEntries
{
get { return this._errorEntries; }
set { this._errorEntries = value; }
}
// Check to see if ErrorEntries property is set
internal bool IsSetErrorEntries()
{
return this._errorEntries != null && this._errorEntries.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token for the next set of results, or null if there are no additional results.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=4096)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property SkippedEntries.
/// <para>
/// A list of entries that were not processed by this batch request. because these entries
/// had been completely processed by previous paginated requests. Each skipped entry contains
/// the <code>entryId</code> of the entry that skipped.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<BatchGetAssetPropertyAggregatesSkippedEntry> SkippedEntries
{
get { return this._skippedEntries; }
set { this._skippedEntries = value; }
}
// Check to see if SkippedEntries property is set
internal bool IsSetSkippedEntries()
{
return this._skippedEntries != null && this._skippedEntries.Count > 0;
}
/// <summary>
/// Gets and sets the property SuccessEntries.
/// <para>
/// A list of entries that were processed successfully by this batch request. Each success
/// entry contains the <code>entryId</code> of the entry that succeeded and the latest
/// query result.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<BatchGetAssetPropertyAggregatesSuccessEntry> SuccessEntries
{
get { return this._successEntries; }
set { this._successEntries = value; }
}
// Check to see if SuccessEntries property is set
internal bool IsSetSuccessEntries()
{
return this._successEntries != null && this._successEntries.Count > 0;
}
}
} | 37.056911 | 140 | 0.642606 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/IoTSiteWise/Generated/Model/BatchGetAssetPropertyAggregatesResponse.cs | 4,558 | C# |
using System;
namespace Artist_Manager_Bot
{
public sealed class UserChangedEventArgs : EventArgs
{
public int Id { get; private set; }
public string Param { get; private set; }
public UserChangedEventArgs(int id, string param)
{
Id = id;
Param = param;
}
}
}
| 19.941176 | 57 | 0.572271 | [
"MIT"
] | Quantum-0/ArtistManagerVkBot | Artist Manager Bot/UserChangedEventArgs.cs | 341 | C# |
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using renderdocui.Windows;
using renderdocui.Windows.Dialogs;
using renderdocui.Windows.PipelineState;
using renderdoc;
namespace renderdocui.Code
{
// Single core class. Between this and the RenderManager these classes govern the interaction
// between the UI and the actual implementation.
//
// This class primarily controls things that need to be propogated globally, it keeps a list of
// ILogViewerForms which are windows that would like to be notified of changes to the current event,
// when a log is opened or closed, etc. It also contains data that potentially every window will
// want access to - like a list of all buffers in the log and their properties, etc.
public class Core
{
#region Privates
private RenderManager m_Renderer = new RenderManager();
private PersistantConfig m_Config = null;
private bool m_LogLocal = false;
private bool m_LogLoaded = false;
private FileSystemWatcher m_LogWatcher = null;
private string m_LogFile = "";
private UInt32 m_EventID = 0;
private APIProperties m_APIProperties = null;
private FetchFrameInfo m_FrameInfo = null;
private FetchDrawcall[] m_DrawCalls = null;
private FetchBuffer[] m_Buffers = null;
private FetchTexture[] m_Textures = null;
private D3D11PipelineState m_D3D11PipelineState = null;
private D3D12PipelineState m_D3D12PipelineState = null;
private GLPipelineState m_GLPipelineState = null;
private VulkanPipelineState m_VulkanPipelineState = null;
private CommonPipelineState m_PipelineState = new CommonPipelineState();
private List<ILogViewerForm> m_LogViewers = new List<ILogViewerForm>();
private List<ILogLoadProgressListener> m_ProgressListeners = new List<ILogLoadProgressListener>();
private MainWindow m_MainWindow = null;
private EventBrowser m_EventBrowser = null;
private APIInspector m_APIInspector = null;
private DebugMessages m_DebugMessages = null;
private TimelineBar m_TimelineBar = null;
private TextureViewer m_TextureViewer = null;
private BufferViewer m_MeshViewer = null;
private PipelineStateViewer m_PipelineStateViewer = null;
private StatisticsViewer m_StatisticsViewer = null;
#endregion
#region Properties
public static string ConfigDirectory
{
get
{
string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(appdata, "renderdoc");
}
}
public static string ConfigFilename
{
get
{
return Path.Combine(ConfigDirectory, "UI.config");
}
}
public PersistantConfig Config { get { return m_Config; } }
public bool LogLoaded { get { return m_LogLoaded; } }
public bool LogLoading { get { return m_LogLoadingInProgress; } }
public string LogFileName { get { return m_LogFile; } set { if (LogLoaded) m_LogFile = value; } }
public bool IsLogLocal { get { return m_LogLocal; } set { m_LogLocal = value; } }
public FetchFrameInfo FrameInfo { get { return m_FrameInfo; } }
public APIProperties APIProps { get { return m_APIProperties; } }
public UInt32 CurEvent { get { return m_EventID; } }
public FetchDrawcall[] CurDrawcalls { get { return GetDrawcalls(); } }
public FetchDrawcall CurDrawcall { get { return GetDrawcall(CurEvent); } }
public FetchTexture[] CurTextures { get { return m_Textures; } }
public FetchBuffer[] CurBuffers { get { return m_Buffers; } }
public FetchTexture GetTexture(ResourceId id)
{
if (id == ResourceId.Null) return null;
for (int t = 0; t < m_Textures.Length; t++)
if (m_Textures[t].ID == id)
return m_Textures[t];
return null;
}
public FetchBuffer GetBuffer(ResourceId id)
{
if (id == ResourceId.Null) return null;
for (int b = 0; b < m_Buffers.Length; b++)
if (m_Buffers[b].ID == id)
return m_Buffers[b];
return null;
}
public List<DebugMessage> DebugMessages = new List<DebugMessage>();
public int UnreadMessageCount = 0;
public void AddMessages(DebugMessage[] msgs)
{
UnreadMessageCount += msgs.Length;
foreach(var msg in msgs)
DebugMessages.Add(msg);
}
// the RenderManager can be used when you want to perform an operation, it will let you Invoke or
// BeginInvoke onto the thread that's used to access the renderdoc project.
public RenderManager Renderer { get { return m_Renderer; } }
public Form AppWindow { get { return m_MainWindow; } }
#endregion
#region Pipeline State
// direct access (note that only one of these will be valid for a log, check APIProps.pipelineType)
public D3D11PipelineState CurD3D11PipelineState { get { return m_D3D11PipelineState; } }
public D3D12PipelineState CurD3D12PipelineState { get { return m_D3D12PipelineState; } }
public GLPipelineState CurGLPipelineState { get { return m_GLPipelineState; } }
public VulkanPipelineState CurVulkanPipelineState { get { return m_VulkanPipelineState; } }
public CommonPipelineState CurPipelineState { get { return m_PipelineState; } }
#endregion
#region Init and Shutdown
public Core(string paramFilename, string remoteHost, uint remoteIdent, bool temp, PersistantConfig config)
{
if (!Directory.Exists(ConfigDirectory))
Directory.CreateDirectory(ConfigDirectory);
m_Config = config;
m_MainWindow = new MainWindow(this, paramFilename, remoteHost, remoteIdent, temp);
}
public void Shutdown()
{
if (m_Renderer != null)
m_Renderer.CloseThreadSync();
}
#endregion
#region Log Loading & Capture
private bool m_LogLoadingInProgress = false;
private bool LogLoadCallback()
{
return !m_LogLoadingInProgress;
}
// used to determine if two drawcalls can be considered in the same 'pass',
// ie. writing to similar targets, same type of call, etc.
//
// When a log has no markers, this is used to group up drawcalls into fake markers
private bool PassEquivalent(FetchDrawcall a, FetchDrawcall b)
{
// executing command lists can have children
if(a.children.Length > 0 || b.children.Length > 0)
return false;
// don't group draws and compute executes
if ((a.flags & DrawcallFlags.Dispatch) != (b.flags & DrawcallFlags.Dispatch))
return false;
// don't group present with anything
if ((a.flags & DrawcallFlags.Present) != (b.flags & DrawcallFlags.Present))
return false;
// don't group things with different depth outputs
if (a.depthOut != b.depthOut)
return false;
int numAOuts = 0, numBOuts = 0;
for (int i = 0; i < 8; i++)
{
if (a.outputs[i] != ResourceId.Null) numAOuts++;
if (b.outputs[i] != ResourceId.Null) numBOuts++;
}
int numSame = 0;
if (a.depthOut != ResourceId.Null)
{
numAOuts++;
numBOuts++;
numSame++;
}
for (int i = 0; i < 8; i++)
{
if (a.outputs[i] != ResourceId.Null)
{
for (int j = 0; j < 8; j++)
{
if (a.outputs[i] == b.outputs[j])
{
numSame++;
break;
}
}
}
else if (b.outputs[i] != ResourceId.Null)
{
for (int j = 0; j < 8; j++)
{
if (a.outputs[j] == b.outputs[i])
{
numSame++;
break;
}
}
}
}
// use a kind of heuristic to group together passes where the outputs are similar enough.
// could be useful for example if you're rendering to a gbuffer and sometimes you render
// without one target, but the draws are still batched up.
if (numSame > Math.Max(numAOuts, numBOuts) / 2 && Math.Max(numAOuts, numBOuts) > 1)
return true;
if (numSame == Math.Max(numAOuts, numBOuts))
return true;
return false;
}
private bool ContainsMarker(FetchDrawcall[] draws)
{
bool ret = false;
foreach (var d in draws)
{
ret |= (d.flags & DrawcallFlags.PushMarker) > 0 && (d.flags & DrawcallFlags.CmdList) == 0 && d.children.Length > 0;
ret |= ContainsMarker(d.children);
}
return ret;
}
// if a log doesn't contain any markers specified at all by the user, then we can
// fake some up by determining batches of draws that are similar and giving them a
// pass number
private FetchDrawcall[] FakeProfileMarkers(FetchDrawcall[] draws)
{
if (ContainsMarker(draws))
return draws;
var ret = new List<FetchDrawcall>();
int depthpassID = 1;
int computepassID = 1;
int passID = 1;
int start = 0;
int refdraw = 0;
for (int i = 1; i < draws.Length; i++)
{
if ((draws[refdraw].flags & (DrawcallFlags.Copy | DrawcallFlags.Resolve | DrawcallFlags.SetMarker | DrawcallFlags.CmdList)) > 0)
{
refdraw = i;
continue;
}
if ((draws[i].flags & (DrawcallFlags.Copy | DrawcallFlags.Resolve | DrawcallFlags.SetMarker | DrawcallFlags.CmdList)) > 0)
continue;
if (PassEquivalent(draws[i], draws[refdraw]))
continue;
int end = i-1;
if (end - start < 2 ||
draws[i].children.Length > 0 || draws[refdraw].children.Length > 0)
{
for (int j = start; j <= end; j++)
ret.Add(draws[j]);
start = i;
refdraw = i;
continue;
}
int minOutCount = 100;
int maxOutCount = 0;
for (int j = start; j <= end; j++)
{
int outCount = 0;
foreach (var o in draws[j].outputs)
if (o != ResourceId.Null)
outCount++;
minOutCount = Math.Min(minOutCount, outCount);
maxOutCount = Math.Max(maxOutCount, outCount);
}
FetchDrawcall mark = new FetchDrawcall();
mark.eventID = draws[start].eventID;
mark.drawcallID = draws[start].drawcallID;
mark.markerColour = new float[] { 0.0f, 0.0f, 0.0f, 0.0f };
mark.flags = DrawcallFlags.PushMarker;
mark.outputs = draws[end].outputs;
mark.depthOut = draws[end].depthOut;
mark.name = "Guessed Pass";
minOutCount = Math.Max(1, minOutCount);
if ((draws[refdraw].flags & DrawcallFlags.Dispatch) != 0)
mark.name = String.Format("Compute Pass #{0}", computepassID++);
else if (maxOutCount == 0)
mark.name = String.Format("Depth-only Pass #{0}", depthpassID++);
else if (minOutCount == maxOutCount)
mark.name = String.Format("Colour Pass #{0} ({1} Targets{2})", passID++, minOutCount, draws[end].depthOut == ResourceId.Null ? "" : " + Depth");
else
mark.name = String.Format("Colour Pass #{0} ({1}-{2} Targets{3})", passID++, minOutCount, maxOutCount, draws[end].depthOut == ResourceId.Null ? "" : " + Depth");
mark.children = new FetchDrawcall[end - start + 1];
for (int j = start; j <= end; j++)
{
mark.children[j - start] = draws[j];
draws[j].parent = mark;
}
ret.Add(mark);
start = i;
refdraw = i;
}
if (start < draws.Length)
{
for (int j = start; j < draws.Length; j++)
ret.Add(draws[j]);
}
return ret.ToArray();
}
// because some engines (*cough*unreal*cough*) provide a valid marker colour of
// opaque black for every marker, instead of transparent black (i.e. just 0) we
// want to check for that case and remove the colors, instead of displaying all
// the markers as black which is not what's intended.
//
// Valid marker colors = has at least one color somewhere that isn't (0.0, 0.0, 0.0, 1.0)
// or (0.0, 0.0, 0.0, 0.0)
//
// This will fail if no marker colors are set anyway, but then removing them is
// harmless.
private bool HasValidMarkerColors(FetchDrawcall[] draws)
{
if (draws.Length == 0)
return false;
foreach (var d in draws)
{
if (d.markerColour[0] != 0.0f ||
d.markerColour[1] != 0.0f ||
d.markerColour[2] != 0.0f ||
(d.markerColour[3] != 1.0f && d.markerColour[3] != 0.0f))
{
return true;
}
if (HasValidMarkerColors(d.children))
return true;
}
return false;
}
private void RemoveMarkerColors(FetchDrawcall[] draws)
{
for (int i = 0; i < draws.Length; i++)
{
draws[i].markerColour[0] = 0.0f;
draws[i].markerColour[1] = 0.0f;
draws[i].markerColour[2] = 0.0f;
draws[i].markerColour[3] = 0.0f;
RemoveMarkerColors(draws[i].children);
}
}
// generally logFile == origFilename, but if the log was transferred remotely then origFilename
// is the log locally before being copied we can present to the user in dialogs, etc.
public void LoadLogfile(string logFile, string origFilename, bool temporary, bool local)
{
m_LogFile = origFilename;
m_LogLocal = local;
m_LogLoadingInProgress = true;
if (File.Exists(Core.ConfigFilename))
m_Config.Serialize(Core.ConfigFilename);
float postloadProgress = 0.0f;
bool progressThread = true;
// start a modal dialog to prevent the user interacting with the form while the log is loading.
// We'll close it down when log loading finishes (whether it succeeds or fails)
ProgressPopup modal = new ProgressPopup(LogLoadCallback, true);
Thread modalThread = Helpers.NewThread(new ThreadStart(() =>
{
modal.SetModalText(string.Format("Loading Log: {0}", origFilename));
AppWindow.BeginInvoke(new Action(() =>
{
modal.ShowDialog(AppWindow);
}));
}));
modalThread.Start();
// this thread continually ticks and notifies any threads of the progress, through a float
// that is updated by the main loading code
Thread thread = Helpers.NewThread(new ThreadStart(() =>
{
modal.LogfileProgressBegin();
foreach (var p in m_ProgressListeners)
p.LogfileProgressBegin();
while (progressThread)
{
Thread.Sleep(2);
float progress = 0.8f * m_Renderer.LoadProgress + 0.19f * postloadProgress + 0.01f;
modal.LogfileProgress(progress);
foreach (var p in m_ProgressListeners)
p.LogfileProgress(progress);
}
}));
thread.Start();
// this function call will block until the log is either loaded, or there's some failure
m_Renderer.OpenCapture(logFile);
// if the renderer isn't running, we hit a failure case so display an error message
if (!m_Renderer.Running)
{
string errmsg = m_Renderer.InitException.Status.Str();
MessageBox.Show(String.Format("{0}\nFailed to open file for replay: {1}.\n\n" +
"Check diagnostic log in Help menu for more details.", origFilename, errmsg),
"Error opening log", MessageBoxButtons.OK, MessageBoxIcon.Error);
progressThread = false;
thread.Join();
m_LogLoadingInProgress = false;
modal.LogfileProgress(-1.0f);
foreach (var p in m_ProgressListeners)
p.LogfileProgress(-1.0f);
return;
}
if (!temporary)
{
m_Config.AddRecentFile(m_Config.RecentLogFiles, origFilename, 10);
if (File.Exists(Core.ConfigFilename))
m_Config.Serialize(Core.ConfigFilename);
}
m_EventID = 0;
m_FrameInfo = null;
m_APIProperties = null;
// fetch initial data like drawcalls, textures and buffers
m_Renderer.Invoke((ReplayRenderer r) =>
{
m_FrameInfo = r.GetFrameInfo();
m_APIProperties = r.GetAPIProperties();
postloadProgress = 0.2f;
m_DrawCalls = FakeProfileMarkers(r.GetDrawcalls());
bool valid = HasValidMarkerColors(m_DrawCalls);
if (!valid)
RemoveMarkerColors(m_DrawCalls);
postloadProgress = 0.4f;
m_Buffers = r.GetBuffers();
postloadProgress = 0.7f;
var texs = new List<FetchTexture>(r.GetTextures());
m_Textures = texs.OrderBy(o => o.name).ToArray();
postloadProgress = 0.9f;
m_D3D11PipelineState = r.GetD3D11PipelineState();
m_D3D12PipelineState = r.GetD3D12PipelineState();
m_GLPipelineState = r.GetGLPipelineState();
m_VulkanPipelineState = r.GetVulkanPipelineState();
m_PipelineState.SetStates(m_APIProperties, m_D3D11PipelineState, m_D3D12PipelineState, m_GLPipelineState, m_VulkanPipelineState);
UnreadMessageCount = 0;
AddMessages(m_FrameInfo.debugMessages);
postloadProgress = 1.0f;
});
Thread.Sleep(20);
DateTime today = DateTime.Now;
DateTime compare = today.AddDays(-21);
if (compare.CompareTo(Config.DegradedLog_LastUpdate) >= 0 && m_APIProperties.degraded)
{
Config.DegradedLog_LastUpdate = today;
MessageBox.Show(String.Format("{0}\nThis log opened with degraded support - " +
"this could mean missing hardware support caused a fallback to software rendering.\n\n" +
"This warning will not appear every time this happens, " +
"check debug errors/warnings window for more details.", origFilename),
"Degraded support of log", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
m_LogLoaded = true;
progressThread = false;
if (local)
{
m_LogWatcher = new FileSystemWatcher(Path.GetDirectoryName(m_LogFile), Path.GetFileName(m_LogFile));
m_LogWatcher.EnableRaisingEvents = true;
m_LogWatcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite;
m_LogWatcher.Created += new FileSystemEventHandler(OnLogfileChanged);
m_LogWatcher.Changed += new FileSystemEventHandler(OnLogfileChanged);
m_LogWatcher.SynchronizingObject = m_MainWindow; // callbacks on UI thread please
}
List<ILogViewerForm> logviewers = new List<ILogViewerForm>();
logviewers.AddRange(m_LogViewers);
// notify all the registers log viewers that a log has been loaded
foreach (var logviewer in logviewers)
{
if (logviewer == null || !(logviewer is Control)) continue;
Control c = (Control)logviewer;
if (c.InvokeRequired)
{
if (!c.IsDisposed)
{
c.Invoke(new Action(() => {
try
{
logviewer.OnLogfileLoaded();
}
catch (Exception ex)
{
throw new AccessViolationException("Rethrown from Invoke:\n" + ex.ToString());
}
}));
}
}
else if (!c.IsDisposed)
logviewer.OnLogfileLoaded();
}
m_LogLoadingInProgress = false;
modal.LogfileProgress(1.0f);
foreach (var p in m_ProgressListeners)
p.LogfileProgress(1.0f);
}
void OnLogfileChanged(object sender, FileSystemEventArgs e)
{
m_Renderer.Invoke((ReplayRenderer r) =>
{
r.FileChanged();
r.SetFrameEvent(m_EventID > 0 ? m_EventID-1 : 1, true);
});
SetEventID(null, CurEvent);
}
public void CloseLogfile()
{
if (!m_LogLoaded) return;
m_LogFile = "";
m_Renderer.CloseThreadSync();
m_APIProperties = null;
m_FrameInfo = null;
m_DrawCalls = null;
m_Buffers = null;
m_Textures = null;
m_D3D11PipelineState = null;
m_D3D12PipelineState = null;
m_GLPipelineState = null;
m_VulkanPipelineState = null;
m_PipelineState.SetStates(null, null,null, null, null);
DebugMessages.Clear();
UnreadMessageCount = 0;
m_LogLoaded = false;
if (m_LogWatcher != null)
m_LogWatcher.EnableRaisingEvents = false;
m_LogWatcher = null;
foreach (var logviewer in m_LogViewers)
{
Control c = (Control)logviewer;
if (c.InvokeRequired)
c.Invoke(new Action(() => logviewer.OnLogfileClosed()));
else
logviewer.OnLogfileClosed();
}
}
public String TempLogFilename(String appname)
{
string folder = Config.TemporaryCaptureDirectory;
try
{
if (folder.Length == 0 || !Directory.Exists(folder))
folder = Path.GetTempPath();
}
catch (ArgumentException)
{
// invalid path or similar
folder = Path.GetTempPath();
}
return Path.Combine(folder, appname + "_" + DateTime.Now.ToString(@"yyyy.MM.dd_HH.mm.ss") + ".rdc");
}
#endregion
#region Log drawcalls
public FetchDrawcall[] GetDrawcalls()
{
return m_DrawCalls;
}
private FetchDrawcall GetDrawcall(FetchDrawcall[] draws, UInt32 eventID)
{
foreach (var d in draws)
{
if (d.children != null && d.children.Length > 0)
{
var draw = GetDrawcall(d.children, eventID);
if (draw != null) return draw;
}
if (d.eventID == eventID)
return d;
}
return null;
}
public FetchDrawcall GetDrawcall(UInt32 eventID)
{
if (m_DrawCalls == null)
return null;
return GetDrawcall(m_DrawCalls, eventID);
}
#endregion
#region Viewers
// Some viewers we only allow one to exist at once, so we keep the instance here.
public EventBrowser GetEventBrowser()
{
if (m_EventBrowser == null || m_EventBrowser.IsDisposed)
{
m_EventBrowser = new EventBrowser(this);
AddLogViewer(m_EventBrowser);
}
return m_EventBrowser;
}
public TextureViewer GetTextureViewer()
{
if (m_TextureViewer == null || m_TextureViewer.IsDisposed)
{
m_TextureViewer = new TextureViewer(this);
AddLogViewer(m_TextureViewer);
}
return m_TextureViewer;
}
public BufferViewer GetMeshViewer()
{
if (m_MeshViewer == null || m_MeshViewer.IsDisposed)
{
m_MeshViewer = new BufferViewer(this, true);
AddLogViewer(m_MeshViewer);
}
return m_MeshViewer;
}
public PipelineStateViewer GetPipelineStateViewer()
{
if (m_PipelineStateViewer == null || m_PipelineStateViewer.IsDisposed)
{
m_PipelineStateViewer = new PipelineStateViewer(this);
AddLogViewer(m_PipelineStateViewer);
}
return m_PipelineStateViewer;
}
public APIInspector GetAPIInspector()
{
if (m_APIInspector == null || m_APIInspector.IsDisposed)
{
m_APIInspector = new APIInspector(this);
AddLogViewer(m_APIInspector);
}
return m_APIInspector;
}
public DebugMessages GetDebugMessages()
{
if (m_DebugMessages == null || m_DebugMessages.IsDisposed)
{
m_DebugMessages = new DebugMessages(this);
AddLogViewer(m_DebugMessages);
}
return m_DebugMessages;
}
public TimelineBar TimelineBar
{
get
{
if (m_TimelineBar == null || m_TimelineBar.IsDisposed)
return null;
return m_TimelineBar;
}
}
private CaptureDialog m_CaptureDialog = null;
public CaptureDialog CaptureDialog
{
get
{
return m_CaptureDialog == null || m_CaptureDialog.IsDisposed ? null : m_CaptureDialog;
}
set
{
if (m_CaptureDialog == null || m_CaptureDialog.IsDisposed)
m_CaptureDialog = value;
}
}
public TimelineBar GetTimelineBar()
{
if (m_TimelineBar == null || m_TimelineBar.IsDisposed)
{
m_TimelineBar = new TimelineBar(this);
AddLogViewer(m_TimelineBar);
}
return m_TimelineBar;
}
public StatisticsViewer GetStatisticsViewer()
{
if (m_StatisticsViewer == null || m_StatisticsViewer.IsDisposed)
{
m_StatisticsViewer = new StatisticsViewer(this);
AddLogViewer(m_StatisticsViewer);
}
return m_StatisticsViewer;
}
public void AddLogProgressListener(ILogLoadProgressListener p)
{
m_ProgressListeners.Add(p);
}
public void AddLogViewer(ILogViewerForm f)
{
m_LogViewers.Add(f);
if (LogLoaded)
{
f.OnLogfileLoaded();
f.OnEventSelected(CurEvent);
}
}
public void RemoveLogViewer(ILogViewerForm f)
{
m_LogViewers.Remove(f);
}
#endregion
#region Log Browsing
public void RefreshStatus()
{
SetEventID(null, m_EventID, true);
}
public void SetEventID(ILogViewerForm exclude, UInt32 eventID)
{
SetEventID(exclude, eventID, false);
}
private void SetEventID(ILogViewerForm exclude, UInt32 eventID, bool force)
{
m_EventID = eventID;
m_Renderer.Invoke((ReplayRenderer r) =>
{
r.SetFrameEvent(m_EventID, force);
m_D3D11PipelineState = r.GetD3D11PipelineState();
m_D3D12PipelineState = r.GetD3D12PipelineState();
m_GLPipelineState = r.GetGLPipelineState();
m_VulkanPipelineState = r.GetVulkanPipelineState();
m_PipelineState.SetStates(m_APIProperties, m_D3D11PipelineState, m_D3D12PipelineState, m_GLPipelineState, m_VulkanPipelineState);
});
foreach (var logviewer in m_LogViewers)
{
if(logviewer == exclude)
continue;
Control c = (Control)logviewer;
if (c.InvokeRequired)
c.Invoke(new Action(() => logviewer.OnEventSelected(eventID)));
else
logviewer.OnEventSelected(eventID);
}
}
#endregion
}
}
| 35.70247 | 182 | 0.520714 | [
"MIT"
] | kvark/renderdoc | renderdocui/Code/Core.cs | 32,311 | C# |
using Newtonsoft.Json;
namespace ProPublica.Congress
{
public class Lobbyist
{
[JsonProperty]
public string Name { get; set; }
[JsonProperty("covered_position")]
public string Position { get; set; }
}
} | 19.153846 | 44 | 0.614458 | [
"MIT"
] | mattheiler/ProPublica.Congress | ProPublica.Congress/Lobbyist.cs | 251 | C# |
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
using smiqs.Controls;
using smiqs.ViewModels.Forms;
namespace smiqs.Converters
{
/// <summary>
/// This class have methods to convert the Boolean values to color objects.
/// This is needed to validate in the Entry controls. If the validation is failed, it will return the color code of error, otherwise it will be transparent.
/// </summary>
[Preserve(AllMembers = true)]
public class ErrorValidationColorConverter : IValueConverter
{
/// <summary>
/// Identifies the simple and gradient login pages.
/// </summary>
public string PageVariantParameter { get; set; }
/// <summary>
/// This method is used to convert the bool to color.
/// </summary>
/// <param name="value">Gets the value.</param>
/// <param name="targetType">Gets the target type.</param>
/// <param name="parameter">Gets the parameter.</param>
/// <param name="culture">Gets the culture.</param>
/// <returns>Returns the color.</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// For Gradient login page
if (PageVariantParameter == "0")
{
var emailEntry = parameter as BorderlessEntry;
if (!(emailEntry?.BindingContext is LoginViewModel bindingContext))
{
return Color.Transparent;
}
var isFocused = (bool)value;
bindingContext.IsInvalidEmail = !isFocused && !CheckValidEmail(bindingContext.Email);
if (isFocused)
{
return Color.FromRgba(255, 255, 255, 0.6);
}
return bindingContext.IsInvalidEmail ? Color.FromHex("#FF4A4A") : Color.Transparent;
}
// For Simple login page
else
{
var emailEntry = parameter as BorderlessEntry;
if (!(emailEntry?.BindingContext is LoginViewModel bindingContext)) return Color.FromHex("#ced2d9");
var isFocused1 = (bool)value;
bindingContext.IsInvalidEmail = !isFocused1 && !CheckValidEmail(bindingContext.Email);
if (isFocused1)
{
return Color.FromHex("#959eac");
}
return bindingContext.IsInvalidEmail ? Color.FromHex("#FF4A4A") : Color.FromHex("#ced2d9");
}
}
/// <summary>
/// This method is used to convert the color to bool.
/// </summary>
/// <param name="value">Gets the value.</param>
/// <param name="targetType">Gets the target type.</param>
/// <param name="parameter">Gets the parameter.</param>
/// <param name="culture">Gets the culture.</param>
/// <returns>Returns the string.</returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
/// <summary>
/// Validates the email.
/// </summary>
/// <param name="email">Gets the email.</param>
/// <returns>Returns the boolean value.</returns>
private static bool CheckValidEmail(string email)
{
if (string.IsNullOrEmpty(email))
{
return true;
}
var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
return regex.IsMatch(email) && !email.EndsWith(".");
}
}
} | 36.057692 | 160 | 0.561067 | [
"MIT"
] | yehiaraslan85/SmiqsMobileApp | smiqs/smiqs/Converters/ErrorValidationColorConverter.cs | 3,752 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
public class PayAct : GameAct
{
private void Start()
{
this.Init();
base.GetComponentInChildren<CancelButton>().GameAct = this;
this.CancelButton = base.GetComponentInChildren<CancelButton>();
this.InputSlots = new List<CardSlot>();
CardSlotData cardSlotData = new CardSlotData();
cardSlotData.SlotOwnerType = CardSlotData.OwnerType.Act;
base.InitCardSlotOnActTable(this.InputTrans, new Vector3(1.3f, 0f, 0f), this.ActData.InputSlotNum, false, null, this.InputSlots, cardSlotData);
this.eventalOffset = new Vector3(0f, 6f, 0f);
this.oppositeOffset = new Vector3(0f, 0f, 2.8f);
this.during = 30;
base.StartCoroutine(this.ActStartAni(this.eventalOffset, this.oppositeOffset, this.during));
}
public override void OnActCancelButton()
{
base.OnActCancelButton();
foreach (CardSlot cardSlot in this.InputSlots)
{
if (cardSlot.ChildCard != null)
{
this.Source.CardData.Belongings.Add(cardSlot.ChildCard.CardData.Name);
}
}
}
public List<CardSlot> InputSlots;
public Transform InputTrans;
public int slotCount;
}
| 28.275 | 145 | 0.748011 | [
"Apache-2.0"
] | Shadowrabbit/BigBiaDecompilation | Source/Assembly-CSharp/PayAct.cs | 1,133 | C# |
using System;
using System.Collections.Generic;
namespace Equinox.API.Filters
{
public class ApiException : Exception
{
public int StatusCode { get; set; }
public List<ValidationError> Errors { get; set; }
public ApiException(string message, int statusCode = 500, List<ValidationError> errors = null) :
base(message)
{
StatusCode = statusCode;
Errors = errors;
}
public ApiException(Exception ex, int statusCode = 500) : base(ex.Message)
{
StatusCode = statusCode;
}
}
} | 23.96 | 104 | 0.595993 | [
"MIT"
] | duyxaoke/DEV | src/Equinox.API/Filters/ApiException.cs | 599 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace VinylStore.Catalog.Domain.Infrastructure.Repositories
{
public interface IUnitOfWork : IDisposable
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken));
Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken));
}
} | 33.5 | 103 | 0.783582 | [
"MIT"
] | samueleresca/Hands-On-RESTful-Web-Services-with-ASP.NET-Core | Chapter 10/Catalog/src/VinylStore.Catalog.Domain/Infrastructure/Repositories/IUnitOfWork.cs | 404 | C# |
using System;
using System.Collections.Generic;
using Restaurant.Objects;
namespace Restaurant
{
public class Display: Restaurant
{
public static void ShowEventList()
{
Console.Write("Lista czasów eventow :");
foreach (var Event in eventList)
{
Console.Write(Event.ExecuteTime + " ");
}
Console.WriteLine();
}
public static int ShowPplInQueue(List<Customer> customers)
{
int numberOfPpl = 0;
foreach (var unused in customers)
numberOfPpl++;
return numberOfPpl;
}
public static int ShowPplInTables()
{
int numberOfPpl = 0;
foreach (var o in tables)
{
if(o.Customer != null)
numberOfPpl++;
}
return numberOfPpl;
}
public static int ShowPplInBuffet(Buffet buffet)
{
int numberOfPpl = 0;
foreach (var o in buffet.ListOfCustomers)
{
if (o != null)
numberOfPpl += o.NumberOfPeople;
}
return numberOfPpl;
}
public static int ShowPplInCashiers()
{
int numberOfPpl = 0;
foreach (var o in cashiers)
{
if (o.Customer != null)
numberOfPpl++;
}
return numberOfPpl;
}
}
}
| 25.59322 | 66 | 0.474834 | [
"MIT"
] | kuba5522/Computer-simulation | Restauracja/Display.cs | 1,513 | C# |
//-----------------------------------------------------------------------
// <copyright file="DefaultMathContext.cs" company="Sphere 10 Software">
//
// Copyright (c) Sphere 10 Software. All rights reserved. (http://www.sphere10.com)
//
// Distributed under the MIT software license, see the accompanying file
// LICENSE or visit http://www.opensource.org/licenses/mit-license.php.
//
// <author>Herman Schoenfeld</author>
// <date>2018</date>
// </copyright>
//-----------------------------------------------------------------------
#if !__MOBILE__
using System;
using System.Collections.Generic;
using System.Text;
namespace Sphere10.Framework.Maths.Compiler {
public class DefaultMathContext : IMathContext {
private IMathContext _parentContext;
private IVariableContext _variableContext;
private IFunctionContext _functionContext;
public DefaultMathContext() {
_parentContext = null;
_variableContext = new DefaultVariableContext(this);
_functionContext = new DefaultFunctionContext(this);
}
public IMathContext ParentContext {
get {
return _parentContext;
}
set {
_parentContext = value;
}
}
public IVariableContext Variables {
get {
return _variableContext;
}
}
public IFunctionContext Functions {
get {
return _functionContext;
}
}
public IFunction GenerateFunction(string expression) {
return GenerateFunction(expression, "x");
}
public IFunction GenerateFunction(string expression, string parameterName)
{
BasicFunctionGenerator functionGenerator = new BasicFunctionGenerator(this);
functionGenerator.FunctionParameterName = parameterName;
return functionGenerator.GenerateFunctionFromExpression(expression);
}
}
}
#endif
| 29.735294 | 88 | 0.589021 | [
"MIT"
] | Sphere10/Framework | src/Sphere10.Framework.DotNet/MathRuntime/Runtime/DefaultMathContext.cs | 2,022 | C# |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace org.camunda.bpm.engine.spring.test.servicetask
{
using ProcessInstance = org.camunda.bpm.engine.runtime.ProcessInstance;
using Deployment = org.camunda.bpm.engine.test.Deployment;
using ContextConfiguration = org.springframework.test.context.ContextConfiguration;
/// <summary>
/// @author Joram Barrez
/// </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ContextConfiguration("classpath:org/camunda/bpm/engine/spring/test/servicetask/servicetaskSpringTest-context.xml") public class ServiceTaskSpringDelegationTest extends org.camunda.bpm.engine.spring.test.SpringProcessEngineTestCase
public class ServiceTaskSpringDelegationTest : SpringProcessEngineTestCase
{
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Deployment public void testDelegateExpression()
public virtual void testDelegateExpression()
{
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateExpressionToSpringBean");
assertEquals("Activiti BPMN 2.0 process engine", runtimeService.getVariable(procInst.Id, "myVar"));
assertEquals("fieldInjectionWorking", runtimeService.getVariable(procInst.Id, "fieldInjection"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Deployment public void testDelegateClass()
public virtual void testDelegateClass()
{
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateClassToSpringBean");
assertEquals("Activiti BPMN 2.0 process engine", runtimeService.getVariable(procInst.Id, "myVar"));
assertEquals("fieldInjectionWorking", runtimeService.getVariable(procInst.Id, "fieldInjection"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Deployment public void testDelegateClassNotABean()
public virtual void testDelegateClassNotABean()
{
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateClassToSpringBean");
assertEquals("DelegateClassNotABean was called", runtimeService.getVariable(procInst.Id, "message"));
assertTrue((bool?)runtimeService.getVariable(procInst.Id, "injectedFieldIsNull"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Deployment public void testMethodExpressionOnSpringBean()
public virtual void testMethodExpressionOnSpringBean()
{
ProcessInstance procInst = runtimeService.startProcessInstanceByKey("methodExpressionOnSpringBean");
assertEquals("ACTIVITI BPMN 2.0 PROCESS ENGINE", runtimeService.getVariable(procInst.Id, "myVar"));
}
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Deployment public void testExecutionAndTaskListenerDelegationExpression()
public virtual void testExecutionAndTaskListenerDelegationExpression()
{
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("executionAndTaskListenerDelegation");
assertEquals("working", runtimeService.getVariable(processInstance.Id, "executionListenerVar"));
assertEquals("working", runtimeService.getVariable(processInstance.Id, "taskListenerVar"));
assertEquals("executionListenerInjection", runtimeService.getVariable(processInstance.Id, "executionListenerField"));
assertEquals("taskListenerInjection", runtimeService.getVariable(processInstance.Id, "taskListenerField"));
}
}
} | 55.5125 | 248 | 0.802297 | [
"Apache-2.0"
] | luizfbicalho/Camunda.NET | camunda-bpm-platform-net/engine-spring/core/src/test/java/org/camunda/bpm/engine/spring/test/servicetask/ServiceTaskSpringDelegationTest.cs | 4,443 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the identitystore-2020-06-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.IdentityStore.Model;
using Amazon.IdentityStore.Model.Internal.MarshallTransformations;
using Amazon.IdentityStore.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.IdentityStore
{
/// <summary>
/// Implementation for accessing IdentityStore
///
///
/// </summary>
public partial class AmazonIdentityStoreClient : AmazonServiceClient, IAmazonIdentityStore
{
private static IServiceMetadata serviceMetadata = new AmazonIdentityStoreMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonIdentityStoreClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonIdentityStoreClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonIdentityStoreConfig()) { }
/// <summary>
/// Constructs AmazonIdentityStoreClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonIdentityStoreClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonIdentityStoreConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonIdentityStoreClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonIdentityStoreClient Configuration Object</param>
public AmazonIdentityStoreClient(AmazonIdentityStoreConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonIdentityStoreClient(AWSCredentials credentials)
: this(credentials, new AmazonIdentityStoreConfig())
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonIdentityStoreClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonIdentityStoreConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Credentials and an
/// AmazonIdentityStoreClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonIdentityStoreClient Configuration Object</param>
public AmazonIdentityStoreClient(AWSCredentials credentials, AmazonIdentityStoreConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonIdentityStoreClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonIdentityStoreConfig())
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonIdentityStoreClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonIdentityStoreConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonIdentityStoreClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonIdentityStoreClient Configuration Object</param>
public AmazonIdentityStoreClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonIdentityStoreConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonIdentityStoreClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIdentityStoreConfig())
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonIdentityStoreClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIdentityStoreConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonIdentityStoreClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonIdentityStoreClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonIdentityStoreClient Configuration Object</param>
public AmazonIdentityStoreClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonIdentityStoreConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region DescribeGroup
/// <summary>
/// Retrieves the group metadata and attributes from <code>GroupId</code> in an identity
/// store.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeGroup service method.</param>
///
/// <returns>The response from the DescribeGroup service method, as returned by IdentityStore.</returns>
/// <exception cref="Amazon.IdentityStore.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.InternalServerException">
/// The request processing has failed because of an unknown error, exception or failure
/// with an internal server.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ResourceNotFoundException">
/// Indicates that a requested resource is not found.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ThrottlingException">
/// Indicates that the principal has crossed the throttling limits of the API operations.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ValidationException">
/// The request failed because it contains a syntax error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/DescribeGroup">REST API Reference for DescribeGroup Operation</seealso>
public virtual DescribeGroupResponse DescribeGroup(DescribeGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeGroupResponseUnmarshaller.Instance;
return Invoke<DescribeGroupResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeGroup operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeGroup operation on AmazonIdentityStoreClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeGroup
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/DescribeGroup">REST API Reference for DescribeGroup Operation</seealso>
public virtual IAsyncResult BeginDescribeGroup(DescribeGroupRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeGroupResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeGroup operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeGroup.</param>
///
/// <returns>Returns a DescribeGroupResult from IdentityStore.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/DescribeGroup">REST API Reference for DescribeGroup Operation</seealso>
public virtual DescribeGroupResponse EndDescribeGroup(IAsyncResult asyncResult)
{
return EndInvoke<DescribeGroupResponse>(asyncResult);
}
#endregion
#region DescribeUser
/// <summary>
/// Retrieves the user metadata and attributes from <code>UserId</code> in an identity
/// store.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeUser service method.</param>
///
/// <returns>The response from the DescribeUser service method, as returned by IdentityStore.</returns>
/// <exception cref="Amazon.IdentityStore.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.InternalServerException">
/// The request processing has failed because of an unknown error, exception or failure
/// with an internal server.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ResourceNotFoundException">
/// Indicates that a requested resource is not found.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ThrottlingException">
/// Indicates that the principal has crossed the throttling limits of the API operations.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ValidationException">
/// The request failed because it contains a syntax error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
public virtual DescribeUserResponse DescribeUser(DescribeUserRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeUserResponseUnmarshaller.Instance;
return Invoke<DescribeUserResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeUser operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeUser operation on AmazonIdentityStoreClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeUser
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
public virtual IAsyncResult BeginDescribeUser(DescribeUserRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeUserRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeUserResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeUser operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeUser.</param>
///
/// <returns>Returns a DescribeUserResult from IdentityStore.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
public virtual DescribeUserResponse EndDescribeUser(IAsyncResult asyncResult)
{
return EndInvoke<DescribeUserResponse>(asyncResult);
}
#endregion
#region ListGroups
/// <summary>
/// Lists the attribute name and value of the group that you specified in the search.
/// We only support <code>DisplayName</code> as a valid filter attribute path currently,
/// and filter is required. This API returns minimum attributes, including <code>GroupId</code>
/// and group <code>DisplayName</code> in the response.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListGroups service method.</param>
///
/// <returns>The response from the ListGroups service method, as returned by IdentityStore.</returns>
/// <exception cref="Amazon.IdentityStore.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.InternalServerException">
/// The request processing has failed because of an unknown error, exception or failure
/// with an internal server.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ResourceNotFoundException">
/// Indicates that a requested resource is not found.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ThrottlingException">
/// Indicates that the principal has crossed the throttling limits of the API operations.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ValidationException">
/// The request failed because it contains a syntax error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/ListGroups">REST API Reference for ListGroups Operation</seealso>
public virtual ListGroupsResponse ListGroups(ListGroupsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListGroupsResponseUnmarshaller.Instance;
return Invoke<ListGroupsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListGroups operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListGroups operation on AmazonIdentityStoreClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListGroups
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/ListGroups">REST API Reference for ListGroups Operation</seealso>
public virtual IAsyncResult BeginListGroups(ListGroupsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListGroupsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListGroups operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListGroups.</param>
///
/// <returns>Returns a ListGroupsResult from IdentityStore.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/ListGroups">REST API Reference for ListGroups Operation</seealso>
public virtual ListGroupsResponse EndListGroups(IAsyncResult asyncResult)
{
return EndInvoke<ListGroupsResponse>(asyncResult);
}
#endregion
#region ListUsers
/// <summary>
/// Lists the attribute name and value of the user that you specified in the search. We
/// only support <code>UserName</code> as a valid filter attribute path currently, and
/// filter is required. This API returns minimum attributes, including <code>UserId</code>
/// and <code>UserName</code> in the response.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListUsers service method.</param>
///
/// <returns>The response from the ListUsers service method, as returned by IdentityStore.</returns>
/// <exception cref="Amazon.IdentityStore.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.InternalServerException">
/// The request processing has failed because of an unknown error, exception or failure
/// with an internal server.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ResourceNotFoundException">
/// Indicates that a requested resource is not found.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ThrottlingException">
/// Indicates that the principal has crossed the throttling limits of the API operations.
/// </exception>
/// <exception cref="Amazon.IdentityStore.Model.ValidationException">
/// The request failed because it contains a syntax error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/ListUsers">REST API Reference for ListUsers Operation</seealso>
public virtual ListUsersResponse ListUsers(ListUsersRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListUsersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListUsersResponseUnmarshaller.Instance;
return Invoke<ListUsersResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListUsers operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListUsers operation on AmazonIdentityStoreClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListUsers
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/ListUsers">REST API Reference for ListUsers Operation</seealso>
public virtual IAsyncResult BeginListUsers(ListUsersRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListUsersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListUsersResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListUsers operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListUsers.</param>
///
/// <returns>Returns a ListUsersResult from IdentityStore.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/identitystore-2020-06-15/ListUsers">REST API Reference for ListUsers Operation</seealso>
public virtual ListUsersResponse EndListUsers(IAsyncResult asyncResult)
{
return EndInvoke<ListUsersResponse>(asyncResult);
}
#endregion
}
} | 50.056818 | 162 | 0.659554 | [
"Apache-2.0"
] | sudoudaisuke/aws-sdk-net | sdk/src/Services/IdentityStore/Generated/_bcl35/AmazonIdentityStoreClient.cs | 26,430 | 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.
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System.Globalization;
using Xunit;
using System.Text.Json.Serialization;
namespace System.Text.Json.Tests
{
public class DateTimeConverterTests
{
internal static string GetUtcOffsetText(DateTime d)
{
TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(d);
return utcOffset.Hours.ToString("+00;-00", CultureInfo.InvariantCulture) + ":" + utcOffset.Minutes.ToString("00;00", CultureInfo.InvariantCulture);
}
[Fact]
public void SerializeDateTime()
{
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc);
string result;
result = JsonSerializer.Serialize(d);
Assert.Equal(@"""2000-12-15T22:11:03.055Z""", result);
Assert.Equal(d, JsonSerializer.Deserialize<DateTime>(result));
d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Local);
result = JsonSerializer.Serialize(d);
Assert.Equal(@"""2000-12-15T22:11:03.055" + GetUtcOffsetText(d) + @"""", result);
}
[Fact]
public void SerializeDateTimeOffset()
{
DateTimeOffset d = new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero);
string result;
result = JsonSerializer.Serialize(d);
Assert.Equal(@"""2000-12-15T22:11:03.055+00:00""", result);
Assert.Equal(d, JsonSerializer.Deserialize<DateTimeOffset>(result));
}
[Fact]
public void DeserializeDateTimeOffset()
{
// Intentionally use an offset that is unlikely in the real world,
// so the test will be accurate regardless of the local time zone setting.
TimeSpan offset = new TimeSpan(2, 15, 0);
DateTimeOffset dto = new DateTimeOffset(2014, 1, 1, 0, 0, 0, 0, offset);
DateTimeOffset test = JsonSerializer.Deserialize<DateTimeOffset>("\"2014-01-01T00:00:00+02:15\"");
Assert.Equal(dto, test);
Assert.Equal(dto.ToString("o"), test.ToString("o"));
}
[Fact]
public void NullableSerializeUTC()
{
NullableDateTimeTestClass c = new NullableDateTimeTestClass();
c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonSerializer.Serialize(c);
NullableDateTimeTestClass newOne = JsonSerializer.Deserialize<NullableDateTimeTestClass>(json);
Assert.Equal(newOne.DateTimeField, c.DateTimeField);
Assert.Equal(newOne.DateTimeOffsetField, c.DateTimeOffsetField);
Assert.Equal(newOne.PostField, c.PostField);
Assert.Equal(newOne.PreField, c.PreField);
c.DateTimeField = null;
c.DateTimeOffsetField = null;
c.PreField = "Pre";
c.PostField = "Post";
json = JsonSerializer.Serialize(c);
Assert.Equal(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", json);
}
[Fact]
public void SerializeUTC()
{
DateTimeTestClass c = new DateTimeTestClass();
c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonSerializer.Serialize(c);
NullableDateTimeTestClass newOne = JsonSerializer.Deserialize<NullableDateTimeTestClass>(json);
Assert.Equal(newOne.DateTimeField, c.DateTimeField);
Assert.Equal(newOne.DateTimeOffsetField, c.DateTimeOffsetField);
Assert.Equal(newOne.PostField, c.PostField);
Assert.Equal(newOne.PreField, c.PreField);
//test the other edge case too (start of a year)
c.DateTimeField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
json = JsonSerializer.Serialize(c);
newOne = JsonSerializer.Deserialize<NullableDateTimeTestClass>(json);
Assert.Equal(newOne.DateTimeField, c.DateTimeField);
Assert.Equal(newOne.DateTimeOffsetField, c.DateTimeOffsetField);
Assert.Equal(newOne.PostField, c.PostField);
Assert.Equal(newOne.PreField, c.PreField);
}
[Fact]
public void BlogCodeSample()
{
Person p = new Person
{
Name = "Keith",
BirthDate = new DateTime(1980, 3, 8),
LastModified = new DateTime(2009, 4, 12, 20, 44, 55),
};
string jsonText = JsonSerializer.Serialize(p, new JsonSerializerOptions { IgnoreNullValues = true});
Assert.Equal(@"{""Name"":""Keith"",""BirthDate"":""1980-03-08T00:00:00"",""LastModified"":""2009-04-12T20:44:55""}", jsonText);
}
}
internal class DateTimeTestClass
{
public string PreField { get; set; }
public DateTime DateTimeField { get; set; }
public DateTimeOffset DateTimeOffsetField { get; set; }
public string PostField { get; set; }
}
internal class NullableDateTimeTestClass
{
public string PreField { get; set; }
public DateTime? DateTimeField { get; set; }
public DateTimeOffset? DateTimeOffsetField { get; set; }
public string PostField { get; set; }
}
}
| 41.797688 | 159 | 0.630342 | [
"MIT"
] | AntonLandor/corefx | src/System.Text.Json/tests/NewtonsoftTests/DateTimeConverterTests.cs | 7,231 | C# |
namespace OutputFileCSVPlugin
{
partial class SettingsForm_OutputFileCSV
{
/// <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(SettingsForm_OutputFileCSV));
this.SetFileButton = new System.Windows.Forms.Button();
this.SelectedFileTextbox = new System.Windows.Forms.TextBox();
this.EncodingDropdown = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.OKButton = new System.Windows.Forms.Button();
this.CSVQuoteTextbox = new System.Windows.Forms.TextBox();
this.CSVDelimiterTextbox = new System.Windows.Forms.TextBox();
this.label42 = new System.Windows.Forms.Label();
this.label41 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// SetFileButton
//
this.SetFileButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.SetFileButton.Location = new System.Drawing.Point(12, 159);
this.SetFileButton.Name = "SetFileButton";
this.SetFileButton.Size = new System.Drawing.Size(118, 40);
this.SetFileButton.TabIndex = 0;
this.SetFileButton.Text = "Choose File";
this.SetFileButton.UseVisualStyleBackColor = true;
this.SetFileButton.Click += new System.EventHandler(this.SetFolderButton_Click);
//
// SelectedFileTextbox
//
this.SelectedFileTextbox.Enabled = false;
this.SelectedFileTextbox.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.SelectedFileTextbox.Location = new System.Drawing.Point(12, 130);
this.SelectedFileTextbox.MaxLength = 2147483647;
this.SelectedFileTextbox.Name = "SelectedFileTextbox";
this.SelectedFileTextbox.Size = new System.Drawing.Size(606, 23);
this.SelectedFileTextbox.TabIndex = 1;
//
// EncodingDropdown
//
this.EncodingDropdown.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.EncodingDropdown.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.EncodingDropdown.FormattingEnabled = true;
this.EncodingDropdown.Location = new System.Drawing.Point(12, 50);
this.EncodingDropdown.Name = "EncodingDropdown";
this.EncodingDropdown.Size = new System.Drawing.Size(268, 23);
this.EncodingDropdown.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(12, 111);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(128, 16);
this.label1.TabIndex = 3;
this.label1.Text = "Select Output File";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(12, 31);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(173, 16);
this.label2.TabIndex = 4;
this.label2.Text = "Select CSV File Encoding";
//
// OKButton
//
this.OKButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.OKButton.Location = new System.Drawing.Point(260, 340);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(118, 40);
this.OKButton.TabIndex = 6;
this.OKButton.Text = "OK";
this.OKButton.UseVisualStyleBackColor = true;
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// CSVQuoteTextbox
//
this.CSVQuoteTextbox.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.CSVQuoteTextbox.Location = new System.Drawing.Point(137, 262);
this.CSVQuoteTextbox.MaxLength = 1;
this.CSVQuoteTextbox.Name = "CSVQuoteTextbox";
this.CSVQuoteTextbox.Size = new System.Drawing.Size(101, 23);
this.CSVQuoteTextbox.TabIndex = 22;
this.CSVQuoteTextbox.Text = "\"";
this.CSVQuoteTextbox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// CSVDelimiterTextbox
//
this.CSVDelimiterTextbox.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.CSVDelimiterTextbox.Location = new System.Drawing.Point(15, 261);
this.CSVDelimiterTextbox.MaxLength = 1;
this.CSVDelimiterTextbox.Name = "CSVDelimiterTextbox";
this.CSVDelimiterTextbox.Size = new System.Drawing.Size(101, 23);
this.CSVDelimiterTextbox.TabIndex = 21;
this.CSVDelimiterTextbox.Text = ",";
this.CSVDelimiterTextbox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label42
//
this.label42.AutoSize = true;
this.label42.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label42.Location = new System.Drawing.Point(134, 243);
this.label42.Name = "label42";
this.label42.Size = new System.Drawing.Size(86, 16);
this.label42.TabIndex = 20;
this.label42.Text = "CSV Quote:";
//
// label41
//
this.label41.AutoSize = true;
this.label41.Font = new System.Drawing.Font("MS Reference Sans Serif", 9.75F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label41.Location = new System.Drawing.Point(14, 243);
this.label41.Name = "label41";
this.label41.Size = new System.Drawing.Size(102, 16);
this.label41.TabIndex = 19;
this.label41.Text = "CSV Delimiter:";
//
// SettingsForm_OutputFileCSV
//
this.AcceptButton = this.OKButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(638, 407);
this.Controls.Add(this.CSVQuoteTextbox);
this.Controls.Add(this.CSVDelimiterTextbox);
this.Controls.Add(this.label42);
this.Controls.Add(this.label41);
this.Controls.Add(this.OKButton);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.EncodingDropdown);
this.Controls.Add(this.SelectedFileTextbox);
this.Controls.Add(this.SetFileButton);
this.DoubleBuffered = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SettingsForm_OutputFileCSV";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Plugin Name";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button SetFileButton;
private System.Windows.Forms.TextBox SelectedFileTextbox;
private System.Windows.Forms.ComboBox EncodingDropdown;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button OKButton;
private System.Windows.Forms.TextBox CSVQuoteTextbox;
private System.Windows.Forms.TextBox CSVDelimiterTextbox;
private System.Windows.Forms.Label label42;
private System.Windows.Forms.Label label41;
}
} | 52.347594 | 175 | 0.61753 | [
"MIT"
] | BUTTER-Tools/OutputFileCSV | SettingsForm_OutputFileCSV.Designer.cs | 9,791 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NationalInstruments.Vision;
using NationalInstruments.Vision.Analysis;
using System.Collections.ObjectModel;
// Blob Analysis example
//
// This example performs a series of grayscale filtering, threshold, binary morphology,
// and blob analysis operations and measures the areas of all large circular particles
// in the image.
namespace BlobAnalysis
{
public partial class Form1 : Form
{
private int currentStep;
public Form1()
{
InitializeComponent();
}
private void resetButton_Click(object sender, EventArgs e)
{
ResetExample();
}
private void ResetExample()
{
// Clear the image from the viewer.
imageViewer1.Image.SetSize(0, 0);
// Start over with the first step
currentStep = 0;
steps.SelectedIndex = 0;
}
private void steps_SelectedIndexChanged(object sender, EventArgs e)
{
// Do not allow the user to change the step selected in the listbox
steps.SelectedIndex = currentStep;
}
private void runCurrentStepButton_Click(object sender, EventArgs e)
{
// Call the appropriate routine based on the current step.
switch (currentStep)
{
case 0:
LoadSampleImage();
break;
case 1:
EnhanceEdgeInformation();
break;
case 2:
Threshold();
break;
case 3:
FillHolesInObjects();
break;
case 4:
RemoveObjectsTouchingTheBorder();
break;
case 5:
KeepRoundObjects();
break;
case 6:
MeasureObjectsAreas();
break;
}
// Advance to the next step
currentStep++;
if (currentStep > 6)
{
currentStep = 0;
}
// Update the listbox.
steps.SelectedIndex = currentStep;
}
private void LoadSampleImage()
{
// Read the image and set the viewer's palette to Gray to display it properly
imageViewer1.Image.ReadFile(System.IO.Path.Combine(ExampleImagesFolder.GetExampleImagesFolder(), "metal.jpg"));
imageViewer1.Palette.Type = NationalInstruments.Vision.WindowsForms.PaletteType.Gray;
}
private void EnhanceEdgeInformation()
{
// Use convolution to sharpen the edges.
Algorithms.Convolute(imageViewer1.Image, imageViewer1.Image, new Kernel(KernelFamily.Laplacian, 3, 5));
}
private void Threshold()
{
// Threshold the image and change the viewer's palette to Binary so the foreground of
// the image is visible.
Algorithms.Threshold(imageViewer1.Image, imageViewer1.Image, new Range(150, 255));
imageViewer1.Palette.Type = NationalInstruments.Vision.WindowsForms.PaletteType.Binary;
}
private void FillHolesInObjects()
{
// Fill holes in particles
Algorithms.FillHoles(imageViewer1.Image, imageViewer1.Image);
}
private void RemoveObjectsTouchingTheBorder()
{
// Remove particles touching the border
Algorithms.RejectBorder(imageViewer1.Image, imageViewer1.Image);
}
private void KeepRoundObjects()
{
// Filter out all very small particles
Algorithms.RemoveParticle(imageViewer1.Image, imageViewer1.Image, 1);
// Filter out non-circular particles
Collection<ParticleFilterCriteria> criteria = new System.Collections.ObjectModel.Collection<ParticleFilterCriteria>();
criteria.Add(new ParticleFilterCriteria(MeasurementType.HeywoodCircularityFactor, new Range(0, 1.06)));
Algorithms.ParticleFilter(imageViewer1.Image, imageViewer1.Image, criteria);
}
private void MeasureObjectsAreas()
{
// Compute the full particle report.
Collection<ParticleReport> reports = Algorithms.ParticleReport(imageViewer1.Image);
// Overlay the area of each particle.
OverlayTextOptions options = new OverlayTextOptions();
options.HorizontalAlignment = HorizontalTextAlignment.Center;
options.VerticalAlignment = VerticalTextAlignment.Bottom;
options.FontSize = 16;
foreach (ParticleReport report in reports)
{
imageViewer1.Image.Overlays.Default.AddText(String.Format("{0}", report.Area), new PointContour(report.CenterOfMass.X, report.BoundingRect.Top), Rgb32Value.GreenColor, options);
}
}
private void Form1_Load(object sender, EventArgs e)
{
steps.SelectedIndex = 0;
}
private void exitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
} | 34.557692 | 193 | 0.589872 | [
"MIT"
] | ni/vdm-dotnet | examples/dotNET/2. Functions/Binary Analysis/Blob Analysis/cs/Form1.cs | 5,391 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Configuration.Environment
{
using System;
using System.Collections.Generic;
[AttributeUsage( AttributeTargets.Class |
AttributeTargets.Field )]
public sealed class DisplayNameAttribute : Attribute
{
//
// State
//
public string Value;
//
// Constructor Methods
//
public DisplayNameAttribute( string value )
{
this.Value = value;
}
}
}
| 19.516129 | 64 | 0.540496 | [
"MIT"
] | NETMF/llilum | Zelig/Zelig/RunTime/Zelig/Common/Configuration/Attributes/DisplayNameAttribute.cs | 605 | C# |
namespace Aviant.Application.Commands;
using MediatR;
public interface ICommand<out TResponse> : IRequest<TResponse>
{ }
public interface ICommand : ICommand<Unit>
{ }
| 17.1 | 62 | 0.777778 | [
"MIT"
] | panosru/Aviant | src/Kernel/Application/Commands/ICommand.cs | 171 | 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("HtDaqViewer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("PetroMar")]
[assembly: AssemblyProduct("HtDaqViewer")]
[assembly: AssemblyCopyright("")]
[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("e36de6fb-52e8-4dc0-b800-5d8b5787da42")]
// 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.459459 | 84 | 0.746032 | [
"MIT"
] | JWatsonADI/hightemp | ht_daq_viewer/Properties/AssemblyInfo.cs | 1,388 | C# |
using System;
using Microsoft.AspNetCore.Hosting;
namespace Dbosoft.Hosuto.Modules.Hosting
{
internal class DelegateWebModuleWebHostBuilderFilter : IWebModuleWebHostBuilderFilter
{
private readonly Action<IWebModule, IWebHostBuilder> _configureDelegate;
public DelegateWebModuleWebHostBuilderFilter(Action<IWebModule, IWebHostBuilder> configureDelegate)
{
_configureDelegate = configureDelegate;
}
public Action<IWebModule, IWebHostBuilder> Invoke(Action<IWebModule, IWebHostBuilder> next)
{
return (webModule, builder) =>
{
_configureDelegate(webModule, builder);
next(webModule, builder);
};
}
}
} | 31.291667 | 107 | 0.668442 | [
"MIT"
] | dbosoft/Hosuto | src/Hosuto.Hosting.AspNetCore/Modules/Hosting/DelegateWebModuleWebHostBuilderFilter.cs | 753 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using MixedRealityExtension.App;
using MixedRealityExtension.IPC;
// TODO: Objects should not be visible until synchronization is complete.
namespace MixedRealityExtension.Messaging.Protocols
{
internal class Idle : Protocol
{
internal Idle(MixedRealityExtensionApp app)
: base(app)
{ }
protected override void InternalStart()
{
}
protected override void InternalComplete()
{
}
protected override void InternalReceive(Message message)
{
}
}
}
| 19.793103 | 73 | 0.749129 | [
"MIT"
] | Djmondoent/mixed-reality-extension-unity | MREUnityRuntimeLib/Messaging/Protocols/Idle.cs | 574 | C# |
// ***********************************************************************
// Assembly : Invisionware.Settings
// Author : Shawn Anderson (sanderson@eye-catcher.com)
// Created : 04-09-2017
//
// Last Modified By : Shawn Anderson (sanderson@eye-catcher.com)
// Last Modified On : 04-09-2017
// ***********************************************************************
// <copyright file="ISettingsOverride.cs" company="Invisionware">
// Copyright (c) Invisionware. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace Invisionware.Settings
{
public interface ISettingsValueOverride : ISettingsOverride
{
T Enrich<T>(string key, T value);
}
} | 36.619048 | 75 | 0.486346 | [
"Apache-2.0"
] | Invisionware/Invisionware.Settings | src/Invisionware.Settings/Interfaces/Override/ISettingsValueOverride.cs | 771 | C# |
using System;
using System.IO;
using NAudio.Wave;
namespace Discord.Soundboard
{
public class SoundboardEffect
{
public string Name { get; set; }
public string Path { get; set; }
public TimeSpan Duration { get; set; }
public DateTime DateLastModified { get; set; }
public SoundboardEffect(string filename)
{
if (filename == null)
throw new ArgumentNullException();
this.Name = System.IO.Path.GetFileNameWithoutExtension(filename);
this.Path = filename;
try
{
if (File.Exists(filename))
{
this.DateLastModified = File.GetLastWriteTimeUtc(filename);
using (var reader = new WaveFileReader(filename))
this.Duration = reader.TotalTime;
}
}
catch (Exception)
{
this.DateLastModified = DateTime.MinValue;
this.Duration = TimeSpan.Zero;
}
}
}
}
| 25.613636 | 80 | 0.500444 | [
"Apache-2.0"
] | chutchinson/discord-soundboard | Discord.Soundboard/SoundboardEffect.cs | 1,129 | C# |
/*
* Copyright 2012-2016 The Asn1Net Project
*
* 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.
*/
/*
* Written for the Asn1Net project by:
* Peter Polacko <peter.polacko+asn1net@gmail.com>
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Net.Asn1.Type;
namespace Net.Asn1.Writer.Tests.Integration
{
class AlgorithmIdentifierAsn1Net
{
public Asn1ObjectIdentifier Algorithm
{
get;
private set;
}
public Asn1ObjectBase Parameters
{
get;
private set;
}
public AlgorithmIdentifierAsn1Net(Asn1ObjectIdentifier algorithm, Asn1ObjectBase parameters)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
Algorithm = algorithm;
Parameters = parameters;
}
public AlgorithmIdentifierAsn1Net(Asn1Sequence seq)
{
if (seq == null)
throw new ArgumentNullException("seq");
if (seq.Content.Count < 1 || seq.Content.Count > 2)
throw new ArgumentException("Invalid number of sequence members");
Algorithm = seq.Content.First() as Asn1ObjectIdentifier;
Parameters = (seq.Content.Count == 2) ? seq.Content[1] : null;
}
public AlgorithmIdentifierAsn1Net(byte[] content)
{
BerReader reader = new BerReader(new MemoryStream(content));
Asn1Sequence seq;
reader.ReadOne<Asn1Sequence>(out seq);
Algorithm = seq.Content.First() as Asn1ObjectIdentifier;
Parameters = (seq.Content.Count == 2) ? seq.Content[1] : null;
}
public static AlgorithmIdentifierAsn1Net GetInstance(object obj)
{
if (obj == null || obj is AlgorithmIdentifierAsn1Net)
return (AlgorithmIdentifierAsn1Net)obj;
if (obj is Asn1Sequence)
return new AlgorithmIdentifierAsn1Net((Asn1Sequence)obj);
throw new ArgumentException("Unable to convert: " + obj.GetType().Name, "obj");
}
public Asn1ObjectBase Encode()
{
var content = new List<Asn1ObjectBase> { Algorithm };
if (Parameters != null)
{
content.Add(Parameters);
}
var encoded = new Asn1Sequence(Asn1Class.Universal, content);
return encoded;
}
}
}
| 30.795918 | 100 | 0.61332 | [
"Apache-2.0"
] | Asn1Net/Asn1Net | test/Asn1Net.Test/Integration/AlgorithmIdentifierAsn1Net.cs | 3,020 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MasterDetailDemo.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoadingIndicatorPage1 : ContentPage
{
public LoadingIndicatorPage1 ()
{
InitializeComponent ();
}
}
} | 19.3 | 57 | 0.784974 | [
"MIT"
] | higedamc/HigeDevelopment | MasterDetailDemo/MasterDetailDemo/Yokuwakaran/LoadingIndicatorPage1.xaml.cs | 388 | 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( "Noise.Core.Tests" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "Microsoft" )]
[assembly: AssemblyProduct( "Noise.Core.Tests" )]
[assembly: AssemblyCopyright( "Copyright © Microsoft 2011" )]
[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( "d11735d7-ff7e-41ae-af55-fdacca92a9e1" )]
// 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" )]
| 39.108108 | 84 | 0.734623 | [
"MIT"
] | bswanson58/NoiseMusicSystem | Noise.Core.Tests/Properties/AssemblyInfo.cs | 1,450 | C# |
using System.Threading.Tasks;
using Microsoft.Playwright.Testing.Xunit;
using Microsoft.Playwright.Tests.Attributes;
using Microsoft.Playwright.Tests.BaseTests;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Playwright.Tests
{
[Collection(TestConstants.TestFixtureBrowserCollectionName)]
public class PageDialogTests : PlaywrightSharpPageBaseTest
{
/// <inheritdoc/>
public PageDialogTests(ITestOutputHelper output) : base(output)
{
}
[PlaywrightTest("page-dialog.spec.ts", "should fire")]
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
public async Task ShouldFire()
{
Page.Dialog += async (_, e) =>
{
Assert.Equal(DialogType.Alert, e.Type);
Assert.Equal(string.Empty, e.DefaultValue);
Assert.Equal("yo", e.Message);
await e.AcceptAsync();
};
await Page.EvaluateAsync("alert('yo');");
}
[PlaywrightTest("page-dialog.spec.ts", "should allow accepting prompts")]
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
public async Task ShouldAllowAcceptingPrompts()
{
Page.Dialog += async (_, e) =>
{
Assert.Equal(DialogType.Prompt, e.Type);
Assert.Equal("yes.", e.DefaultValue);
Assert.Equal("question?", e.Message);
await e.AcceptAsync("answer!");
};
string result = await Page.EvaluateAsync<string>("prompt('question?', 'yes.')");
Assert.Equal("answer!", result);
}
[PlaywrightTest("page-dialog.spec.ts", "should dismiss the prompt")]
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
public async Task ShouldDismissThePrompt()
{
Page.Dialog += async (_, e) =>
{
await e.DismissAsync();
};
string result = await Page.EvaluateAsync<string>("prompt('question?')");
Assert.Null(result);
}
[PlaywrightTest("page-dialog.spec.ts", "should accept the confirm prompt")]
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
public async Task ShouldAcceptTheConfirmPrompts()
{
Page.Dialog += async (_, e) =>
{
await e.AcceptAsync();
};
bool result = await Page.EvaluateAsync<bool>("confirm('boolean?')");
Assert.True(result);
}
[PlaywrightTest("page-dialog.spec.ts", "should dismiss the confirm prompt")]
[Fact(Timeout = TestConstants.DefaultTestTimeout)]
public async Task ShouldDismissTheConfirmPrompt()
{
Page.Dialog += async (_, e) =>
{
await e.DismissAsync();
};
bool result = await Page.EvaluateAsync<bool>("prompt('boolean?')");
Assert.False(result);
}
[PlaywrightTest("page-dialog.spec.ts", "should log prompt actions")]
[Fact(Skip = "FAIL CHANNEL")]
public async Task ShouldLogPromptActions()
{
Page.Dialog += async (_, e) =>
{
await e.DismissAsync();
};
bool result = await Page.EvaluateAsync<bool>("prompt('boolean?')");
Assert.False(result);
}
[PlaywrightTest("page-dialog.spec.ts", "should be able to close context with open alert")]
[SkipBrowserAndPlatformFact(skipWebkit: true)]
public async Task ShouldBeAbleToCloseContextWithOpenAlert()
{
var context = await Browser.NewContextAsync();
var page = await context.NewPageAsync();
var alertTask = page.WaitForEventAsync(PageEvent.Dialog);
await page.EvaluateAsync("() => setTimeout(() => alert('hello'), 0)");
await alertTask;
await context.CloseAsync();
}
}
}
| 34.051282 | 98 | 0.570281 | [
"MIT"
] | hardkoded/playwright-sharp | src/Playwright.Tests/PageDialogTests.cs | 3,984 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.Documentation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation
{
/// <summary>
/// Default implementation of <see cref="ITypeDefinition"/>.
/// </summary>
public class DefaultResolvedTypeDefinition : ITypeDefinition
{
readonly ITypeResolveContext parentContext;
readonly IUnresolvedTypeDefinition[] parts;
Accessibility accessibility = Accessibility.Internal;
bool isAbstract, isSealed, isShadowing;
bool isSynthetic = true; // true if all parts are synthetic
public DefaultResolvedTypeDefinition(ITypeResolveContext parentContext, params IUnresolvedTypeDefinition[] parts)
{
if (parentContext == null || parentContext.CurrentAssembly == null)
throw new ArgumentException("Parent context does not specify any assembly", "parentContext");
if (parts == null || parts.Length == 0)
throw new ArgumentException("No parts were specified", "parts");
this.parentContext = parentContext;
this.parts = parts;
foreach (IUnresolvedTypeDefinition part in parts) {
isAbstract |= part.IsAbstract;
isSealed |= part.IsSealed;
isShadowing |= part.IsShadowing;
isSynthetic &= part.IsSynthetic; // true if all parts are synthetic
// internal is the default, so use another part's accessibility until we find a non-internal accessibility
if (accessibility == Accessibility.Internal)
accessibility = part.Accessibility;
}
}
IList<ITypeParameter> typeParameters;
public IList<ITypeParameter> TypeParameters {
get {
var result = LazyInit.VolatileRead(ref this.typeParameters);
if (result != null) {
return result;
}
ITypeResolveContext contextForTypeParameters = parts[0].CreateResolveContext(parentContext);
contextForTypeParameters = contextForTypeParameters.WithCurrentTypeDefinition(this);
if (parentContext.CurrentTypeDefinition == null || parentContext.CurrentTypeDefinition.TypeParameterCount == 0) {
result = parts[0].TypeParameters.CreateResolvedTypeParameters(contextForTypeParameters);
} else {
// This is a nested class inside a generic class; copy type parameters from outer class if we can:
var outerClass = parentContext.CurrentTypeDefinition;
ITypeParameter[] typeParameters = new ITypeParameter[parts[0].TypeParameters.Count];
for (int i = 0; i < typeParameters.Length; i++) {
var unresolvedTP = parts[0].TypeParameters[i];
if (i < outerClass.TypeParameterCount && outerClass.TypeParameters[i].Name == unresolvedTP.Name)
typeParameters[i] = outerClass.TypeParameters[i];
else
typeParameters[i] = unresolvedTP.CreateResolvedTypeParameter(contextForTypeParameters);
}
result = Array.AsReadOnly(typeParameters);
}
return LazyInit.GetOrSet(ref this.typeParameters, result);
}
}
IList<IAttribute> attributes;
public IList<IAttribute> Attributes {
get {
var result = LazyInit.VolatileRead(ref this.attributes);
if (result != null) {
return result;
}
result = new List<IAttribute>();
var context = parentContext.WithCurrentTypeDefinition(this);
foreach (IUnresolvedTypeDefinition part in parts) {
ITypeResolveContext parentContextForPart = part.CreateResolveContext(context);
foreach (var attr in part.Attributes) {
result.Add(attr.CreateResolvedAttribute(parentContextForPart));
}
}
if (result.Count == 0)
result = EmptyList<IAttribute>.Instance;
return LazyInit.GetOrSet(ref this.attributes, result);
}
}
public IList<IUnresolvedTypeDefinition> Parts {
get { return parts; }
}
public SymbolKind SymbolKind {
get { return parts[0].SymbolKind; }
}
[Obsolete("Use the SymbolKind property instead.")]
public EntityType EntityType {
get { return (EntityType)parts[0].SymbolKind; }
}
public virtual TypeKind Kind {
get { return parts[0].Kind; }
}
#region NestedTypes
IList<ITypeDefinition> nestedTypes;
public IList<ITypeDefinition> NestedTypes {
get {
IList<ITypeDefinition> result = LazyInit.VolatileRead(ref this.nestedTypes);
if (result != null) {
return result;
} else {
result = (
from part in parts
from nestedTypeRef in part.NestedTypes
group nestedTypeRef by new { nestedTypeRef.Name, nestedTypeRef.TypeParameters.Count } into g
select new DefaultResolvedTypeDefinition(new SimpleTypeResolveContext(this), g.ToArray())
).ToList<ITypeDefinition>().AsReadOnly();
return LazyInit.GetOrSet(ref this.nestedTypes, result);
}
}
}
#endregion
#region Members
sealed class MemberList : IList<IMember>
{
internal readonly ITypeResolveContext[] contextPerMember;
internal readonly IUnresolvedMember[] unresolvedMembers;
internal readonly IMember[] resolvedMembers;
internal readonly int NonPartialMemberCount;
public MemberList(List<ITypeResolveContext> contextPerMember, List<IUnresolvedMember> unresolvedNonPartialMembers, List<PartialMethodInfo> partialMethodInfos)
{
this.NonPartialMemberCount = unresolvedNonPartialMembers.Count;
this.contextPerMember = contextPerMember.ToArray();
this.unresolvedMembers = unresolvedNonPartialMembers.ToArray();
if (partialMethodInfos == null) {
this.resolvedMembers = new IMember[unresolvedNonPartialMembers.Count];
} else {
this.resolvedMembers = new IMember[unresolvedNonPartialMembers.Count + partialMethodInfos.Count];
for (int i = 0; i < partialMethodInfos.Count; i++) {
var info = partialMethodInfos[i];
int memberIndex = NonPartialMemberCount + i;
resolvedMembers[memberIndex] = DefaultResolvedMethod.CreateFromMultipleParts(
info.Parts.ToArray(), info.Contexts.ToArray (), false);
}
}
}
public IMember this[int index] {
get {
IMember output = LazyInit.VolatileRead(ref resolvedMembers[index]);
if (output != null) {
return output;
}
return LazyInit.GetOrSet(ref resolvedMembers[index], unresolvedMembers[index].CreateResolved(contextPerMember[index]));
}
set { throw new NotSupportedException(); }
}
public int Count {
get { return resolvedMembers.Length; }
}
bool ICollection<IMember>.IsReadOnly {
get { return true; }
}
public int IndexOf(IMember item)
{
for (int i = 0; i < this.Count; i++) {
if (this[i].Equals(item))
return i;
}
return -1;
}
void IList<IMember>.Insert(int index, IMember item)
{
throw new NotSupportedException();
}
void IList<IMember>.RemoveAt(int index)
{
throw new NotSupportedException();
}
void ICollection<IMember>.Add(IMember item)
{
throw new NotSupportedException();
}
void ICollection<IMember>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<IMember>.Contains(IMember item)
{
return IndexOf(item) >= 0;
}
void ICollection<IMember>.CopyTo(IMember[] array, int arrayIndex)
{
for (int i = 0; i < this.Count; i++) {
array[arrayIndex + i] = this[i];
}
}
bool ICollection<IMember>.Remove(IMember item)
{
throw new NotSupportedException();
}
public IEnumerator<IMember> GetEnumerator()
{
for (int i = 0; i < this.Count; i++) {
yield return this[i];
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
sealed class PartialMethodInfo
{
public readonly string Name;
public readonly int TypeParameterCount;
public readonly IList<IParameter> Parameters;
public readonly List<IUnresolvedMethod> Parts = new List<IUnresolvedMethod>();
public readonly List<ITypeResolveContext> Contexts = new List<ITypeResolveContext>();
public PartialMethodInfo(IUnresolvedMethod method, ITypeResolveContext context)
{
this.Name = method.Name;
this.TypeParameterCount = method.TypeParameters.Count;
this.Parameters = method.Parameters.CreateResolvedParameters(context);
this.Parts.Add(method);
this.Contexts.Add (context);
}
public void AddPart(IUnresolvedMethod method, ITypeResolveContext context)
{
if (method.HasBody) {
// make the implementation the primary part
this.Parts.Insert(0, method);
this.Contexts.Insert (0, context);
} else {
this.Parts.Add(method);
this.Contexts.Add (context);
}
}
public bool IsSameSignature(PartialMethodInfo other, StringComparer nameComparer)
{
return nameComparer.Equals(this.Name, other.Name)
&& this.TypeParameterCount == other.TypeParameterCount
&& ParameterListComparer.Instance.Equals(this.Parameters, other.Parameters);
}
}
MemberList memberList;
MemberList GetMemberList()
{
var result = LazyInit.VolatileRead(ref this.memberList);
if (result != null) {
return result;
}
List<IUnresolvedMember> unresolvedMembers = new List<IUnresolvedMember>();
List<ITypeResolveContext> contextPerMember = new List<ITypeResolveContext>();
List<PartialMethodInfo> partialMethodInfos = null;
bool addDefaultConstructorIfRequired = false;
foreach (IUnresolvedTypeDefinition part in parts) {
ITypeResolveContext parentContextForPart = part.CreateResolveContext(parentContext);
ITypeResolveContext contextForPart = parentContextForPart.WithCurrentTypeDefinition(this);
foreach (var member in part.Members) {
if (member is IUnresolvedMethod method && method.IsPartial)
{
// Merge partial method declaration and implementation
if (partialMethodInfos == null)
partialMethodInfos = new List<PartialMethodInfo>();
PartialMethodInfo newInfo = new PartialMethodInfo(method, contextForPart);
PartialMethodInfo existingInfo = null;
foreach (var info in partialMethodInfos)
{
if (newInfo.IsSameSignature(info, Compilation.NameComparer))
{
existingInfo = info;
break;
}
}
if (existingInfo != null)
{
// Add the unresolved method to the PartialMethodInfo:
existingInfo.AddPart(method, contextForPart);
}
else
{
partialMethodInfos.Add(newInfo);
}
}
else
{
unresolvedMembers.Add(member);
contextPerMember.Add(contextForPart);
}
}
addDefaultConstructorIfRequired |= part.AddDefaultConstructorIfRequired;
}
if (addDefaultConstructorIfRequired) {
TypeKind kind = this.Kind;
if (kind == TypeKind.Class && !this.IsStatic && !unresolvedMembers.Any(m => m.SymbolKind == SymbolKind.Constructor && !m.IsStatic)
|| kind == TypeKind.Enum || kind == TypeKind.Struct)
{
contextPerMember.Add(parts[0].CreateResolveContext(parentContext).WithCurrentTypeDefinition(this));
unresolvedMembers.Add(DefaultUnresolvedMethod.CreateDefaultConstructor(parts[0]));
}
}
result = new MemberList(contextPerMember, unresolvedMembers, partialMethodInfos);
return LazyInit.GetOrSet(ref this.memberList, result);
}
public IList<IMember> Members {
get { return GetMemberList(); }
}
public IEnumerable<IField> Fields {
get {
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
if (members.unresolvedMembers[i].SymbolKind == SymbolKind.Field)
yield return (IField)members[i];
}
}
}
public IEnumerable<IMethod> Methods {
get {
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
if (members.unresolvedMembers[i] is IUnresolvedMethod)
yield return (IMethod)members[i];
}
for (int i = members.unresolvedMembers.Length; i < members.Count; i++) {
yield return (IMethod)members[i];
}
}
}
public IEnumerable<IProperty> Properties {
get {
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
switch (members.unresolvedMembers[i].SymbolKind) {
case SymbolKind.Property:
case SymbolKind.Indexer:
yield return (IProperty)members[i];
break;
}
}
}
}
public IEnumerable<IEvent> Events {
get {
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
if (members.unresolvedMembers[i].SymbolKind == SymbolKind.Event)
yield return (IEvent)members[i];
}
}
}
#endregion
volatile KnownTypeCode knownTypeCode = (KnownTypeCode)(-1);
public KnownTypeCode KnownTypeCode {
get {
KnownTypeCode result = this.knownTypeCode;
if (result == (KnownTypeCode)(-1)) {
result = KnownTypeCode.None;
ICompilation compilation = this.Compilation;
for (int i = 0; i < KnownTypeReference.KnownTypeCodeCount; i++) {
if (compilation.FindType((KnownTypeCode)i) == this) {
result = (KnownTypeCode)i;
break;
}
}
this.knownTypeCode = result;
}
return result;
}
}
volatile IType enumUnderlyingType;
public IType EnumUnderlyingType {
get {
IType result = this.enumUnderlyingType;
if (result == null) {
if (this.Kind == TypeKind.Enum) {
result = CalculateEnumUnderlyingType();
} else {
result = SpecialType.UnknownType;
}
this.enumUnderlyingType = result;
}
return result;
}
}
IType CalculateEnumUnderlyingType()
{
foreach (var part in parts) {
var context = part.CreateResolveContext(parentContext).WithCurrentTypeDefinition(this);
foreach (var baseTypeRef in part.BaseTypes) {
IType type = baseTypeRef.Resolve(context);
if (type.Kind != TypeKind.Unknown)
return type;
}
}
return this.Compilation.FindType(KnownTypeCode.Int32);
}
volatile byte hasExtensionMethods; // 0 = unknown, 1 = true, 2 = false
public bool HasExtensionMethods {
get {
byte val = this.hasExtensionMethods;
if (val == 0) {
if (CalculateHasExtensionMethods())
val = 1;
else
val = 2;
this.hasExtensionMethods = val;
}
return val == 1;
}
}
bool CalculateHasExtensionMethods()
{
bool noExtensionMethods = true;
foreach (var part in parts) {
// Return true if any part has extension methods
if (part.HasExtensionMethods == true)
return true;
if (part.HasExtensionMethods == null)
noExtensionMethods = false;
}
// Return false if all parts are known to have no extension methods
if (noExtensionMethods)
return false;
// If unsure, look at the resolved methods.
return Methods.Any(m => m.IsExtensionMethod);
}
public bool IsPartial {
get { return parts.Length > 1 || parts[0].IsPartial; }
}
public bool? IsReferenceType {
get {
switch (this.Kind) {
case TypeKind.Class:
case TypeKind.Interface:
case TypeKind.Module:
case TypeKind.Delegate:
return true;
case TypeKind.Struct:
case TypeKind.Enum:
case TypeKind.Void:
return false;
default:
throw new InvalidOperationException("Invalid value for TypeKind");
}
}
}
public int TypeParameterCount {
get { return parts[0].TypeParameters.Count; }
}
public IList<IType> TypeArguments {
get {
// ToList() call is necessary because IList<> isn't covariant
return TypeParameters.ToList<IType>();
}
}
public bool IsParameterized {
get { return false; }
}
#region DirectBaseTypes
IList<IType> directBaseTypes;
public IEnumerable<IType> DirectBaseTypes {
get {
IList<IType> result = LazyInit.VolatileRead(ref this.directBaseTypes);
if (result != null) {
return result;
}
using (var busyLock = BusyManager.Enter(this)) {
if (busyLock.Success) {
result = CalculateDirectBaseTypes();
return LazyInit.GetOrSet(ref this.directBaseTypes, result);
} else {
// This can happen for "class Test : $Test.Base$ { public class Base {} }"
// and also for the valid code
// "class Test : Base<Test.Inner> { public class Inner {} }"
// Don't cache the error!
return EmptyList<IType>.Instance;
}
}
}
}
IList<IType> CalculateDirectBaseTypes()
{
List<IType> result = new List<IType>();
bool hasNonInterface = false;
if (this.Kind != TypeKind.Enum) {
foreach (var part in parts) {
var context = part.CreateResolveContext(parentContext).WithCurrentTypeDefinition(this);
foreach (var baseTypeRef in part.BaseTypes) {
IType baseType = baseTypeRef.Resolve(context);
if (!(baseType.Kind == TypeKind.Unknown || result.Contains(baseType))) {
result.Add(baseType);
if (baseType.Kind != TypeKind.Interface)
hasNonInterface = true;
}
}
}
}
if (!hasNonInterface && !(this.Name == "Object" && this.Namespace == "System" && this.TypeParameterCount == 0)) {
KnownTypeCode primitiveBaseType;
switch (this.Kind) {
case TypeKind.Enum:
primitiveBaseType = KnownTypeCode.Enum;
break;
case TypeKind.Struct:
case TypeKind.Void:
primitiveBaseType = KnownTypeCode.ValueType;
break;
case TypeKind.Delegate:
primitiveBaseType = KnownTypeCode.Delegate;
break;
default:
primitiveBaseType = KnownTypeCode.Object;
break;
}
IType t = parentContext.Compilation.FindType(primitiveBaseType);
if (t.Kind != TypeKind.Unknown)
result.Add(t);
}
return result;
}
#endregion
public string FullName {
get { return parts[0].FullName; }
}
public string Name {
get { return parts[0].Name; }
}
public string ReflectionName {
get { return parts[0].ReflectionName; }
}
public string Namespace {
get { return parts[0].Namespace; }
}
public FullTypeName FullTypeName {
get { return parts[0].FullTypeName; }
}
public DomRegion Region {
get { return parts[0].Region; }
}
public DomRegion BodyRegion {
get { return parts[0].BodyRegion; }
}
public ITypeDefinition DeclaringTypeDefinition {
get { return parentContext.CurrentTypeDefinition; }
}
public IType DeclaringType {
get { return parentContext.CurrentTypeDefinition; }
}
public IAssembly ParentAssembly {
get { return parentContext.CurrentAssembly; }
}
public virtual DocumentationComment Documentation {
get {
foreach (var part in parts) {
if (part.UnresolvedFile is IUnresolvedDocumentationProvider unresolvedProvider)
{
var doc = unresolvedProvider.GetDocumentation(part, this);
if (doc != null)
return doc;
}
}
IDocumentationProvider provider = AbstractResolvedEntity.FindDocumentation(parentContext);
if (provider != null)
return provider.GetDocumentation(this);
else
return null;
}
}
public ICompilation Compilation {
get { return parentContext.Compilation; }
}
#region Modifiers
public bool IsStatic { get { return isAbstract && isSealed; } }
public bool IsAbstract { get { return isAbstract; } }
public bool IsSealed { get { return isSealed; } }
public bool IsShadowing { get { return isShadowing; } }
public bool IsSynthetic { get { return isSynthetic; } }
public Accessibility Accessibility {
get { return accessibility; }
}
bool IHasAccessibility.IsPrivate {
get { return accessibility == Accessibility.Private; }
}
bool IHasAccessibility.IsPublic {
get { return accessibility == Accessibility.Public; }
}
bool IHasAccessibility.IsProtected {
get { return accessibility == Accessibility.Protected; }
}
bool IHasAccessibility.IsInternal {
get { return accessibility == Accessibility.Internal; }
}
bool IHasAccessibility.IsProtectedOrInternal {
get { return accessibility == Accessibility.ProtectedOrInternal; }
}
bool IHasAccessibility.IsProtectedAndInternal {
get { return accessibility == Accessibility.ProtectedAndInternal; }
}
#endregion
ITypeDefinition IType.GetDefinition()
{
return this;
}
IType IType.AcceptVisitor(TypeVisitor visitor)
{
return visitor.VisitTypeDefinition(this);
}
IType IType.VisitChildren(TypeVisitor visitor)
{
return this;
}
public ITypeReference ToTypeReference()
{
ITypeDefinition declTypeDef = this.DeclaringTypeDefinition;
if (declTypeDef != null) {
return new NestedTypeReference(declTypeDef.ToTypeReference(), this.Name, this.TypeParameterCount - declTypeDef.TypeParameterCount);
} else {
IAssembly asm = this.ParentAssembly;
IAssemblyReference asmRef;
if (asm != null)
asmRef = new DefaultAssemblyReference(asm.AssemblyName);
else
asmRef = null;
return new GetClassTypeReference(asmRef, this.Namespace, this.Name, this.TypeParameterCount);
}
}
ISymbolReference ISymbol.ToReference()
{
return (ISymbolReference)ToTypeReference();
}
public IEnumerable<IType> GetNestedTypes(Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
const GetMemberOptions opt = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions;
if ((options & opt) == opt) {
if (filter == null)
return this.NestedTypes;
else
return GetNestedTypesImpl(filter);
} else {
return GetMembersHelper.GetNestedTypes(this, filter, options);
}
}
IEnumerable<IType> GetNestedTypesImpl(Predicate<ITypeDefinition> filter)
{
foreach (var nestedType in this.NestedTypes) {
if (filter(nestedType))
yield return nestedType;
}
}
public IEnumerable<IType> GetNestedTypes(IList<IType> typeArguments, Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return GetMembersHelper.GetNestedTypes(this, typeArguments, filter, options);
}
#region GetMembers()
IEnumerable<IMember> GetFilteredMembers(Predicate<IUnresolvedMember> filter)
{
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
if (filter == null || filter(members.unresolvedMembers[i])) {
yield return members[i];
}
}
for (int i = members.unresolvedMembers.Length; i < members.Count; i++) {
var method = (IMethod)members[i];
bool ok = false;
foreach (var part in method.Parts) {
if (filter == null || filter(part)) {
ok = true;
break;
}
}
if (ok)
yield return method;
}
}
IEnumerable<IMethod> GetFilteredMethods(Predicate<IUnresolvedMethod> filter)
{
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
if (members.unresolvedMembers[i] is IUnresolvedMethod unresolved && (filter == null || filter(unresolved)))
{
yield return (IMethod)members[i];
}
}
for (int i = members.unresolvedMembers.Length; i < members.Count; i++) {
var method = (IMethod)members[i];
bool ok = false;
foreach (var part in method.Parts) {
if (filter == null || filter(part)) {
ok = true;
break;
}
}
if (ok)
yield return method;
}
}
IEnumerable<TResolved> GetFilteredNonMethods<TUnresolved, TResolved>(Predicate<TUnresolved> filter) where TUnresolved : class, IUnresolvedMember where TResolved : class, IMember
{
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
if (members.unresolvedMembers[i] is TUnresolved unresolved && (filter == null || filter(unresolved)))
{
yield return (TResolved)members[i];
}
}
}
public virtual IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
return GetFilteredMethods(Utils.ExtensionMethods.And(m => !m.IsConstructor, filter));
} else {
return GetMembersHelper.GetMethods(this, filter, options);
}
}
public virtual IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return GetMembersHelper.GetMethods(this, typeArguments, filter, options);
}
public virtual IEnumerable<IMethod> GetConstructors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers)
{
if (ComHelper.IsComImport(this)) {
IType coClass = ComHelper.GetCoClass(this);
using (var busyLock = BusyManager.Enter(this)) {
if (busyLock.Success) {
return coClass.GetConstructors(filter, options)
.Select(m => new SpecializedMethod(m, m.Substitution) { DeclaringType = this });
}
}
return EmptyList<IMethod>.Instance;
}
if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
return GetFilteredMethods(Utils.ExtensionMethods.And(m => m.IsConstructor && !m.IsStatic, filter));
} else {
return GetMembersHelper.GetConstructors(this, filter, options);
}
}
public virtual IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
return GetFilteredNonMethods<IUnresolvedProperty, IProperty>(filter);
} else {
return GetMembersHelper.GetProperties(this, filter, options);
}
}
public virtual IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
return GetFilteredNonMethods<IUnresolvedField, IField>(filter);
} else {
return GetMembersHelper.GetFields(this, filter, options);
}
}
public virtual IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
return GetFilteredNonMethods<IUnresolvedEvent, IEvent>(filter);
} else {
return GetMembersHelper.GetEvents(this, filter, options);
}
}
public virtual IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
return GetFilteredMembers(filter);
} else {
return GetMembersHelper.GetMembers(this, filter, options);
}
}
public virtual IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
return GetFilteredAccessors(filter);
} else {
return GetMembersHelper.GetAccessors(this, filter, options);
}
}
IEnumerable<IMethod> GetFilteredAccessors(Predicate<IUnresolvedMethod> filter)
{
var members = GetMemberList();
for (int i = 0; i < members.unresolvedMembers.Length; i++) {
IUnresolvedMember unresolved = members.unresolvedMembers[i];
if (unresolved is IUnresolvedProperty unresolvedProperty)
{
if (unresolvedProperty.CanGet && (filter == null || filter(unresolvedProperty.Getter)))
yield return ((IProperty)members[i]).Getter;
if (unresolvedProperty.CanSet && (filter == null || filter(unresolvedProperty.Setter)))
yield return ((IProperty)members[i]).Setter;
}
else if (unresolved is IUnresolvedEvent unresolvedEvent)
{
if (unresolvedEvent.CanAdd && (filter == null || filter(unresolvedEvent.AddAccessor)))
yield return ((IEvent)members[i]).AddAccessor;
if (unresolvedEvent.CanRemove && (filter == null || filter(unresolvedEvent.RemoveAccessor)))
yield return ((IEvent)members[i]).RemoveAccessor;
if (unresolvedEvent.CanInvoke && (filter == null || filter(unresolvedEvent.InvokeAccessor)))
yield return ((IEvent)members[i]).InvokeAccessor;
}
}
}
#endregion
#region GetInterfaceImplementation
public IMember GetInterfaceImplementation(IMember interfaceMember)
{
return GetInterfaceImplementation(new[] { interfaceMember })[0];
}
public IList<IMember> GetInterfaceImplementation(IList<IMember> interfaceMembers)
{
// TODO: review the subtle rules for interface reimplementation,
// write tests and fix this method.
// Also virtual/override is going to be tricky -
// I think we'll need to consider the 'virtual' method first for
// reimplemenatation purposes, but then actually return the 'override'
// (as that's the method that ends up getting called)
interfaceMembers = interfaceMembers.ToList(); // avoid evaluating more than once
var result = new IMember[interfaceMembers.Count];
var signatureToIndexDict = new MultiDictionary<IMember, int>(SignatureComparer.Ordinal);
for (int i = 0; i < interfaceMembers.Count; i++) {
signatureToIndexDict.Add(interfaceMembers[i], i);
}
foreach (var member in GetMembers(m => !m.IsExplicitInterfaceImplementation)) {
foreach (int interfaceMemberIndex in signatureToIndexDict[member]) {
result[interfaceMemberIndex] = member;
}
}
foreach (var explicitImpl in GetMembers(m => m.IsExplicitInterfaceImplementation)) {
foreach (var interfaceMember in explicitImpl.ImplementedInterfaceMembers) {
foreach (int potentialMatchingIndex in signatureToIndexDict[interfaceMember]) {
if (interfaceMember.Equals(interfaceMembers[potentialMatchingIndex])) {
result[potentialMatchingIndex] = explicitImpl;
}
}
}
}
return result;
}
#endregion
public TypeParameterSubstitution GetSubstitution()
{
return TypeParameterSubstitution.Identity;
}
public TypeParameterSubstitution GetSubstitution(IList<IType> methodTypeArguments)
{
return TypeParameterSubstitution.Identity;
}
public bool Equals(IType other)
{
return this == other;
}
public override string ToString()
{
return this.ReflectionName;
}
}
}
| 41.624486 | 185 | 0.545713 | [
"Apache-2.0"
] | curiosity-ai/h5 | External/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs | 40,461 | C# |
namespace Bike.Interpreter
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Ast;
using Builtin;
internal class ClrImportContext : ImportContext
{
private static readonly ISet<Assembly> StartupAssemblies = new HashSet<Assembly>();
private readonly object syncLock = new object();
private readonly ISet<Assembly> importedAssemblies = new HashSet<Assembly>();
private readonly IDictionary<string, Type> visibleTypes = new Dictionary<string, Type>();
static ClrImportContext()
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
#if DEBUG
// For some reason, loading NUnit will fail
// when running tests in MonoDevelop
if (!assembly.FullName.Contains("NUnit"))
#endif
StartupAssemblies.Add(assembly);
}
}
public ClrImportContext(string coreLibFolder, string addonLibFolders)
: base(coreLibFolder, addonLibFolders)
{
foreach (var assembly in StartupAssemblies)
ImportAssembly(assembly);
}
public void ImportAssembly(string currentFolder, string assemblyString)
{
var assembly = ResolveAssembly(currentFolder, assemblyString);
lock (syncLock)
{
ImportAssembly(assembly);
}
}
private void ImportAssembly(Assembly assembly)
{
if (importedAssemblies.Contains(assembly))
return;
importedAssemblies.Add(assembly);
ImportTypes(assembly.GetTypes());
}
private void ImportTypes(IEnumerable<Type> types)
{
foreach (var type in types)
{
if (!visibleTypes.ContainsKey(type.FullName))
visibleTypes.Add(type.FullName, type);
ImportTypes(type.GetNestedTypes());
}
}
public bool IsVisibleClrType(string typeName)
{
lock (syncLock)
{
return visibleTypes.ContainsKey(typeName);
}
}
public Type LoadTypeFromName(string typeName)
{
lock (syncLock)
{
if (!IsVisibleClrType(typeName))
throw ErrorFactory.CreateClrError(string.Format("Type {0} cannot be found", typeName));
return visibleTypes[typeName];
}
}
public Type LoadTypeFromName(string typeName, Type[] typeParams)
{
var sb = new StringBuilder();
sb.Append(typeName)
.Append("`")
.Append(typeParams.Length);
var openType = LoadTypeFromName(sb.ToString());
return openType.MakeGenericType(typeParams);
}
public Type LoadTypeFromDescriptor(TypeDescriptor typeDescriptor)
{
if (typeDescriptor.TypeDescriptors.Count == 0)
return LoadTypeFromName(typeDescriptor.Name);
var typeParams = typeDescriptor
.TypeDescriptors
.Select(LoadTypeFromDescriptor)
.ToArray();
return LoadTypeFromName(typeDescriptor.Name, typeParams);
}
private Assembly ResolveAssembly(string currentFolder, string assemblyString)
{
if (Path.GetExtension(assemblyString).ToUpperInvariant() == ".DLL")
{
var fullPath = ResolvePath(currentFolder, assemblyString);
return Assembly.LoadFrom(fullPath);
}
return Assembly.Load(assemblyString);
}
}
}
| 32.179487 | 107 | 0.582736 | [
"MIT"
] | buunguyen/bike | src/Bike/Interpreter/Context/ClrImportContext.cs | 3,767 | C# |
using System;
using System.Collections.Generic;
namespace Bonobo.Git.Server.Data.Update
{
public static class UpdateScriptRepository
{
/// <summary>
/// Creates the list of scripts that should be executed on app start. Ordering matters!
/// </summary>
public static IEnumerable<IUpdateScript> GetScriptsBySqlProviderName(string sqlProvider)
{
switch (sqlProvider)
{
case "SQLiteConnection":
return new List<IUpdateScript>
{
new Sqlite.InitialCreateScript(),
new UsernamesToLower(),
new Sqlite.AddAuditPushUser(),
new Sqlite.AddGroup(),
new Sqlite.AddRepositoryLogo(),
new Sqlite.AddGuidColumn(),
new Sqlite.AddRepoPushColumn(),
new Sqlite.AddRepoLinksColumn(),
new Sqlite.InsertDefaultData()
};
case "SqlConnection":
return new List<IUpdateScript>
{
new SqlServer.InitialCreateScript(),
new UsernamesToLower(),
new SqlServer.AddAuditPushUser(),
new SqlServer.AddGroup(),
new SqlServer.AddRepositoryLogo(),
new SqlServer.AddGuidColumn(),
new SqlServer.AddRepoPushColumn(),
new SqlServer.AddRepoLinksColumn(),
new SqlServer.InsertDefaultData()
};
default:
throw new NotImplementedException($"The provider '{sqlProvider}' is not supported yet");
}
}
}
}
| 39.765957 | 108 | 0.489032 | [
"MIT"
] | 16it/Bonobo-Git-Server | Bonobo.Git.Server/Data/Update/UpdateScriptRepository.cs | 1,871 | C# |
///
/// See COPYING file for licensing information
///
using System;
namespace com.mosso.cloudfiles.exceptions
{
/// <summary>
/// This exception is thrown when the user attempts to delete a container that still has storage objects associated with it
/// </summary>
public class ContainerNotEmptyException : Exception
{
/// <summary>
/// The default constructor
/// </summary>
public ContainerNotEmptyException()
{
}
/// <summary>
/// A constructor for more explicitly explaining the reason for failure
/// </summary>
/// <param name="msg">A message for describing the exception in detail</param>
public ContainerNotEmptyException(string msg) : base(msg)
{
}
}
} | 26.466667 | 127 | 0.617128 | [
"Apache-2.0"
] | seanlinmt/tradelr | com.mosso.cloudfiles/Exceptions/ContainerNotEmptyException.cs | 794 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using DxLibDLL;
namespace Charlotte
{
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public class ReleaseAccessibleSwordService
{
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int ArchiveNestedPortiaUsername;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void UploadVisibleRosalindHost()
{
this.ClonePublicPaaliaqNotice(0);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int ValidateMockMnemeCoordinate;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int PassCorrectEurydomeScript;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public SignBasedEuantheDashboard UninstallUnavailableNamakaContainer()
{
return PlayCorrectMetisExpression;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void EmailPreferredSeaborgiumBuffer(int PostMissingProteusBreakpoint, int IncludeEmptyPsamatheForm, int DeployPrivateHoneyExtension, int ValidateFalseCarmeLimit, int ForceMissingEuantheUnit, int ReferBasedHermippeFramework)
{
var AttachAdditionalNileAllocation = new[]
{
new
{
UseAdditionalAtlasConflict = PostMissingProteusBreakpoint, ProvisionManualBeautyPrefix = ValidateFalseCarmeLimit
},
new
{
UseAdditionalAtlasConflict = IncludeEmptyPsamatheForm, ProvisionManualBeautyPrefix = ValidateFalseCarmeLimit
},
new
{
UseAdditionalAtlasConflict = DeployPrivateHoneyExtension, ProvisionManualBeautyPrefix = ValidateFalseCarmeLimit
},
};
this.CollapseCustomIocasteSession(new SignBasedEuantheDashboard()
{
DecodeLatestCopperCheckbox = PostMissingProteusBreakpoint,
SeeExecutableAlbiorixAllocation = IncludeEmptyPsamatheForm,
ActivateAlternativeAntimonyEvent = DeployPrivateHoneyExtension,
});
if (AttachAdditionalNileAllocation[0].UseAdditionalAtlasConflict == ValidateFalseCarmeLimit) this.SearchPrivateCharonList(AttachAdditionalNileAllocation[0].ProvisionManualBeautyPrefix);
if (AttachAdditionalNileAllocation[1].UseAdditionalAtlasConflict == ForceMissingEuantheUnit) this.SearchPrivateCharonList(AttachAdditionalNileAllocation[1].ProvisionManualBeautyPrefix);
if (AttachAdditionalNileAllocation[2].UseAdditionalAtlasConflict == ReferBasedHermippeFramework) this.SearchPrivateCharonList(AttachAdditionalNileAllocation[2].ProvisionManualBeautyPrefix);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static EncounterPreviousPeaceCommunication ArchiveAccessibleIridiumFollowing = new EncounterPreviousPeaceCommunication();
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int CompareIncompatibleParfaitDomain()
{
return ReloadVerboseKatyushaBranch() == 0 ? 1 : LaunchRemotePantaloniLine;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int CompressUndefinedErriapusThirdparty = -1;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int CancelOpenFlamingoObject = PassUnknownMimasMap.ModifyFreeUraniumOutput;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int ScheduleExecutableCallirrhoeDevelopment()
{
return OverrideFinalWaveBlock() == 0 ? 0 : ClearCurrentErinomeCase;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int ReloadVerboseKatyushaBranch()
{
return SelectVerboseMeitneriumSpecification() == 0 ? 1 : RefreshGenericHeartAuthor;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void ExtendInternalMoonExecution(int PostMissingProteusBreakpoint, int IncludeEmptyPsamatheForm)
{
this.ConfigureGeneralBlackPatch(PostMissingProteusBreakpoint, IncludeEmptyPsamatheForm, this.ScanMinimumFloraCapability());
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int LaunchRemotePantaloniLine;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void ConfigureGeneralBlackPatch(int PostMissingProteusBreakpoint, int IncludeEmptyPsamatheForm, int DeployPrivateHoneyExtension)
{
this.EmailPreferredSeaborgiumBuffer(PostMissingProteusBreakpoint, IncludeEmptyPsamatheForm, DeployPrivateHoneyExtension, this.UninstallUnavailableNamakaContainer().DecodeLatestCopperCheckbox, this.UninstallUnavailableNamakaContainer().SeeExecutableAlbiorixAllocation, this.UninstallUnavailableNamakaContainer().ActivateAlternativeAntimonyEvent);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int MatchNormalSulfurInspection;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int ConfigureAnonymousCallirrhoeSeparator = PassUnknownMimasMap.RetrieveFollowingDubniumRegistry;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int RefreshGenericHeartAuthor;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int SetExternalAstatineProfile()
{
return UploadTemporaryPhoebeBundle() - SynchronizeCurrentAitneSeparator;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static SignBasedEuantheDashboard PlayCorrectMetisExpression;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int HackFollowingPlutoniumProvision = -1;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static GeneratePreferredHyrrokkinRepresentation SaveAvailableSeleniumInstallation;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int PlayRemoteFerdinandCoordinate()
{
return OverrideOptionalSwordSocket() != 1 ? 1 : FindInlineKoreEditor;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int DistributeActiveEinsteiniumQuery()
{
return CompareIncompatibleParfaitDomain() == 1 ? 0 : SendGenericTaygeteFlag;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int OverrideFinalWaveBlock()
{
return DisableEqualLarissaInformation() - CompareNullNamakaClient;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static double AssertExternalMegacliteDefault = PassUnknownMimasMap.DuplicateMultipleEarthDevelopment;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static ScrollAccessibleRutherfordiumDashboard ReserveNextPhosphorusPath;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int ScanMinimumFloraCapability()
{
return AdjustCorrectIodineSection++;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int ScrollCleanFornjotSecurity;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int ClearCurrentErinomeCase;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int InvokeUndefinedNeptuniumTransition;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int NormalizeBinaryTitaniaWidth()
{
return AdjustCorrectIodineSection;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int FindVerboseAegirStep;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int CompleteMultipleBeautyFile;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void EncounterEqualSiarnaqModifier(int PostMissingProteusBreakpoint)
{
this.ExtendInternalMoonExecution(PostMissingProteusBreakpoint, this.ScanMinimumFloraCapability());
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static double ManageStandaloneDespinaContext = PassUnknownMimasMap.DuplicateMultipleEarthDevelopment;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int CreatePrivateGermaniumNote()
{
return ScheduleExecutableCallirrhoeDevelopment() != 1 ? 1 : ArchiveNestedPortiaUsername;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static bool DetermineEqualGoldConflict = false;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static ScrollAccessibleRutherfordiumDashboard ExecuteVirtualAoedeLicense;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static AdjustNativeParfaitInspection TouchExecutableBlackOperation;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int FindInlineKoreEditor;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int CompareNullNamakaClient;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int SynchronizeCurrentAitneSeparator;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static ScrollAccessibleRutherfordiumDashboard FilterAvailableCalibanBranch;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public class SignBasedEuantheDashboard
{
public int DecodeLatestCopperCheckbox;
public int SeeExecutableAlbiorixAllocation;
public int ActivateAlternativeAntimonyEvent;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static SignAvailablePhosphorusAccount TerminateExtraArielUse = new SignAvailablePhosphorusAccount();
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void RecordApplicableMoscoviumInstruction()
{
this.EncounterEqualSiarnaqModifier(this.ScanMinimumFloraCapability());
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int SelectVerboseMeitneriumSpecification()
{
return ImportUnnecessaryPeachConstraint() + ValidateMockMnemeCoordinate;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int AdjustCorrectIodineSection;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int UploadTemporaryPhoebeBundle()
{
return PassCorrectEurydomeScript;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static ParseCorrectSetebosPlaceholder DebugAccessibleTelluriumInterface = new ParseCorrectSetebosPlaceholder();
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void ClonePublicPaaliaqNotice(int ChooseCleanMercuryCache)
{
AdjustCorrectIodineSection = ChooseCleanMercuryCache;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static void StoreExternalScandiumBranch()
{
SuppressDedicatedHafniumChoice.SetUnexpectedMatadorSyntax.PerformInvalidFarbautiWidget = 0;
SuppressDedicatedHafniumChoice.RestartMissingHimaliaNavigation.PerformInvalidFarbautiWidget = 1;
SuppressDedicatedHafniumChoice.CloneMultipleSinopeInitialization.PerformInvalidFarbautiWidget = 2;
SuppressDedicatedHafniumChoice.RenameBasedSunsetPlaceholder.PerformInvalidFarbautiWidget = 3;
SuppressDedicatedHafniumChoice.DisableDynamicIodineHeader.PerformInvalidFarbautiWidget = 4;
SuppressDedicatedHafniumChoice.DeclareExecutableMarineFolder.PerformInvalidFarbautiWidget = 7;
SuppressDedicatedHafniumChoice.SanitizeFreeSamariumProvider.PerformInvalidFarbautiWidget = 5;
SuppressDedicatedHafniumChoice.RedirectFinalGoldLibrary.PerformInvalidFarbautiWidget = 8;
SuppressDedicatedHafniumChoice.RevertEmptyRutherfordiumConstraint.PerformInvalidFarbautiWidget = 6;
SuppressDedicatedHafniumChoice.ToggleDuplicateUmbrielInteger.PerformInvalidFarbautiWidget = 9;
SuppressDedicatedHafniumChoice.RecommendBasedScandiumImage.PerformInvalidFarbautiWidget = 10;
SuppressDedicatedHafniumChoice.NoteUnauthorizedJupiterBackup.PerformInvalidFarbautiWidget = 11;
SuppressDedicatedHafniumChoice.DescribeExtraGalateaLoop.PerformInvalidFarbautiWidget = 13;
SuppressDedicatedHafniumChoice.ZipMockPhobosCleanup.PerformInvalidFarbautiWidget = 12;
SuppressDedicatedHafniumChoice.SetUnexpectedMatadorSyntax.CancelExecutableLysitheaLine = DX.KEY_INPUT_DOWN;
SuppressDedicatedHafniumChoice.RestartMissingHimaliaNavigation.CancelExecutableLysitheaLine = DX.KEY_INPUT_LEFT;
SuppressDedicatedHafniumChoice.CloneMultipleSinopeInitialization.CancelExecutableLysitheaLine = DX.KEY_INPUT_RIGHT;
SuppressDedicatedHafniumChoice.RenameBasedSunsetPlaceholder.CancelExecutableLysitheaLine = DX.KEY_INPUT_UP;
SuppressDedicatedHafniumChoice.DisableDynamicIodineHeader.CancelExecutableLysitheaLine = DX.KEY_INPUT_Z;
SuppressDedicatedHafniumChoice.DeclareExecutableMarineFolder.CancelExecutableLysitheaLine = DX.KEY_INPUT_X;
SuppressDedicatedHafniumChoice.SanitizeFreeSamariumProvider.CancelExecutableLysitheaLine = DX.KEY_INPUT_C;
SuppressDedicatedHafniumChoice.RedirectFinalGoldLibrary.CancelExecutableLysitheaLine = DX.KEY_INPUT_V;
SuppressDedicatedHafniumChoice.RevertEmptyRutherfordiumConstraint.CancelExecutableLysitheaLine = DX.KEY_INPUT_A;
SuppressDedicatedHafniumChoice.ToggleDuplicateUmbrielInteger.CancelExecutableLysitheaLine = DX.KEY_INPUT_S;
SuppressDedicatedHafniumChoice.RecommendBasedScandiumImage.CancelExecutableLysitheaLine = DX.KEY_INPUT_D;
SuppressDedicatedHafniumChoice.NoteUnauthorizedJupiterBackup.CancelExecutableLysitheaLine = DX.KEY_INPUT_F;
SuppressDedicatedHafniumChoice.DescribeExtraGalateaLoop.CancelExecutableLysitheaLine = DX.KEY_INPUT_SPACE;
SuppressDedicatedHafniumChoice.ZipMockPhobosCleanup.CancelExecutableLysitheaLine = DX.KEY_INPUT_RETURN;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int DisableEqualLarissaInformation()
{
return SetExternalAstatineProfile() == 1 ? 0 : FindVerboseAegirStep;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int SendGenericTaygeteFlag;
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int ImportUnnecessaryPeachConstraint()
{
return PlayRemoteFerdinandCoordinate() != 1 ? 1 : InvokeUndefinedNeptuniumTransition;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public int OverrideOptionalSwordSocket()
{
return CreatePrivateGermaniumNote() + ScrollCleanFornjotSecurity;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void SearchPrivateCharonList(int CleanBasedSeleneSwitch)
{
if (CleanBasedSeleneSwitch != this.NormalizeBinaryTitaniaWidth())
this.ClonePublicPaaliaqNotice(CleanBasedSeleneSwitch);
else
this.EncounterEqualSiarnaqModifier(CleanBasedSeleneSwitch);
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public void CollapseCustomIocasteSession(SignBasedEuantheDashboard EditAnonymousHoneyDuration)
{
PlayCorrectMetisExpression = EditAnonymousHoneyDuration;
}
/// <summary>
/// Confused by ConfuserElsa
/// </summary>
public static int DefaultUndefinedNeptuniumFlag;
}
}
| 32.482456 | 348 | 0.771064 | [
"MIT"
] | soleil-taruto/Hatena | a20201226/Confused_02/tmpsol/Elsa20200001/AgreeIncompatibleErbiumConsole.cs | 14,814 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Tailwind.Traders.Profile.Api.DTOs;
namespace Tailwind.Traders.Profile.Api.Models
{
public class Profiles
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string ImageNameSmall { get; set; }
public string ImageNameMedium { get; set; }
public ProfileDto ToProfileDto(AppSettings settings) =>
new ProfileDto()
{
Id = this.Id,
Name = this.Name,
Address = this.Address,
Email = this.Email,
PhoneNumber = this.PhoneNumber,
ImageUrlSmall = $"{settings.ProfilesImageUrl}/{this.ImageNameSmall}",
ImageUrlMedium = $"{settings.ProfilesImageUrl}/{this.ImageNameMedium}"
};
}
}
| 32.1875 | 86 | 0.586408 | [
"MIT"
] | NileshGule/TailwindTraders-Backend | Source/Services/Tailwind.Traders.Profile.Api/Models/Profiles.cs | 1,032 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Caching;
using Orchard.Data;
using Orchard.Localization.Records;
namespace Orchard.Localization.Services {
public class DefaultCultureManager : ICultureManager {
private readonly IRepository<CultureRecord> _cultureRepository;
private readonly ISignals _signals;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly ICacheManager _cacheManager;
public DefaultCultureManager(
IRepository<CultureRecord> cultureRepository,
ISignals signals,
IWorkContextAccessor workContextAccessor,
ICacheManager cacheManager) {
_cultureRepository = cultureRepository;
_signals = signals;
_workContextAccessor = workContextAccessor;
_cacheManager = cacheManager;
}
public IEnumerable<string> ListCultures() {
return _cacheManager.Get("Cultures", true, context => {
context.Monitor(_signals.When("culturesChanged"));
return _cultureRepository.Table.Select(o => o.Culture).ToList();
});
}
public void AddCulture(string cultureName) {
if (!IsValidCulture(cultureName)) {
throw new ArgumentException("cultureName");
}
if (ListCultures().Any(culture => culture == cultureName)) {
return;
}
_cultureRepository.Create(new CultureRecord { Culture = cultureName });
_signals.Trigger("culturesChanged");
}
public void DeleteCulture(string cultureName) {
if (!IsValidCulture(cultureName)) {
throw new ArgumentException("cultureName");
}
if (ListCultures().Any(culture => culture == cultureName)) {
var culture = _cultureRepository.Get(cr => cr.Culture == cultureName);
_cultureRepository.Delete(culture);
_signals.Trigger("culturesChanged");
}
}
public string GetCurrentCulture(HttpContextBase requestContext) {
return _workContextAccessor.GetContext().CurrentCulture;
}
public CultureRecord GetCultureById(int id) {
return _cultureRepository.Get(id);
}
public CultureRecord GetCultureByName(string cultureName) {
return _cultureRepository.Get(cr => cr.Culture == cultureName);
}
public string GetSiteCulture() {
return _workContextAccessor.GetContext().CurrentSite == null ? null : _workContextAccessor.GetContext().CurrentSite.SiteCulture;
}
// "<languagecode2>" or
// "<languagecode2>-<country/regioncode2>" or
// "<languagecode2>-<scripttag>-<country/regioncode2>"
public bool IsValidCulture(string cultureName) {
var segments = cultureName.Split('-');
if (segments.Length == 0) {
return false;
}
if (segments.Length > 3) {
return false;
}
if (segments.Any(s => s.Length < 2)) {
return false;
}
return true;
}
}
}
| 33.323232 | 140 | 0.60291 | [
"BSD-3-Clause"
] | 1996dylanriley/Orchard | src/Orchard/Localization/Services/DefaultCultureManager.cs | 3,301 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pixel {
private Vector2 position;
private Color color;
private bool isCorner = true;
public Pixel(Vector2 position, Color color) {
this.position = position;
this.color = color;
}
public void GetConnectedPixels(PixelGrouper grouper, PixelSquare pixelSquare) {
List<Pixel> connectedPixels = new List<Pixel>();
Pixel foundPixel;
if(grouper.PixelMap.TryGetValue(position + new Vector2(-1, 0), out foundPixel))
connectedPixels.Add(foundPixel);
if(grouper.PixelMap.TryGetValue(position + new Vector2(1, 0), out foundPixel))
connectedPixels.Add(foundPixel);
if(grouper.PixelMap.TryGetValue(position + new Vector2(0, -1), out foundPixel))
connectedPixels.Add(foundPixel);
if(grouper.PixelMap.TryGetValue(position + new Vector2(0, 1), out foundPixel))
connectedPixels.Add(foundPixel);
pixelSquare.AddPixel(this);
this.color = pixelSquare.Color;
//Spread :P
if(connectedPixels.Count > 0) {
isCorner = connectedPixels.Count <= 2;
foreach(Pixel pixel in connectedPixels) {
if(!pixelSquare.colided(pixel.position))
pixel.GetConnectedPixels(grouper, pixelSquare);
}
}
}
public Vector2 Position { get { return this.position; } }
public Color Color { get { return this.color; } }
public bool IsCorner { get { return this.isCorner; } }
}
| 29.518519 | 87 | 0.640527 | [
"MIT"
] | TimBouwman/KlauterGame | admin/Ouput-KG/Assets/QRToMap/objects/Pixels/Pixel.cs | 1,596 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal class SyntaxDiffer
{
private const int InitialStackSize = 8;
private const int MaxSearchLength = 8;
private readonly Stack<SyntaxNodeOrToken> _oldNodes = new Stack<SyntaxNodeOrToken>(InitialStackSize);
private readonly Stack<SyntaxNodeOrToken> _newNodes = new Stack<SyntaxNodeOrToken>(InitialStackSize);
private readonly List<ChangeRecord> _changes = new List<ChangeRecord>();
private readonly TextSpan _oldSpan;
private readonly bool _computeNewText;
private readonly HashSet<GreenNode> _nodeSimilaritySet = new HashSet<GreenNode>();
private readonly HashSet<string> _tokenTextSimilaritySet = new HashSet<string>();
private SyntaxDiffer(SyntaxNode oldNode, SyntaxNode newNode, bool computeNewText)
{
_oldNodes.Push((SyntaxNodeOrToken)oldNode);
_newNodes.Push((SyntaxNodeOrToken)newNode);
_oldSpan = oldNode.FullSpan;
_computeNewText = computeNewText;
}
// return a set of text changes that when applied to the old document produces the new document
internal static IList<TextChange> GetTextChanges(SyntaxTree before, SyntaxTree after)
{
if (before == after)
{
return SpecializedCollections.EmptyList<TextChange>();
}
else if (before == null)
{
return new[] { new TextChange(new TextSpan(0, 0), after.GetText().ToString()) };
}
else if (after == null)
{
throw new ArgumentNullException(nameof(after));
}
else
{
return GetTextChanges(before.GetRoot(), after.GetRoot());
}
}
// return a set of text changes that when applied to the old document produces the new document
internal static IList<TextChange> GetTextChanges(SyntaxNode oldNode, SyntaxNode newNode)
{
return new SyntaxDiffer(oldNode, newNode, computeNewText: true).ComputeTextChangesFromOld();
}
private IList<TextChange> ComputeTextChangesFromOld()
{
this.ComputeChangeRecords();
var reducedChanges = this.ReduceChanges(_changes);
return reducedChanges.Select(c => new TextChange(c.Range.Span, c.NewText)).ToList();
}
internal static IList<TextSpan> GetPossiblyDifferentTextSpans(SyntaxTree before, SyntaxTree after)
{
if (before == after)
{
// They're the same, so nothing changed.
return SpecializedCollections.EmptyList<TextSpan>();
}
else if (before == null)
{
// The tree is completely new, everything has changed.
return new[] { new TextSpan(0, after.GetText().Length) };
}
else if (after == null)
{
throw new ArgumentNullException(nameof(after));
}
else
{
return GetPossiblyDifferentTextSpans(before.GetRoot(), after.GetRoot());
}
}
// return which spans of text in the new document are possibly different than text in the old document
internal static IList<TextSpan> GetPossiblyDifferentTextSpans(SyntaxNode oldNode, SyntaxNode newNode)
{
return new SyntaxDiffer(oldNode, newNode, computeNewText: false).ComputeSpansInNew();
}
private IList<TextSpan> ComputeSpansInNew()
{
this.ComputeChangeRecords();
var reducedChanges = ReduceChanges(_changes);
// this algorithm assumes changes are in non-overlapping document order
var newSpans = new List<TextSpan>();
int delta = 0; // difference between old & new start positions
foreach (var change in reducedChanges)
{
if (change.Range.NewLength > 0) // delete-only ranges cannot be expressed as part of new text
{
int start = change.Range.Span.Start + delta;
newSpans.Add(new TextSpan(start, change.Range.NewLength));
}
delta += change.Range.NewLength - change.Range.Span.Length;
}
return newSpans;
}
private void ComputeChangeRecords()
{
while (true)
{
// first check end-of-lists termination cases...
if (_newNodes.Count == 0)
{
// remaining old nodes are deleted
if (_oldNodes.Count > 0)
{
RecordDeleteOld(_oldNodes.Count);
}
break;
}
else if (_oldNodes.Count == 0)
{
// remaining nodes were inserted
if (_newNodes.Count > 0)
{
RecordInsertNew(_newNodes.Count);
}
break;
}
else
{
var action = GetNextAction();
switch (action.Operation)
{
case DiffOp.SkipBoth:
RemoveFirst(_oldNodes, action.Count);
RemoveFirst(_newNodes, action.Count);
break;
case DiffOp.ReduceOld:
ReplaceFirstWithChildren(_oldNodes);
break;
case DiffOp.ReduceNew:
ReplaceFirstWithChildren(_newNodes);
break;
case DiffOp.ReduceBoth:
ReplaceFirstWithChildren(_oldNodes);
ReplaceFirstWithChildren(_newNodes);
break;
case DiffOp.InsertNew:
RecordInsertNew(action.Count);
break;
case DiffOp.DeleteOld:
RecordDeleteOld(action.Count);
break;
case DiffOp.ReplaceOldWithNew:
RecordReplaceOldWithNew(action.Count, action.Count);
break;
}
}
}
}
private enum DiffOp
{
None = 0,
SkipBoth,
ReduceOld,
ReduceNew,
ReduceBoth,
InsertNew,
DeleteOld,
ReplaceOldWithNew
}
private struct DiffAction
{
public readonly DiffOp Operation;
public readonly int Count;
public DiffAction(DiffOp operation, int count)
{
System.Diagnostics.Debug.Assert(count >= 0);
this.Operation = operation;
this.Count = count;
}
}
private DiffAction GetNextAction()
{
bool oldIsToken = _oldNodes.Peek().IsToken;
bool newIsToken = _newNodes.Peek().IsToken;
// look for exact match
int indexOfOldInNew;
int similarityOfOldInNew;
int indexOfNewInOld;
int similarityOfNewInOld;
FindBestMatch(_newNodes, _oldNodes.Peek(), out indexOfOldInNew, out similarityOfOldInNew);
FindBestMatch(_oldNodes, _newNodes.Peek(), out indexOfNewInOld, out similarityOfNewInOld);
if (indexOfOldInNew == 0 && indexOfNewInOld == 0)
{
// both first nodes are somewhat similar to each other
if (AreIdentical(_oldNodes.Peek(), _newNodes.Peek()))
{
// they are identical, so just skip over both first new and old nodes.
return new DiffAction(DiffOp.SkipBoth, 1);
}
else if (!oldIsToken && !newIsToken)
{
// neither are tokens, so replace each first node with its child nodes
return new DiffAction(DiffOp.ReduceBoth, 1);
}
else
{
// otherwise just claim one's text replaces the other..
// NOTE: possibly we can improve this by reducing the side that may not be token?
return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
}
}
else if (indexOfOldInNew >= 0 || indexOfNewInOld >= 0)
{
// either the first old-node is similar to some node in the new-list or
// the first new-node is similar to some node in the old-list
if (indexOfNewInOld < 0 || similarityOfOldInNew >= similarityOfNewInOld)
{
// either there is no match for the first new-node in the old-list or the
// the similarity of the first old-node in the new-list is much greater
// if we find a match for the old node in the new list, that probably means nodes were inserted before it.
if (indexOfOldInNew > 0)
{
// look ahead to see if the old node also appears again later in its own list
int indexOfOldInOld;
int similarityOfOldInOld;
FindBestMatch(_oldNodes, _oldNodes.Peek(), out indexOfOldInOld, out similarityOfOldInOld, 1);
// don't declare an insert if the node also appeared later in the original list
var oldHasSimilarSibling = (indexOfOldInOld >= 1 && similarityOfOldInOld >= similarityOfOldInNew);
if (!oldHasSimilarSibling)
{
return new DiffAction(DiffOp.InsertNew, indexOfOldInNew);
}
}
if (!newIsToken)
{
if (AreSimilar(_oldNodes.Peek(), _newNodes.Peek()))
{
return new DiffAction(DiffOp.ReduceBoth, 1);
}
else
{
return new DiffAction(DiffOp.ReduceNew, 1);
}
}
else
{
return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
}
}
else
{
if (indexOfNewInOld > 0)
{
return new DiffAction(DiffOp.DeleteOld, indexOfNewInOld);
}
else if (!oldIsToken)
{
if (AreSimilar(_oldNodes.Peek(), _newNodes.Peek()))
{
return new DiffAction(DiffOp.ReduceBoth, 1);
}
else
{
return new DiffAction(DiffOp.ReduceOld, 1);
}
}
else
{
return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
}
}
}
else
{
// no similarities between first node of old-list in new-list or between first new-node in old-list
if (!oldIsToken && !newIsToken)
{
// check similarity anyway
var sim = GetSimilarity(_oldNodes.Peek(), _newNodes.Peek());
if (sim >= Math.Max(_oldNodes.Peek().FullSpan.Length, _newNodes.Peek().FullSpan.Length))
{
return new DiffAction(DiffOp.ReduceBoth, 1);
}
}
return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
}
}
private static void ReplaceFirstWithChildren(Stack<SyntaxNodeOrToken> stack)
{
var node = stack.Pop();
int c = 0;
var children = new SyntaxNodeOrToken[node.ChildNodesAndTokens().Count];
foreach (var child in node.ChildNodesAndTokens())
{
if (child.FullSpan.Length > 0)
{
children[c] = child;
c++;
}
}
for (int i = c - 1; i >= 0; i--)
{
stack.Push(children[i]);
}
}
private void FindBestMatch(Stack<SyntaxNodeOrToken> stack, SyntaxNodeOrToken node, out int index, out int similarity, int startIndex = 0)
{
index = -1;
similarity = -1;
int i = 0;
foreach (var stackNode in stack)
{
if (i >= MaxSearchLength)
{
break;
}
if (i >= startIndex)
{
if (AreIdentical(stackNode, node))
{
var sim = node.FullSpan.Length;
if (sim > similarity)
{
index = i;
similarity = sim;
return;
}
}
else if (AreSimilar(stackNode, node))
{
var sim = GetSimilarity(stackNode, node);
// Are these really the same? This may be expensive so only check this if
// similarity is rated equal to them being identical.
if (sim == node.FullSpan.Length && node.IsToken)
{
if (stackNode.ToFullString() == node.ToFullString())
{
index = i;
similarity = sim;
return;
}
}
if (sim > similarity)
{
index = i;
similarity = sim;
}
}
else
{
// check one level deep inside list node's children
int j = 0;
foreach (var child in stackNode.ChildNodesAndTokens())
{
if (j >= MaxSearchLength)
{
break;
}
j++;
if (AreIdentical(child, node))
{
index = i;
similarity = node.FullSpan.Length;
return;
}
else if (AreSimilar(child, node))
{
var sim = GetSimilarity(child, node);
if (sim > similarity)
{
index = i;
similarity = sim;
}
}
}
}
}
i++;
}
}
private int GetSimilarity(SyntaxNodeOrToken node1, SyntaxNodeOrToken node2)
{
// count the characters in the common/identical nodes
int w = 0;
_nodeSimilaritySet.Clear();
_tokenTextSimilaritySet.Clear();
if (node1.IsToken && node2.IsToken)
{
var text1 = node1.ToString();
var text2 = node2.ToString();
if (text1 == text2)
{
// main text of token is the same
w += text1.Length;
}
foreach (var tr in node1.GetLeadingTrivia())
{
_nodeSimilaritySet.Add(tr.UnderlyingNode);
}
foreach (var tr in node1.GetTrailingTrivia())
{
_nodeSimilaritySet.Add(tr.UnderlyingNode);
}
foreach (var tr in node2.GetLeadingTrivia())
{
if (_nodeSimilaritySet.Contains(tr.UnderlyingNode))
{
w += tr.FullSpan.Length;
}
}
foreach (var tr in node2.GetTrailingTrivia())
{
if (_nodeSimilaritySet.Contains(tr.UnderlyingNode))
{
w += tr.FullSpan.Length;
}
}
}
else
{
foreach (var n1 in node1.ChildNodesAndTokens())
{
_nodeSimilaritySet.Add(n1.UnderlyingNode);
if (n1.IsToken)
{
_tokenTextSimilaritySet.Add(n1.ToString());
}
}
foreach (var n2 in node2.ChildNodesAndTokens())
{
if (_nodeSimilaritySet.Contains(n2.UnderlyingNode))
{
w += n2.FullSpan.Length;
}
else if (n2.IsToken)
{
var tokenText = n2.ToString();
if (_tokenTextSimilaritySet.Contains(tokenText))
{
w += tokenText.Length;
}
}
}
}
return w;
}
private static bool AreIdentical(SyntaxNodeOrToken node1, SyntaxNodeOrToken node2)
{
return node1.UnderlyingNode == node2.UnderlyingNode;
}
private static bool AreSimilar(SyntaxNodeOrToken node1, SyntaxNodeOrToken node2)
{
return node1.RawKind == node2.RawKind;
}
private struct ChangeRecord
{
public readonly TextChangeRange Range;
public readonly Stack<SyntaxNodeOrToken> OldNodes;
public readonly Stack<SyntaxNodeOrToken> NewNodes;
internal ChangeRecord(TextChangeRange range, Stack<SyntaxNodeOrToken> oldNodes, Stack<SyntaxNodeOrToken> newNodes)
{
this.Range = range;
this.OldNodes = oldNodes;
this.NewNodes = newNodes;
}
}
private void RecordDeleteOld(int oldNodeCount)
{
var oldSpan = GetSpan(_oldNodes, 0, oldNodeCount);
var removedNodes = CopyFirst(_oldNodes, oldNodeCount);
RemoveFirst(_oldNodes, oldNodeCount);
RecordChange(new ChangeRecord(new TextChangeRange(oldSpan, 0), removedNodes, null));
}
private void RecordReplaceOldWithNew(int oldNodeCount, int newNodeCount)
{
var oldSpan = GetSpan(_oldNodes, 0, oldNodeCount);
var removedNodes = CopyFirst(_oldNodes, oldNodeCount);
RemoveFirst(_oldNodes, oldNodeCount);
var newSpan = GetSpan(_newNodes, 0, newNodeCount);
var insertedNodes = CopyFirst(_newNodes, newNodeCount);
RemoveFirst(_newNodes, newNodeCount);
RecordChange(new ChangeRecord(new TextChangeRange(oldSpan, newSpan.Length), removedNodes, insertedNodes));
}
private void RecordInsertNew(int newNodeCount)
{
var newSpan = GetSpan(_newNodes, 0, newNodeCount);
var insertedNodes = CopyFirst(_newNodes, newNodeCount);
RemoveFirst(_newNodes, newNodeCount);
int start = _oldNodes.Count > 0 ? _oldNodes.Peek().Position : _oldSpan.End;
RecordChange(new ChangeRecord(new TextChangeRange(new TextSpan(start, 0), newSpan.Length), null, insertedNodes));
}
private void RecordChange(ChangeRecord change)
{
if (_changes.Count > 0)
{
var last = _changes[_changes.Count - 1];
if (last.Range.Span.End == change.Range.Span.Start)
{
// merge changes...
_changes[_changes.Count - 1] = new ChangeRecord(
new TextChangeRange(new TextSpan(last.Range.Span.Start, last.Range.Span.Length + change.Range.Span.Length), last.Range.NewLength + change.Range.NewLength),
Combine(last.OldNodes, change.OldNodes),
Combine(last.NewNodes, change.NewNodes));
return;
}
Debug.Assert(change.Range.Span.Start >= last.Range.Span.End);
}
_changes.Add(change);
}
private static TextSpan GetSpan(Stack<SyntaxNodeOrToken> stack, int first, int length)
{
int start = -1, end = -1, i = 0;
foreach (var n in stack)
{
if (i == first)
{
start = n.Position;
}
if (i == first + length - 1)
{
end = n.EndPosition;
break;
}
i++;
}
Debug.Assert(start >= 0);
Debug.Assert(end >= 0);
return TextSpan.FromBounds(start, end);
}
private static Stack<SyntaxNodeOrToken> Combine(Stack<SyntaxNodeOrToken> first, Stack<SyntaxNodeOrToken> next)
{
if (first == null)
{
return next;
}
if (next == null)
{
return first;
}
var nodes = ToArray(first, first.Count);
for (int i = 0; i < nodes.Length; i++)
{
next.Push(nodes[i]);
}
return next;
}
private static Stack<SyntaxNodeOrToken> CopyFirst(Stack<SyntaxNodeOrToken> stack, int n)
{
if (n == 0)
{
return null;
}
var nodes = ToArray(stack, n);
var newStack = new Stack<SyntaxNodeOrToken>(nodes);
return newStack;
}
private static SyntaxNodeOrToken[] ToArray(Stack<SyntaxNodeOrToken> stack, int n)
{
var nodes = new SyntaxNodeOrToken[n];
int i = n - 1;
foreach (var node in stack)
{
nodes[i] = node;
i--;
if (i < 0)
{
break;
}
}
return nodes;
}
private static void RemoveFirst(Stack<SyntaxNodeOrToken> stack, int count)
{
for (int i = 0; i < count; ++i)
{
stack.Pop();
}
}
private struct ChangeRangeWithText
{
public readonly TextChangeRange Range;
public readonly string NewText;
public ChangeRangeWithText(TextChangeRange range, string newText)
{
this.Range = range;
this.NewText = newText;
}
}
private List<ChangeRangeWithText> ReduceChanges(List<ChangeRecord> changeRecords)
{
var textChanges = new List<ChangeRangeWithText>(changeRecords.Count);
var oldText = new StringBuilder();
var newText = new StringBuilder();
foreach (var cr in changeRecords)
{
// try to reduce change range by finding common characters
if (cr.Range.Span.Length > 0 && cr.Range.NewLength > 0)
{
var range = cr.Range;
CopyText(cr.OldNodes, oldText);
CopyText(cr.NewNodes, newText);
int commonLeadingCount;
int commonTrailingCount;
GetCommonEdgeLengths(oldText, newText, out commonLeadingCount, out commonTrailingCount);
// did we have any common leading or trailing characters between the strings?
if (commonLeadingCount > 0 || commonTrailingCount > 0)
{
range = new TextChangeRange(
new TextSpan(range.Span.Start + commonLeadingCount, range.Span.Length - (commonLeadingCount + commonTrailingCount)),
range.NewLength - (commonLeadingCount + commonTrailingCount));
if (commonTrailingCount > 0)
{
newText.Remove(newText.Length - commonTrailingCount, commonTrailingCount);
}
if (commonLeadingCount > 0)
{
newText.Remove(0, commonLeadingCount);
}
}
// only include adjusted change if there is still a change
if (range.Span.Length > 0 || range.NewLength > 0)
{
textChanges.Add(new ChangeRangeWithText(range, _computeNewText ? newText.ToString() : null));
}
}
else
{
// pure inserts and deletes
textChanges.Add(new ChangeRangeWithText(cr.Range, _computeNewText ? GetText(cr.NewNodes) : null));
}
}
return textChanges;
}
private static void GetCommonEdgeLengths(StringBuilder oldText, StringBuilder newText, out int commonLeadingCount, out int commonTrailingCount)
{
int maxChars = Math.Min(oldText.Length, newText.Length);
commonLeadingCount = 0;
for (; commonLeadingCount < maxChars; commonLeadingCount++)
{
if (oldText[commonLeadingCount] != newText[commonLeadingCount])
{
break;
}
}
// don't double count the chars we matched at the start of the strings
maxChars = maxChars - commonLeadingCount;
commonTrailingCount = 0;
for (; commonTrailingCount < maxChars; commonTrailingCount++)
{
if (oldText[oldText.Length - commonTrailingCount - 1] != newText[newText.Length - commonTrailingCount - 1])
{
break;
}
}
}
private static string GetText(Stack<SyntaxNodeOrToken> stack)
{
if (stack == null || stack.Count == 0)
{
return string.Empty;
}
var span = GetSpan(stack, 0, stack.Count);
var builder = new StringBuilder(span.Length);
CopyText(stack, builder);
return builder.ToString();
}
private static void CopyText(Stack<SyntaxNodeOrToken> stack, StringBuilder builder)
{
builder.Length = 0;
if (stack != null && stack.Count > 0)
{
var writer = new System.IO.StringWriter(builder);
foreach (var n in stack)
{
n.WriteTo(writer);
}
writer.Flush();
}
}
}
}
| 36.453846 | 179 | 0.46979 | [
"Apache-2.0"
] | 0x53A/roslyn | src/Compilers/Core/Portable/Syntax/SyntaxDiffer.cs | 28,436 | C# |
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using Xenko.Core.Presentation.Behaviors;
using Xceed.Wpf.DataGrid;
namespace Xenko.Core.Assets.Editor.View.Behaviors
{
public class XceedDataGridBindableSelectedItemsBehavior : BindableSelectedItemsBehavior<DataGridControl>
{
protected override void OnAttached()
{
SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems;
AssociatedObject.SelectionChanged += XceedDataGridSelectionChanged;
base.OnAttached();
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= XceedDataGridSelectionChanged;
SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems;
}
protected override void ScrollIntoView(object dataItem)
{
AssociatedObject.BringItemIntoView(dataItem);
}
private void XceedDataGridSelectionChanged(object sender, DataGridSelectionChangedEventArgs e)
{
foreach (var selectionInfo in e.SelectionInfos)
{
ControlSelectionChanged(selectionInfo.AddedItems, selectionInfo.RemovedItems);
}
}
}
}
| 36.512821 | 114 | 0.691011 | [
"MIT"
] | Aminator/xenko | sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs | 1,424 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.HealthcareApis
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
/// <summary>
/// Azure Healthcare APIs Client
/// </summary>
public partial interface IHealthcareApisManagementClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// The subscription identifier.
/// </summary>
string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
string ApiVersion { get; }
/// <summary>
/// The preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default
/// value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When
/// set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IServicesOperations.
/// </summary>
IServicesOperations Services { get; }
/// <summary>
/// Gets the IOperations.
/// </summary>
IOperations Operations { get; }
/// <summary>
/// Gets the IOperationResultsOperations.
/// </summary>
IOperationResultsOperations OperationResults { get; }
/// <summary>
/// Gets the IPrivateEndpointConnectionsOperations.
/// </summary>
IPrivateEndpointConnectionsOperations PrivateEndpointConnections { get; }
/// <summary>
/// Gets the IPrivateLinkResourcesOperations.
/// </summary>
IPrivateLinkResourcesOperations PrivateLinkResources { get; }
}
}
| 30.111111 | 81 | 0.597786 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/healthcareapis/Microsoft.Azure.Management.HealthcareApis/src/Generated/IHealthcareApisManagementClient.cs | 2,981 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayFinancialnetAuthPaymentNotifyResponse.
/// </summary>
public class AlipayFinancialnetAuthPaymentNotifyResponse : AlipayResponse
{
/// <summary>
/// 响应结果码
/// </summary>
[JsonPropertyName("result_code")]
public string ResultCode { get; set; }
/// <summary>
/// 响应结果描述
/// </summary>
[JsonPropertyName("result_desc")]
public string ResultDesc { get; set; }
/// <summary>
/// 业务结果是否成功
/// </summary>
[JsonPropertyName("success")]
public string Success { get; set; }
}
}
| 24.931034 | 77 | 0.573997 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayFinancialnetAuthPaymentNotifyResponse.cs | 763 | C# |
using JobToolkit.DBRepository;
using ORMToolkit.Core;
using System;
using System.Runtime.Serialization;
namespace JobToolkit.Oracle
{
public class OracleJobRepository : DBJobRepository
{
public OracleJobRepository(string connectionString)
: base(new DataManagerNoConfilict(connectionString, new ORMToolkit.OracleOdpManaged.OracleOdpManagedDataProviderFactory()))
{
OrmToolkitSettings.ObjectFactory = new ORMToolkit.Core.Factories.ObjectFactory2();
}
public OracleJobRepository(string connectionString, IFormatter formatter)
: base(new DataManagerNoConfilict(connectionString, new ORMToolkit.OracleOdpManaged.OracleOdpManagedDataProviderFactory()), formatter)
{
OrmToolkitSettings.ObjectFactory = new ORMToolkit.Core.Factories.ObjectFactory2();
}
}
}
| 37.434783 | 146 | 0.743322 | [
"MIT"
] | InfoTechBridge/JobToolkit | JobToolkit.Oracle/OracleJobRepository.cs | 863 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2021 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
// 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.
using NUnit.Framework;
[assembly: AssemblyTitle("YAF.Tests.UserTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("YAF.Tests.UserTests")]
[assembly: AssemblyCompany("YAF.NET")]
[assembly: AssemblyCopyright("Copyright © Yet Another Forum.NET")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Apartment(ApartmentState.STA)]
// 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("b79415c9-f3c6-48a3-aba4-7e0e4d783ba7")] | 41.411765 | 85 | 0.745265 | [
"Apache-2.0"
] | YAFNET/YAFNET-UnitTests | YAF.UnitTests/YAF.Tests.UserTests/Properties/AssemblyInfo.cs | 2,116 | C# |
// MIT License
// Copyright (c) 2016 Geometry Gym Pty Ltd
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Reflection;
using System.IO;
using System.ComponentModel;
using System.Linq;
using GeometryGym.STEP;
namespace GeometryGym.Ifc
{
public partial class IfcUnitaryControlElement : IfcDistributionControlElement //IFC4
{
protected override string BuildStringSTEP(ReleaseVersion release) { return base.BuildStringSTEP(release) + (release < ReleaseVersion.IFC4 ? "" : (mPredefinedType == IfcUnitaryControlElementTypeEnum.NOTDEFINED ? ",$" : ",." + mPredefinedType.ToString() + ".")); }
internal override void parse(string str, ref int pos, ReleaseVersion release, int len, ConcurrentDictionary<int,BaseClassIfc> dictionary)
{
base.parse(str, ref pos, release, len, dictionary);
string s = ParserSTEP.StripField(str, ref pos, len);
if (s.StartsWith("."))
Enum.TryParse<IfcUnitaryControlElementTypeEnum>(s.Replace(".", ""), true, out mPredefinedType);
}
}
public partial class IfcUnitaryControlElementType : IfcDistributionControlElementType
{
protected override string BuildStringSTEP(ReleaseVersion release) { return base.BuildStringSTEP(release) + ",." + mPredefinedType.ToString() + "."; }
internal override void parse(string str, ref int pos, ReleaseVersion release, int len, ConcurrentDictionary<int,BaseClassIfc> dictionary)
{
base.parse(str, ref pos, release, len, dictionary);
string s = ParserSTEP.StripField(str, ref pos, len);
if (s.StartsWith("."))
Enum.TryParse<IfcUnitaryControlElementTypeEnum>(s.Replace(".", ""), true, out mPredefinedType);
}
}
public partial class IfcUnitaryEquipment : IfcEnergyConversionDevice //IFC4
{
protected override string BuildStringSTEP(ReleaseVersion release) { return base.BuildStringSTEP(release) + (release < ReleaseVersion.IFC4 ? "" : (mPredefinedType == IfcUnitaryEquipmentTypeEnum.NOTDEFINED ? ",$" : ",." + mPredefinedType.ToString() + ".")); }
internal override void parse(string str, ref int pos, ReleaseVersion release, int len, ConcurrentDictionary<int,BaseClassIfc> dictionary)
{
base.parse(str, ref pos, release, len, dictionary);
string s = ParserSTEP.StripField(str, ref pos, len);
if (s.StartsWith("."))
Enum.TryParse<IfcUnitaryEquipmentTypeEnum>(s.Replace(".", ""), true, out mPredefinedType);
}
}
public partial class IfcUnitaryEquipmentType : IfcEnergyConversionDeviceType
{
protected override string BuildStringSTEP(ReleaseVersion release) { return base.BuildStringSTEP(release) + ",." + mPredefinedType.ToString() + "."; }
internal override void parse(string str, ref int pos, ReleaseVersion release, int len, ConcurrentDictionary<int,BaseClassIfc> dictionary)
{
base.parse(str, ref pos, release, len, dictionary);
string s = ParserSTEP.StripField(str, ref pos, len);
if (s.StartsWith("."))
Enum.TryParse<IfcUnitaryEquipmentTypeEnum>(s.Replace(".", ""), true, out mPredefinedType);
}
}
public partial class IfcUnitAssignment : BaseClassIfc
{
protected override string BuildStringSTEP(ReleaseVersion release) { return "(#" + string.Join(",#", mUnits.ConvertAll(x=>x.Index)) + ")"; }
internal override void parse(string str, ref int pos, ReleaseVersion release, int len, ConcurrentDictionary<int,BaseClassIfc> dictionary) { Units.AddRange(ParserSTEP.StripListLink(str, ref pos, len).ConvertAll(x=>Database[x] as IfcUnit)); }
}
public partial class IfcUShapeProfileDef : IfcParameterizedProfileDef
{
protected override string BuildStringSTEP(ReleaseVersion release) { return base.BuildStringSTEP(release) + "," + ParserSTEP.DoubleToString(mDepth) + "," + ParserSTEP.DoubleToString(mFlangeWidth) + "," + ParserSTEP.DoubleToString(mWebThickness) + "," + ParserSTEP.DoubleToString(mFlangeThickness) + "," + ParserSTEP.DoubleOptionalToString(mFilletRadius) + "," + ParserSTEP.DoubleOptionalToString(mEdgeRadius) + "," + ParserSTEP.DoubleOptionalToString(mFlangeSlope) + (release < ReleaseVersion.IFC4 ? "," + ParserSTEP.DoubleOptionalToString(mCentreOfGravityInX) : ""); }
internal override void parse(string str, ref int pos, ReleaseVersion release, int len, ConcurrentDictionary<int,BaseClassIfc> dictionary)
{
base.parse(str, ref pos, release, len, dictionary);
mDepth = ParserSTEP.StripDouble(str, ref pos, len);
mFlangeWidth = ParserSTEP.StripDouble(str, ref pos, len);
mWebThickness = ParserSTEP.StripDouble(str, ref pos, len);
mFlangeThickness = ParserSTEP.StripDouble(str, ref pos, len);
mFilletRadius = ParserSTEP.StripDouble(str, ref pos, len);
mEdgeRadius = ParserSTEP.StripDouble(str, ref pos, len);
mFlangeSlope = ParserSTEP.StripDouble(str, ref pos, len);
if(release < ReleaseVersion.IFC4)
mCentreOfGravityInX = ParserSTEP.StripDouble(str, ref pos, len);
}
}
}
| 60.171717 | 570 | 0.755917 | [
"MIT"
] | jmirtsch/GeometryGymIFC | Core/IFC/STEP/IFC U STEP.cs | 5,957 | C# |
using System;
using System.Collections.Concurrent;
using System.Linq;
using Jasily.FunctionInvoker.ArgumentsResolvers;
using JetBrains.Annotations;
namespace Jasily.Awaitablify.Internal
{
internal class AwaitableAdapterResolver
{
private readonly Func<Type, Lazy<IAwaitableAdapter>> _factory;
private readonly ConcurrentDictionary<Type, Lazy<IAwaitableAdapter>> _adapters =
new ConcurrentDictionary<Type, Lazy<IAwaitableAdapter>>();
private readonly FunctionInvokerResolver _functionInvokerResolver = new FunctionInvokerResolver();
private readonly AwaitableInfoResolver _awaitableInfoResolver = new AwaitableInfoResolver();
public AwaitableAdapterResolver()
{
this._factory = this.CreateLazy;
}
[NotNull]
public IAwaitableAdapter Resolve([CanBeNull] Type type)
{
if (type == null) return NonAwaitableAdapter.Instance;
return this._adapters.GetOrAdd(type, this._factory).Value;
}
private Lazy<IAwaitableAdapter> CreateLazy(Type type)
{
return new Lazy<IAwaitableAdapter>(() =>
{
var info = this._awaitableInfoResolver.Resolve(type);
if (info == null) return NonAwaitableAdapter.Instance;
var resultType = info.ResultType;
var closedType = resultType == typeof(void)
? typeof(VoidAwaitableAdapter<,>).MakeGenericType(type, info.AwaiterInfo.TypeInfo)
: typeof(TypedAwaitableAdapter<,,>).MakeGenericType(type, info.AwaiterInfo.TypeInfo, resultType);
return (IAwaitableAdapter)this._functionInvokerResolver.Resolve(closedType.GetConstructors().Single())
.Invoke(new object[] { info, this._functionInvokerResolver });
});
}
}
} | 39.978723 | 118 | 0.662054 | [
"MIT"
] | Jasily/jasily.awaitablify-csharp | Jasily.Awaitablify/Internal/AwaitableAdapterResolver.cs | 1,881 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using RimWorld;
using UnityEngine;
using FertilityMapMode.Coloring;
namespace FertilityMapMode
{
public static class FertilityDrawer
{
private static List<Thing> fertilityCountedThings = new List<Thing>();
private static Coloring.Gradient ColorGradient = GetColorGradient();
private static Coloring.Gradient GetColorGradient()
{
var gradient = new Coloring.Gradient();
var colorKeys = new SortedDictionary<float, Color>
{
{ 0.0f, Color.grey },
// orange/brown
{ 0.7f, new Color(0.6f, 0.5f, 0.0f) },
// bland green
{ 1.0f, new Color(0.1f, 0.6f, 0.1f) },
{ 1.4f, Color.green },
// For modded fertility levels (highest vanilla=1.4)
{ 2.5f, Color.cyan }
};
var alphaKeys = new SortedDictionary<float, float>
{
{ 0.0f, 1.0f },
{ 1.0f, 1.0f }
};
gradient.AddKeys(colorKeys, alphaKeys);
return gradient;
}
public static void FertilityDrawerOnGUI()
{
if (Event.current.type != EventType.Repaint || !FertilityDrawer.ShouldShow())
{
return;
}
FertilityDrawer.DrawFertilityAroundMouse();
}
private static bool ShouldShow()
{
return Find.PlaySettings.showFertilityOverlay && !Mouse.IsInputBlockedNow && UI.MouseCell().InBounds(Find.CurrentMap) && !UI.MouseCell().Fogged(Find.CurrentMap);
}
private static void DrawFertilityAroundMouse()
{
if (!Find.PlaySettings.showFertilityOverlay)
{
return;
}
// Prevent overlap with beauty display
if (Find.PlaySettings.showBeauty)
{
return;
}
FertilityUtility.FillFertilityRelevantCells(UI.MouseCell(), Find.CurrentMap);
foreach (var cell in FertilityUtility.fertilityRelevantCells)
{
float num = FertilityUtility.CellFertility(cell, Find.CurrentMap, FertilityDrawer.fertilityCountedThings);
if (num != 0f)
{
Vector3 v = GenMapUI.LabelDrawPosFor(cell);
GenMapUI.DrawThingLabel(v, num.ToString("n1"), FertilityDrawer.FertilityColor(num, 1.4f));
}
}
FertilityDrawer.fertilityCountedThings.Clear();
}
public static Color FertilityColor(float fertility, float scale)
{
var color = ColorGradient.Evaluate(fertility);
return color;
}
}
}
| 23.947368 | 164 | 0.694505 | [
"MIT"
] | SaucyPigeon/RW_ShowFertility | Source/FertilityMapMode/FertilityMapMode-RW1.1/FertilityDrawer.cs | 2,277 | C# |
using UnityEngine;
using System.Collections;
public class Rotator : MonoBehaviour {
// Update is called once per frame
void Update ()
{
transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime);
}
} | 19.181818 | 63 | 0.706161 | [
"MIT"
] | rahatm1/learning-unity | Roll a Ball/Assets/Scripts/Rotator.cs | 213 | C# |
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using HttpMethodConstraint = System.Web.Http.Routing.HttpMethodConstraint;
namespace EventEmitter.Api
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 26.375 | 99 | 0.593997 | [
"MIT"
] | Stelmashenko-A/EventEmitter | EventEmitter.Api/App_Start/RouteConfig.cs | 635 | C# |
// Generated by UblXml2CSharp
using System.Xml;
using UblLarsen.Ubl2;
using UblLarsen.Ubl2.Cac;
using UblLarsen.Ubl2.Ext;
using UblLarsen.Ubl2.Udt;
namespace UblLarsen.Test.UblClass
{
internal class UBLOrderCancellation21Example
{
public static OrderCancellationType Create()
{
var doc = new OrderCancellationType
{
UBLVersionID = "2.1",
CustomizationID = "urn:www.cenbii.eu:transaction:biicoretrdmXYZ:ver1.0",
ProfileID = new IdentifierType
{
schemeAgencyID = "BII",
schemeID = "Profile",
Value = "urn:www.cenbii.eu:profile:BIIXYZ:ver1.0"
},
ID = "7",
IssueDate = "2010-01-21",
IssueTime = "12:30:00",
CancellationNote = new TextType[]
{
new TextType
{
Value = "With reference to phone call"
}
},
OrderReference = new OrderReferenceType[]
{
new OrderReferenceType
{
ID = "34"
}
},
BuyerCustomerParty = new CustomerPartyType
{
Party = new PartyType
{
EndpointID = new IdentifierType
{
schemeAgencyID = "9",
schemeID = "GLN",
Value = "7300072311115"
},
PartyIdentification = new PartyIdentificationType[]
{
new PartyIdentificationType
{
ID = new IdentifierType
{
schemeAgencyID = "9",
schemeID = "GLN",
Value = "7300070011115"
}
},
new PartyIdentificationType
{
ID = "PartyID123"
}
},
PartyName = new PartyNameType[]
{
new PartyNameType
{
Name = "Johnssons byggvaror"
}
}
}
},
SellerSupplierParty = new SupplierPartyType
{
Party = new PartyType
{
EndpointID = new IdentifierType
{
schemeAgencyID = "9",
schemeID = "GLN",
Value = "7302347231111"
},
PartyIdentification = new PartyIdentificationType[]
{
new PartyIdentificationType
{
ID = "SellerPartyID123"
}
},
PartyName = new PartyNameType[]
{
new PartyNameType
{
Name = "Moderna Produkter AB"
}
}
}
}
};
doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[]
{
new XmlQualifiedName("cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"),
new XmlQualifiedName("cbc","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"),
});
return doc;
}
}
}
| 36.848214 | 119 | 0.355222 | [
"Unlicense"
] | Gammern/ubllarsen | UblLarsen/UblLarsen.IntegrationV2_1.Test/UblClass/UBL-OrderCancellation-2.1-Example.cs | 4,127 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.461)
// Version 5.461.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.Diagnostics;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Draw element for a context menu separator.
/// </summary>
public class ViewDrawMenuSeparator : ViewDrawDocker
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawMenuSeparator class.
/// </summary>
/// <param name="separator">Reference to owning separator entry.</param>
/// <param name="palette">Palette for obtaining drawing values.</param>
public ViewDrawMenuSeparator(KryptonContextMenuSeparator separator,
PaletteDoubleRedirect palette)
: base(separator.StateNormal.Back, separator.StateNormal.Border)
{
// Draw the separator by default
Draw = true;
// Give the separator object the redirector to use when inheriting values
separator.SetPaletteRedirect(palette);
Orientation = separator.Horizontal ? VisualOrientation.Top : VisualOrientation.Left;
// We need to be big enough to contain 1 pixel square spacer
Add(new ViewLayoutSeparator(1));
}
/// <summary>
/// Initialize a new instance of the ViewDrawMenuSeparator class.
/// </summary>
/// <param name="state">State specific source of palette values.</param>
public ViewDrawMenuSeparator(PaletteDouble state)
: base(state.Back, state.Border)
{
// We need to be big enough to contain 1 pixel square spacer
Orientation = VisualOrientation.Left;
Add(new ViewLayoutSeparator(1));
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawMenuSeparator:" + Id;
}
#endregion
#region Draw
/// <summary>
/// Gets and sets the drawing of the separator.
/// </summary>
public bool Draw { get; set; }
#endregion
#region Paint
/// <summary>
/// Perform a render of the elements.
/// </summary>
/// <param name="context">Rendering context.</param>
public override void Render(RenderContext context)
{
Debug.Assert(context != null);
if (Draw)
{
base.Render(context);
}
}
#endregion
}
}
| 36.536842 | 157 | 0.580524 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.461 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/View Draw/ViewDrawMenuSeparator.cs | 3,474 | C# |
using System.Collections.Generic;
using Moq;
using Transmogrifier.Chrysalis;
namespace Transmogrifier.StylesheetCompilerTests
{
public class ChrysalisMockFactory
{
public static IChrysalis CreateChrysalis(IChrysalisFactory factory = null)
{
if (factory == null) factory = new ChrysalisFactory();
var chrysalis = factory.CreateChrysalis();
var grandTotal = factory.CreateField("GrandTotal", factory.CreateFieldData("grandTotal"),
factory.CreateFieldData("GrandTotal", ContentType.Element));
var poNumber = new Field("PurchaseOrderNumber")
{
DataType = "string",
InputData = new FieldData("PurchaseOrderNumber"),
OutputData = new FieldData("PurchaseOrderNumber")
{
Path = "Header",
ContentType = ContentType.Element
}
};
var poTotal = new Field("LineTotal")
{
DataType = "decimal",
InputData = new FieldData("poTotal"),
OutputData = new FieldData("LineTotal")
{
Path = "Header",
ContentType = ContentType.Element
}
};
var lineNumber = new Field("LineNumber")
{
DataType = "string",
InputData = new FieldData("line")
{
ContentType = ContentType.Attribute
},
OutputData = new FieldData("number")
{
ContentType = ContentType.Attribute
}
};
var quantity = new Field("Quantity")
{
DataType = "decimal",
InputData = new FieldData("Quantity"),
OutputData = new FieldData("Quantity")
{
ContentType = ContentType.Element
}
};
var unitPrice = new Field("UnitPrice")
{
DataType = "decimal",
InputData = new FieldData("UnitPrice"),
OutputData = new FieldData("Price")
{
ContentType = ContentType.Element
}
};
var description = new Field("Description")
{
DataType = "string",
InputData = new FieldData("Description"),
OutputData = new FieldData("Description")
{
ContentType = ContentType.Element
}
};
var businessUnit = new Field("BusinessUnit")
{
DataType = "string",
InputData = new FieldData("BusinessUnit"),
OutputData = new FieldData("BusinessUnit")
{
Path = "Header/Properties",
ContentType = ContentType.Element
}
};
var currency = new Field("Currency")
{
DataType = "string",
InputData = new FieldData("currency")
{
Path = "UnitPrice",
ContentType = ContentType.Attribute
},
OutputData = new FieldData("curr")
{
Path = "Price",
ContentType = ContentType.Attribute
}
};
var taxIncluded = new Field("TaxIncluded")
{
DataType = "string",
InputData = new FieldData("taxIncluded")
{
Path = "UnitPrice",
ContentType = ContentType.Attribute
},
OutputData = new FieldData("taxIncluded")
{
Path = "Price",
ContentType = ContentType.Attribute
}
};
var constantField = new Field("ElTesto")
{
DataType = "string",
InputData = new FieldData("This is a test one two three.")
{
ContentType = ContentType.Text
},
OutputData = new FieldData("ElTesto")
{
ContentType = ContentType.Element
}
};
var calcSubTotal = new Field("SubTotal")
{
DataType = "decimal",
InputData = new FieldData("Quantity*@line")
{
ContentType = ContentType.Calculation
},
OutputData = new FieldData("SubTotal")
{
ContentType = ContentType.Element
}
};
var calcTaxTotal = new Field("TaxTotal")
{
DataType = "decimal",
InputData = new FieldData("Quantity*@line*$TaxRate")
{
ContentType = ContentType.Calculation
},
OutputData = new FieldData("TaxTotal")
{
ContentType = ContentType.Element
}
};
var variableField = new Field("TaxRate")
{
DataType = "decimal",
InputData = new FieldData(".0825")
{
ContentType = ContentType.Number
},
OutputData = new FieldData("TaxRate")
{
ContentType = ContentType.Variable
}
};
var lineGroup = factory.CreateGroup<ISubGroup>("Record");
lineGroup.OutputData = new FieldData("Line", path:"Lines");
lineGroup.AddKeyField(lineNumber);
lineGroup.AddFields(
lineNumber,
quantity,
unitPrice,
calcSubTotal,
description,
currency,
calcTaxTotal,
variableField,
taxIncluded
);
var poGroup = factory.CreateGroup<ISubGroup>("Record");
poGroup.OutputData = factory.CreateFieldData("PurchaseOrder", path:"PurchaseOrders");
poGroup.AddKeyField(poNumber);
poGroup.AddKeyField(businessUnit);
poGroup.AddFields(poNumber, poTotal, businessUnit, constantField);
poGroup.AddGroup(lineGroup);
var rootGroup = factory.CreateGroup<IRootGroup>("/");
rootGroup.InputContext = "/File/Record";
rootGroup.OutputData = new FieldData("MasterData")
{
Path = "Transmogrifier"
};
rootGroup.AddField(grandTotal);
rootGroup.AddGroup(poGroup);
chrysalis.AddRootGroup(rootGroup);
return chrysalis;
}
public static IField MockIField(string alias)
{
var mockIField = new Mock<IField>();
mockIField.SetupAllProperties();
mockIField.SetupGet(f => f.Alias).Returns(alias);
return mockIField.Object;
}
public static IFieldData MockIFieldData(string name, ContentType contentType = ContentType.None,
string path = null)
{
var mockIFieldData = new Mock<IFieldData>();
mockIFieldData.SetupAllProperties();
mockIFieldData.SetupGet(fd => fd.Name).Returns(name);
mockIFieldData.Object.ContentType = contentType;
mockIFieldData.Object.Path = path;
return mockIFieldData.Object;
}
public static ISubGroup MockISubGroup(string templateMatch, IField keyField) =>
MockISubGroup(templateMatch, new List<IField> {keyField});
public static ISubGroup MockISubGroup(string templateMatch, List<IField> keyFields = null)
{
var mockISubGroup = new Mock<ISubGroup>();
mockISubGroup.SetupAllProperties();
mockISubGroup.SetupGet(sg => sg.TemplateMatch).Returns(templateMatch);
mockISubGroup.Setup(sg => sg.KeyFields).Returns(keyFields ?? new List<IField>());
return mockISubGroup.Object;
}
}
} | 35.764957 | 104 | 0.483929 | [
"MIT"
] | hellourgo/Transmogrifier | StylesheetCompilerTests/ChrysalisMockFactory.cs | 8,371 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Triton.Utility
{
/// <summary>
/// Provides lookups from hashed strings to the actual string
/// This class will also detect hash collisions
/// </summary>
public static class HashedStringTable
{
public static string GetString(HashedString hashedString)
{
if (Lookup.ContainsKey(hashedString))
return Lookup[hashedString];
else
return "";
}
public static void AddString(HashedString hashedString, string value)
{
if (!Lookup.ContainsKey(hashedString))
{
Lookup.TryAdd(hashedString, value);
}
else if (value != Lookup[hashedString])
{
throw new Exception("hash collision");
}
}
static ConcurrentDictionary<HashedString, string> Lookup = new ConcurrentDictionary<HashedString, string>();
}
}
| 23.538462 | 110 | 0.728758 | [
"BSD-3-Clause"
] | johang88/triton | Triton/Utility/HashedStringTable.cs | 920 | C# |
/***
*
* Title: "SUIFW"UI框架项目
* 主题: UI遮罩管理
* Description:
* 功能: 实现对于任何对象的监听处理。
* Date: 2019
* Version: 0.1版本
* Modify Recoder:
*
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
namespace UIFrame
{
public class UIMaskManager : MonoBehaviour
{
/*字段*/
//单例
private static UIMaskManager _Instance = null;
/// <summary>
/// UI根节点对象
/// </summary>
private GameObject _objCanvasRoot = null;
/// <summary>
/// UI脚本节点对象
/// </summary>
private Transform _TraUIScriptsNode = null;
/// <summary>
/// 顶层面板
/// </summary>
private GameObject _objTopPanel = null;
/// <summary>
/// 遮罩面板
/// </summary>
private GameObject _objMaskPanel = null;
/// <summary>
/// UI相机
/// </summary>
private Camera _UICamera = null;
/// <summary>
/// UI相机原始的层深
/// </summary>
/// <returns></returns>
private float _OriginalUICameraDepth = 0;
/// <summary>
/// 得到实例
/// </summary>
/// <returns></returns>
public static UIMaskManager GetInstance()
{
if (_Instance == null)
{
_Instance = new GameObject("_UIMaskManager").AddComponent<UIMaskManager>();
}
return _Instance;
}
private void Awake()
{
//得到UI根节点对象、脚本节点对象
_objCanvasRoot = GameObject.FindGameObjectWithTag(SysDefine.SYS_TAG_CANVAS);
_TraUIScriptsNode = UnityHelper.FindTheChildNode(_objCanvasRoot, SysDefine.SYS_SCRIPTMANAGER_NODE);
//把本脚本实例作为,作为脚本节点的子对象
UnityHelper.AddParentNodeToChildNode(_TraUIScriptsNode, this.gameObject.transform);
//得到“顶层面板”、“遮罩面板”
_objTopPanel = _objCanvasRoot;
_objMaskPanel = UnityHelper.FindTheChildNode(_objCanvasRoot, "_UIMaskPanel").gameObject;
//得到UI摄像机原始的“层深”
_UICamera = GameObject.FindGameObjectWithTag("_UICamera").GetComponent<Camera>();
if (_UICamera != null)
{
//得到原始的层深
_OriginalUICameraDepth = _UICamera.depth;
}
else
{
Debug.Log(GetType() + "/Start()/UI_Camera Is Null!");
}
}
/// <summary>
/// 设置遮罩状态
/// </summary>
/// <param name="objDisplay">需要显示的UI窗体</param>
/// <param name="LucenyType"></param>
public void SetMaskWindow(GameObject objDisplay,UIFormLucenyType LucenyType = UIFormLucenyType.Lucency)
{
if (LucenyType == UIFormLucenyType.DnotMask)
{
//显示窗体下移
objDisplay.transform.SetAsLastSibling();
//增加当前UI摄像机的层深(保证当前相机为最前显示)
if (_UICamera != null)
{
_UICamera.depth = _UICamera.depth + 100;
}
return;
}
Canvas _MaskCanvas = _objMaskPanel.GetOrAddComponent<Canvas>();
_objMaskPanel.GetOrAddComponent<GraphicRaycaster>();
//顶层窗体下移
_objTopPanel.transform.SetAsLastSibling();
if (UIManager._DicUIFormSortLayerCount.ContainsKey(objDisplay.name))
{
objDisplay.GetComponent<Canvas>().sortingOrder = UIManager._DicUIFormSortLayerCount[objDisplay.name]+2;
_MaskCanvas = _objMaskPanel.GetComponent<Canvas>();
_MaskCanvas.overrideSorting = true;
_MaskCanvas.enabled = true;
_MaskCanvas.sortingOrder = objDisplay.GetComponent<Canvas>().sortingOrder - 1;
}
else
{
if (_MaskCanvas != null)
{
Destroy(_objMaskPanel.GetComponent<GraphicRaycaster>());
Destroy(_MaskCanvas);
}
}
//启动遮罩窗体以及设置透明度
switch (LucenyType)
{
case UIFormLucenyType.Lucency:
{
_objMaskPanel.SetActive(true);
Color newColor = new Color(
SysDefine.SYS_LUCENCY_RGB,
SysDefine.SYS_LUCENCY_RGB,
SysDefine.SYS_LUCENCY_RGB,
SysDefine.SYS_LUCENCY_RGB_A
);
_objMaskPanel.GetComponent<Image>().color = newColor;
}
break;
case UIFormLucenyType.Translucence:
{
_objMaskPanel.SetActive(true);
Color newColor = new Color(
SysDefine.SYS_TRANS_RGB,
SysDefine.SYS_TRANS_RGB,
SysDefine.SYS_TRANS_RGB,
SysDefine.SYS_TRANS_RGB_A
);
_objMaskPanel.GetComponent<Image>().color = newColor;
}
break;
case UIFormLucenyType.ImPenetrable:
{
_objMaskPanel.SetActive(true);
Color newColor = new Color(
SysDefine.SYS_IMPENETRABLE_RGB,
SysDefine.SYS_IMPENETRABLE_RGB,
SysDefine.SYS_IMPENETRABLE_RGB,
SysDefine.SYS_IMPENETRABLE_RGB_A
);
_objMaskPanel.GetComponent<Image>().color = newColor;
}
break;
case UIFormLucenyType.Pentrate:
{
print("允许穿透");
if (_objMaskPanel.activeInHierarchy)
{
_objMaskPanel.SetActive(false);
_objMaskPanel.GetComponent<Canvas>().enabled = false;
}
}
break;
}
//遮罩窗体下移
_objMaskPanel.transform.SetAsLastSibling();
//显示窗体下移
objDisplay.transform.SetAsLastSibling();
//增加当前UI摄像机的层深(保证当前相机为最前显示)
if (_UICamera != null)
{
_UICamera.depth = _UICamera.depth + 100;
}
}
/// <summary>
/// 取消遮罩状态
/// </summary>
public void CancelMaskWindow()
{
//顶层窗体上移
_objTopPanel.transform.SetAsFirstSibling();
//禁用遮罩体
if(_objMaskPanel.activeInHierarchy)
{
//隐藏
_objMaskPanel.SetActive(false);
}
//恢复层深
if (_UICamera != null)
{
_UICamera.depth = _OriginalUICameraDepth;
}
}
}
}
| 33.130233 | 119 | 0.477467 | [
"MIT"
] | petergjh/-c-sharpcrash | Assets/Scripts/UIFramework/Helps/UIMaskManager.cs | 7,637 | C# |
using System;
using System.Threading.Tasks;
using uhttpsharp;
namespace Server.Web.Handlers
{
public class ExceptionHandler : IHttpRequestHandler
{
public async Task Handle(IHttpContext context, Func<Task> next)
{
try
{
await next().ConfigureAwait(false);
}
catch (HttpException e)
{
context.Response = new HttpResponse(e.ResponseCode, "Error while handling your request. " + e.Message, false);
}
catch (Exception e)
{
context.Response = new HttpResponse(HttpResponseCode.InternalServerError, "Error while handling your request. " + e, false);
}
}
}
}
| 28.692308 | 140 | 0.569705 | [
"MIT"
] | 211network/LunaMultiplayer | Server/Web/Handlers/ExceptionHandler.cs | 748 | C# |
namespace Journey.Data.Models
{
using System.Collections.Generic;
using Journey.Data.Common.Models;
public class Publisher : BaseDeletableModel<int>
{
public Publisher()
{
this.Games = new HashSet<Game>();
}
public string Name { get; set; }
public ICollection<Game> Games { get; set; }
}
}
| 19.315789 | 52 | 0.588556 | [
"MIT"
] | stefandenchev/Journey | Data/Journey.Data.Models/Publisher.cs | 369 | C# |
using HyperSlackers.Bootstrap.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using HyperSlackers.Bootstrap.Extensions;
namespace HyperSlackers.Bootstrap.Builders
{
public class TableBuilder<TModel> : DisposableHtmlElement<TModel, Table>
{
private bool disposed = false;
internal TableBuilder(HtmlHelper<TModel> html, Table table)
: base(html, table)
{
Contract.Requires<ArgumentNullException>(html != null, "html");
Contract.Requires<ArgumentNullException>(table != null, "table");
textWriter.Write(element.StartTag);
if (!element.caption.IsNullOrWhiteSpace())
{
textWriter.Write(string.Format("<caption>{0}</caption>", element.caption));
}
}
public TableHeaderBuilder<TModel> BeginHeader()
{
Contract.Ensures(Contract.Result<TableHeaderBuilder<TModel>>() != null);
element.wasHeaderTagRendered = true;
return new TableHeaderBuilder<TModel>(html, new TableHeader());
}
public TableHeaderBuilder<TModel> BeginHeader(TableHeader header)
{
Contract.Requires<ArgumentNullException>(header != null, "header");
Contract.Ensures(Contract.Result<TableHeaderBuilder<TModel>>() != null);
element.wasHeaderTagRendered = true;
return new TableHeaderBuilder<TModel>(html, header);
}
public IHtmlString Header(params string[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
return Header(TableColor.Default, columnHeaders);
}
public IHtmlString Header(TableColor style, params string[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
EnsureHeader();
StringBuilder header = new StringBuilder();
TableHeaderRow row = new TableHeaderRow();
TableHeaderCell cell = new TableHeaderCell();
row.Style(style);
header.Append(row.StartTag);
foreach (var item in columnHeaders)
{
header.Append(cell.StartTag);
header.Append(item);
header.Append(cell.EndTag);
}
header.Append(row.EndTag);
return MvcHtmlString.Create(header.ToString());
}
public IHtmlString Header(params IHtmlString[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
return Header(TableColor.Default, columnHeaders);
}
public IHtmlString Header(TableColor style, params IHtmlString[] columnHeaders)
{
Contract.Requires<ArgumentNullException>(columnHeaders != null, "columnHeaders");
EnsureHeader();
StringBuilder header = new StringBuilder();
TableHeaderRow row = new TableHeaderRow();
TableHeaderCell cell = new TableHeaderCell();
row.Style(style);
header.Append(row.StartTag);
foreach (var item in columnHeaders)
{
header.Append(cell.StartTag);
header.Append(item);
header.Append(cell.EndTag);
}
header.Append(row.EndTag);
return MvcHtmlString.Create(header.ToString());
}
public TableBodyBuilder<TModel> BeginBody()
{
Contract.Ensures(Contract.Result<TableBodyBuilder<TModel>>() != null);
element.wasBodyTagRendered = true;
return new TableBodyBuilder<TModel>(html, new TableBody());
}
public TableBodyBuilder<TModel> BeginBody(TableBody body)
{
Contract.Requires<ArgumentNullException>(body != null, "body");
Contract.Ensures(Contract.Result<TableBodyBuilder<TModel>>() != null);
element.wasBodyTagRendered = true;
return new TableBodyBuilder<TModel>(html, body);
}
public TableRowBuilder<TModel> BeginRow()
{
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
return new TableRowBuilder<TModel>(html, new TableRow());
}
public TableRowBuilder<TModel> BeginRow(TableRow row)
{
Contract.Requires<ArgumentNullException>(row != null, "row");
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
return new TableRowBuilder<TModel>(html, row);
}
public TableRowBuilder<TModel> BeginRow(TableColor style)
{
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
TableRow tableRow = (new TableRow()).Style(style);
return new TableRowBuilder<TModel>(html, tableRow);
}
public TableRowBuilder<TModel> BeginRow(object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
TableRow tableRow = (new TableRow()).HtmlAttributes(htmlAttributes);
return new TableRowBuilder<TModel>(html, tableRow);
}
public TableRowBuilder<TModel> BeginRow(TableColor style, object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<TableRowBuilder<TModel>>() != null);
EnsureBody();
TableRow tableRow = (new TableRow()).Style(style).HtmlAttributes(htmlAttributes);
return new TableRowBuilder<TModel>(html, tableRow);
}
public IHtmlString Row(params string[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
return Row(TableColor.Default, cellContents);
}
public IHtmlString Row(TableColor style, params string[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
EnsureBody();
StringBuilder tableRow = new StringBuilder();
TableRow row = new TableRow();
TableCell cell = new TableCell();
row.Style(style);
tableRow.Append(row.StartTag);
foreach (var item in cellContents)
{
tableRow.Append(cell.StartTag);
tableRow.Append(item);
tableRow.Append(cell.EndTag);
}
tableRow.Append(row.EndTag);
return MvcHtmlString.Create(tableRow.ToString());
}
public IHtmlString Row(params IHtmlString[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
return Row(TableColor.Default, cellContents);
}
public IHtmlString Row(TableColor style, params IHtmlString[] cellContents)
{
Contract.Requires<ArgumentNullException>(cellContents != null, "cellContents");
EnsureBody();
StringBuilder tableRow = new StringBuilder();
TableRow row = new TableRow();
TableCell cell = new TableCell();
row.Style(style);
tableRow.Append(row.StartTag);
foreach (var item in cellContents)
{
tableRow.Append(cell.StartTag);
tableRow.Append(item);
tableRow.Append(cell.EndTag);
}
tableRow.Append(row.EndTag);
return MvcHtmlString.Create(tableRow.ToString());
}
public TableFooterBuilder<TModel> BeginFooter()
{
Contract.Ensures(Contract.Result<TableFooterBuilder<TModel>>() != null);
return new TableFooterBuilder<TModel>(html, new TableFooter());
}
public TableFooterBuilder<TModel> BeginFooter(TableFooter footer)
{
Contract.Requires<ArgumentNullException>(footer != null, "footer");
Contract.Ensures(Contract.Result<TableFooterBuilder<TModel>>() != null);
return new TableFooterBuilder<TModel>(html, footer);
}
public IHtmlString Footer(params string[] columnFooters)
{
Contract.Requires<ArgumentNullException>(columnFooters != null, "columnFooters");
EnsureFooter();
StringBuilder footer = new StringBuilder();
TableFooterRow row = new TableFooterRow();
TableFooterCell cell = new TableFooterCell();
footer.Append(row.StartTag);
foreach (var item in columnFooters)
{
footer.Append(cell.StartTag);
footer.Append(item);
footer.Append(cell.EndTag);
}
footer.Append(row.EndTag);
return MvcHtmlString.Create(footer.ToString());
}
public IHtmlString Footer(params IHtmlString[] columnFooters)
{
Contract.Requires<ArgumentNullException>(columnFooters != null, "columnFooters");
EnsureFooter();
StringBuilder footer = new StringBuilder();
TableFooterRow row = new TableFooterRow();
TableFooterCell cell = new TableFooterCell();
footer.Append(row.StartTag);
foreach (var item in columnFooters)
{
footer.Append(cell.StartTag);
footer.Append(item);
footer.Append(cell.EndTag);
}
footer.Append(row.EndTag);
return MvcHtmlString.Create(footer.ToString());
}
private void EnsureHeader()
{
if (!element.wasHeaderTagRendered && !element.isHeaderTagOpen)
{
element.isHeaderTagOpen = true;
textWriter.Write("<thead>");
}
}
private void EnsureHeaderClosed()
{
if (element.isHeaderTagOpen)
{
element.isHeaderTagOpen = false;
element.wasHeaderTagRendered = true;
textWriter.Write("</thead>");
}
}
private void EnsureBody()
{
EnsureHeaderClosed();
if (!element.wasBodyTagRendered && !element.isBodyTagOpen)
{
element.isBodyTagOpen = true;
textWriter.Write("<tbody>");
}
}
private void EnsureBodyClosed()
{
if (element.isBodyTagOpen)
{
element.isBodyTagOpen = false;
element.wasBodyTagRendered = true;
textWriter.Write("</tbody>");
}
}
private void EnsureFooter()
{
EnsureHeaderClosed();
EnsureBodyClosed();
if (!element.wasFooterTagRendered && !element.isFooterTagOpen)
{
element.isFooterTagOpen = true;
textWriter.Write("<tfoot>");
}
}
private void EnsureFooterClosed()
{
if (element.isFooterTagOpen)
{
element.isFooterTagOpen = false;
element.wasFooterTagRendered = true;
textWriter.Write("</tfoot>");
}
}
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
EnsureHeaderClosed();
EnsureBodyClosed();
EnsureFooterClosed();
disposed = true;
}
}
base.Dispose(true);
}
}
} | 30.210396 | 95 | 0.574273 | [
"Apache-2.0"
] | dmayhak/HyperSlackers.Bootstrap | Bootstrap/Table/TableBuilder.cs | 12,205 | C# |
//******************************************************************************************************
// Command.cs - Gbtc
//
// Copyright © 2016, James Ritchie Carroll. All Rights Reserved.
// MIT License (MIT)
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 05/15/2015 - J. Ritchie Carroll
// Generated original version of source code.
//
//******************************************************************************************************
using System.Xml.Serialization;
namespace AlexaDoPlugin.Commands
{
/// <summary>
/// Represents a command to be executed consisting of a trigger, action and a response.
/// </summary>
public class Command
{
/// <summary>
/// Command description.
/// </summary>
[XmlAttribute("description")]
public string Description;
/// <summary>
/// Command usage.
/// </summary>
[XmlAttribute("usage")]
public string Usage;
/// <summary>
/// Command enabled flag.
/// </summary>
[XmlAttribute("enabled")]
public bool Enabled;
/// <summary>
/// Command trigger.
/// </summary>
[XmlElement("trigger")]
public Trigger Trigger;
/// <summary>
/// Command action.
/// </summary>
[XmlElement("action")]
public Action Action;
/// <summary>
/// Command response.
/// </summary>
[XmlElement("response")]
public Response Response;
/// <summary>
/// Any associated notes.
/// </summary>
[XmlElement("notes", IsNullable = true)]
public Notes Notes;
}
}
| 28.166667 | 106 | 0.426036 | [
"MIT"
] | ritchiecarroll/AlexaDo | src/AlexaDoPlugin/Commands/Command.cs | 1,862 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1
{
public class PackageSpecControllerDeploymentSpecTemplateSpecInitContainersEnvValueFromFieldRefArgs : Pulumi.ResourceArgs
{
[Input("apiVersion")]
public Input<string>? ApiVersion { get; set; }
[Input("fieldPath", required: true)]
public Input<string> FieldPath { get; set; } = null!;
public PackageSpecControllerDeploymentSpecTemplateSpecInitContainersEnvValueFromFieldRefArgs()
{
}
}
}
| 30.884615 | 124 | 0.723537 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/crossplane/dotnet/Kubernetes/Crds/Operators/Crossplane/Packages/V1Alpha1/Inputs/PackageSpecControllerDeploymentSpecTemplateSpecInitContainersEnvValueFromFieldRefArgs.cs | 803 | C# |
using System;
using NetOffice;
namespace NetOffice.OutlookApi.Enums
{
/// <summary>
/// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff869828.aspx </remarks>
[SupportByVersionAttribute("Outlook", 9,10,11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum OlPane
{
/// <summary>
/// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("Outlook", 9,10,11,12,14,15,16)]
olOutlookBar = 1,
/// <summary>
/// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Outlook", 9,10,11,12,14,15,16)]
olFolderList = 2,
/// <summary>
/// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersionAttribute("Outlook", 9,10,11,12,14,15,16)]
olPreview = 3,
/// <summary>
/// SupportByVersion Outlook 11, 12, 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersionAttribute("Outlook", 11,12,14,15,16)]
olNavigationPane = 4,
/// <summary>
/// SupportByVersion Outlook 12, 14, 15, 16
/// </summary>
/// <remarks>5</remarks>
[SupportByVersionAttribute("Outlook", 12,14,15,16)]
olToDoBar = 5
}
} | 29.291667 | 119 | 0.633713 | [
"MIT"
] | brunobola/NetOffice | Source/Outlook/Enums/OlPane.cs | 1,408 | C# |
using System;
using System.Linq;
using System.Reflection;
using Weikio.PluginFramework.TypeFinding;
namespace Weikio.PluginFramework.Context
{
public class MetadataTypeFindingContext : ITypeFindingContext
{
private readonly MetadataLoadContext _metadataLoadContext;
public MetadataTypeFindingContext(MetadataLoadContext metadataLoadContext)
{
_metadataLoadContext = metadataLoadContext;
}
public Assembly FindAssembly(string assemblyName)
{
var result = _metadataLoadContext.LoadFromAssemblyName(assemblyName);
return result;
}
public Type FindType(Type type)
{
var assemblyName = type.Assembly.GetName();
var assemblies = _metadataLoadContext.GetAssemblies();
var assembly = assemblies.FirstOrDefault(x => string.Equals(x.FullName, assemblyName.FullName));
if (assembly == null)
{
assembly = _metadataLoadContext.LoadFromAssemblyName(assemblyName);
}
var result = assembly.GetType(type.FullName);
return result;
}
}
}
| 27.833333 | 108 | 0.651839 | [
"MIT"
] | ApocDev/PluginFramework | src/Weikio.PluginFramework/Context/MetadataTypeFindingContext.cs | 1,171 | 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("BrowserShell")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BrowserShell")]
[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("a4931099-4101-4301-abb9-d79475a4ba56")]
// 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.756757 | 84 | 0.745168 | [
"MIT"
] | deostroll/WebBrowserBrowser | MockBrowser/BrowserShell/BrowserShell/Properties/AssemblyInfo.cs | 1,400 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace QuantConnect.Indicators
{
/// <summary>
/// Represents the LogReturn indicator (LOGR)
/// - log returns are useful for identifying price convergence/divergence in a given period
/// - logr = log (current price / last price in period)
/// </summary>
public class LogReturn : WindowIndicator<IndicatorDataPoint>
{
/// <summary>
/// Initializes a new instance of the LogReturn class with the specified name and period
/// </summary>
/// <param name="name">The name of this indicator</param>
/// <param name="period">The period of the LOGR</param>
public LogReturn(string name, int period)
: base(name, period)
{
}
/// <summary>
/// Initializes a new instance of the LogReturn class with the default name and period
/// </summary>
/// <param name="period">The period of the SMA</param>
public LogReturn(int period)
: base("LOGR" + period, period)
{
}
/// <summary>
/// Computes the next value for this indicator from the given state.
/// - logr = log (current price / last price in period)
/// </summary>
/// <param name="window">The window of data held in this indicator</param>
/// <param name="input">The input value to this indicator on this time step</param>
/// <returns>A new value for this indicator</returns>
protected override decimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input)
{
decimal valuef = input;
decimal value0 = !window.IsReady
? window[window.Count - 1]
: window.MostRecentlyRemoved;
return (decimal)Math.Log((double)(valuef / value0));
}
}
}
| 39.953846 | 121 | 0.635734 | [
"Apache-2.0"
] | CircleOnCircles/Lean | Indicators/LogReturn.cs | 2,599 | C# |
using Agree.Accord.SharedKernel.Data;
namespace Agree.Accord.Domain.Identity.Dtos
{
public class SearchAccountsDto : Pagination
{
public string Query { get; set; }
}
} | 20.888889 | 47 | 0.696809 | [
"MIT"
] | vassourita/agree | apps/accord/src/Agree.Accord.Domain/Identity/Dtos/SearchAccountsDto.cs | 188 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Ovh
{
public static class GetMePaymentMeanCreditCard
{
/// <summary>
/// Use this data source to retrieve information about a credit card
/// payment mean associated with an OVH account.
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Ovh = Pulumi.Ovh;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var cc = Output.Create(Ovh.GetMePaymentMeanCreditCard.InvokeAsync(new Ovh.GetMePaymentMeanCreditCardArgs
/// {
/// UseDefault = true,
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetMePaymentMeanCreditCardResult> InvokeAsync(GetMePaymentMeanCreditCardArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetMePaymentMeanCreditCardResult>("ovh:index/getMePaymentMeanCreditCard:getMePaymentMeanCreditCard", args ?? new GetMePaymentMeanCreditCardArgs(), options.WithDefaults());
/// <summary>
/// Use this data source to retrieve information about a credit card
/// payment mean associated with an OVH account.
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Ovh = Pulumi.Ovh;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var cc = Output.Create(Ovh.GetMePaymentMeanCreditCard.InvokeAsync(new Ovh.GetMePaymentMeanCreditCardArgs
/// {
/// UseDefault = true,
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Output<GetMePaymentMeanCreditCardResult> Invoke(GetMePaymentMeanCreditCardInvokeArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetMePaymentMeanCreditCardResult>("ovh:index/getMePaymentMeanCreditCard:getMePaymentMeanCreditCard", args ?? new GetMePaymentMeanCreditCardInvokeArgs(), options.WithDefaults());
}
public sealed class GetMePaymentMeanCreditCardArgs : Pulumi.InvokeArgs
{
/// <summary>
/// a regexp used to filter credit cards
/// on their `description` attributes.
/// </summary>
[Input("descriptionRegexp")]
public string? DescriptionRegexp { get; set; }
[Input("states")]
private List<string>? _states;
/// <summary>
/// Filter credit cards on their `state` attribute.
/// Can be "expired", "valid", "tooManyFailures"
/// </summary>
public List<string> States
{
get => _states ?? (_states = new List<string>());
set => _states = value;
}
/// <summary>
/// Retrieve credit card marked as default payment mean.
/// </summary>
[Input("useDefault")]
public bool? UseDefault { get; set; }
/// <summary>
/// Retrieve the credit card that will be the last
/// to expire according to its expiration date.
/// </summary>
[Input("useLastToExpire")]
public bool? UseLastToExpire { get; set; }
public GetMePaymentMeanCreditCardArgs()
{
}
}
public sealed class GetMePaymentMeanCreditCardInvokeArgs : Pulumi.InvokeArgs
{
/// <summary>
/// a regexp used to filter credit cards
/// on their `description` attributes.
/// </summary>
[Input("descriptionRegexp")]
public Input<string>? DescriptionRegexp { get; set; }
[Input("states")]
private InputList<string>? _states;
/// <summary>
/// Filter credit cards on their `state` attribute.
/// Can be "expired", "valid", "tooManyFailures"
/// </summary>
public InputList<string> States
{
get => _states ?? (_states = new InputList<string>());
set => _states = value;
}
/// <summary>
/// Retrieve credit card marked as default payment mean.
/// </summary>
[Input("useDefault")]
public Input<bool>? UseDefault { get; set; }
/// <summary>
/// Retrieve the credit card that will be the last
/// to expire according to its expiration date.
/// </summary>
[Input("useLastToExpire")]
public Input<bool>? UseLastToExpire { get; set; }
public GetMePaymentMeanCreditCardInvokeArgs()
{
}
}
[OutputType]
public sealed class GetMePaymentMeanCreditCardResult
{
/// <summary>
/// a boolean which tells if the retrieved credit card
/// is marked as the default payment mean
/// </summary>
public readonly bool Default;
/// <summary>
/// the description attribute of the credit card
/// </summary>
public readonly string Description;
public readonly string? DescriptionRegexp;
/// <summary>
/// The provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
/// <summary>
/// the state attribute of the credit card
/// </summary>
public readonly string State;
public readonly ImmutableArray<string> States;
public readonly bool? UseDefault;
public readonly bool? UseLastToExpire;
[OutputConstructor]
private GetMePaymentMeanCreditCardResult(
bool @default,
string description,
string? descriptionRegexp,
string id,
string state,
ImmutableArray<string> states,
bool? useDefault,
bool? useLastToExpire)
{
Default = @default;
Description = description;
DescriptionRegexp = descriptionRegexp;
Id = id;
State = state;
States = states;
UseDefault = useDefault;
UseLastToExpire = useLastToExpire;
}
}
}
| 32.317536 | 226 | 0.553014 | [
"ECL-2.0",
"Apache-2.0"
] | tumblewader/pulumi-ovh | sdk/dotnet/GetMePaymentMeanCreditCard.cs | 6,819 | C# |
using System;
using System.Collections.Generic;
namespace StackOverflowDumpCodeBuilder
{
public class User
{
private List<Badge> badges;
public int Id { get; set; }
public int Reputation { get; set; }
public string DisplayName { get; set; }
public DateTime LastAccessDate { get; set; }
public DateTime CreationDate { get; set; }
public string WebsiteUrl { get; set; }
public int Views { get; set; }
public int Age { get; set; }
public int UpVotes { get; set; }
public int DownVotes { get; set; }
public string Location { get; set; }
public string AboutMe { get; set; }
public IEnumerable<Badge> Badges { get; private set; }
public User()
{
DisplayName = "";
WebsiteUrl = "";
Location = "";
AboutMe = "";
badges = new List<Badge>();
Badges = badges;
}
public override string ToString()
{
return String.Format("\nName: {0}\n\tReputation: {1}\n\tWebsite: {2}\n\tAge: {3}\n\tLocation: {4}\n\tUpVotes: {5}\n\tDownVotes: {6}",
this.DisplayName, this.Reputation, this.WebsiteUrl, this.Age, this.Location, this.UpVotes, this.DownVotes);
}
public void AddBadge(Badge badge)
{
badges.Add(badge);
}
}
} | 32.377778 | 146 | 0.530542 | [
"MIT"
] | kinshuk4/Coursera | k2e/dev/languages/csharp/Linq-Reference/StackOverflowDumpCodeBuilder/StackOverflowDumpCodeBuilder/Entities/User.cs | 1,459 | C# |
namespace DotNet.Testcontainers.Images
{
public interface IDockerImage
{
/// <summary>Gets the Docker image repository name.</summary>
/// <value>Returns the Docker image repository name.</value>
string Repository { get; }
/// <summary>Gets the Docker image name.</summary>
/// <value>Returns the Docker image name.</value>
string Name { get; }
/// <summary>Gets the Docker image tag.</summary>
/// <value>Returns the Docker image tag if present or "latest" instead.</value>
string Tag { get; }
/// <summary>Gets or sets the full Docker image name. Splits the full Docker image name into its components and sets each properties.</summary>
/// <value>Full Docker image name, like "foo/bar:1.0.0" or "bar:latest" based on the components values.</value>
string Image { get; }
}
}
| 37.909091 | 147 | 0.678657 | [
"MIT"
] | SbiCA/dotnet-testcontainers | src/DotNet.Testcontainers/Images/IDockerImage.cs | 834 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Questionnaire.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "DeviceCodes",
columns: table => new
{
UserCode = table.Column<string>(maxLength: 200, nullable: false),
DeviceCode = table.Column<string>(maxLength: 200, nullable: false),
SubjectId = table.Column<string>(maxLength: 200, nullable: true),
ClientId = table.Column<string>(maxLength: 200, nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
Expiration = table.Column<DateTime>(nullable: false),
Data = table.Column<string>(maxLength: 50000, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DeviceCodes", x => x.UserCode);
});
migrationBuilder.CreateTable(
name: "PersistedGrants",
columns: table => new
{
Key = table.Column<string>(maxLength: 200, nullable: false),
Type = table.Column<string>(maxLength: 50, nullable: false),
SubjectId = table.Column<string>(maxLength: 200, nullable: true),
ClientId = table.Column<string>(maxLength: 200, nullable: false),
CreationTime = table.Column<DateTime>(nullable: false),
Expiration = table.Column<DateTime>(nullable: true),
Data = table.Column<string>(maxLength: 50000, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PersistedGrants", x => x.Key);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_DeviceCodes_DeviceCode",
table: "DeviceCodes",
column: "DeviceCode",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_DeviceCodes_Expiration",
table: "DeviceCodes",
column: "Expiration");
migrationBuilder.CreateIndex(
name: "IX_PersistedGrants_Expiration",
table: "PersistedGrants",
column: "Expiration");
migrationBuilder.CreateIndex(
name: "IX_PersistedGrants_SubjectId_ClientId_Type",
table: "PersistedGrants",
columns: new[] { "SubjectId", "ClientId", "Type" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "DeviceCodes");
migrationBuilder.DropTable(
name: "PersistedGrants");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 42.907473 | 108 | 0.494816 | [
"Apache-2.0"
] | mariusmoe/ever-questionnaire | Questionnaire/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 12,059 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace JobHelperSample.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.516129 | 151 | 0.583178 | [
"MIT"
] | EminentTechnology/JobHelper | samples/JobHelperSample/Properties/Settings.Designer.cs | 1,072 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class RepositoryFixture : BaseFixture
{
private const string commitSha = "8496071c1b46c854b31185ea97743be6a8774479";
[Fact]
public void CanCreateBareRepo()
{
string repoPath = InitNewRepository(true);
using (var repo = new Repository(repoPath))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
CheckGitConfigFile(dir);
Assert.Null(repo.Info.WorkingDirectory);
Assert.Equal(Path.GetFullPath(repoPath), repo.Info.Path);
Assert.True(repo.Info.IsBare);
Assert.Throws<BareRepositoryException>(() => { var idx = repo.Index; });
AssertInitializedRepository(repo, "refs/heads/master");
repo.Refs.Add("HEAD", "refs/heads/orphan", true);
AssertInitializedRepository(repo, "refs/heads/orphan");
}
}
[Fact]
public void AccessingTheIndexInABareRepoThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<BareRepositoryException>(() => repo.Index);
}
}
[Fact]
public void CanCheckIfADirectoryLeadsToAValidRepository()
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
Assert.False(Repository.IsValid(scd.DirectoryPath));
Directory.CreateDirectory(scd.DirectoryPath);
Assert.False(Repository.IsValid(scd.DirectoryPath));
}
[Fact]
public void IsValidWithNullPathThrows()
{
Assert.Throws<ArgumentNullException>(() => Repository.IsValid(null));
}
[Fact]
public void IsNotValidWithEmptyPath()
{
Assert.False(Repository.IsValid(string.Empty));
}
[Fact]
public void IsValidWithValidPath()
{
string repoPath = InitNewRepository();
Assert.True(Repository.IsValid(repoPath));
}
[Fact]
public void CanCreateStandardRepo()
{
string repoPath = InitNewRepository();
Assert.True(Repository.IsValid(repoPath));
using (var repo = new Repository(repoPath))
{
Assert.True(Repository.IsValid(repo.Info.WorkingDirectory));
Assert.True(Repository.IsValid(repo.Info.Path));
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
CheckGitConfigFile(dir);
Assert.NotNull(repo.Info.WorkingDirectory);
Assert.Equal(repoPath, repo.Info.Path);
Assert.False(repo.Info.IsBare);
AssertIsHidden(repo.Info.Path);
AssertInitializedRepository(repo, "refs/heads/master");
repo.Refs.Add("HEAD", "refs/heads/orphan", true);
AssertInitializedRepository(repo, "refs/heads/orphan");
}
}
[Fact]
public void CanCreateStandardRepoAndSpecifyAFolderWhichWillContainTheNewlyCreatedGitDirectory()
{
var scd1 = BuildSelfCleaningDirectory();
var scd2 = BuildSelfCleaningDirectory();
string repoPath = Repository.Init(scd1.DirectoryPath, scd2.DirectoryPath);
Assert.True(Repository.IsValid(repoPath));
using (var repo = new Repository(repoPath))
{
Assert.True(Repository.IsValid(repo.Info.WorkingDirectory));
Assert.True(Repository.IsValid(repo.Info.Path));
Assert.Equal(false, repo.Info.IsBare);
char sep = Path.DirectorySeparatorChar;
Assert.Equal(scd1.RootedDirectoryPath + sep, repo.Info.WorkingDirectory);
Assert.Equal(scd2.RootedDirectoryPath + sep + ".git" + sep, repo.Info.Path);
}
}
[Fact]
public void CanCreateStandardRepoAndDirectlySpecifyAGitDirectory()
{
var scd1 = BuildSelfCleaningDirectory();
var scd2 = BuildSelfCleaningDirectory();
var gitDir = Path.Combine(scd2.DirectoryPath, ".git/");
string repoPath = Repository.Init(scd1.DirectoryPath, gitDir);
Assert.True(Repository.IsValid(repoPath));
using (var repo = new Repository(repoPath))
{
Assert.True(Repository.IsValid(repo.Info.WorkingDirectory));
Assert.True(Repository.IsValid(repo.Info.Path));
Assert.Equal(false, repo.Info.IsBare);
char sep = Path.DirectorySeparatorChar;
Assert.Equal(scd1.RootedDirectoryPath + sep, repo.Info.WorkingDirectory);
Assert.Equal(Path.GetFullPath(gitDir), repo.Info.Path);
}
}
private static void CheckGitConfigFile(string dir)
{
string configFilePath = Path.Combine(dir, "config");
Assert.True(File.Exists(configFilePath));
string contents = File.ReadAllText(configFilePath);
Assert.NotEqual(-1, contents.IndexOf("repositoryformatversion = 0", StringComparison.Ordinal));
}
private static void AssertIsHidden(string repoPath)
{
//Workaround for .NET Core 1.x never considering a directory hidden if the path has a trailing slash
//https://github.com/dotnet/corefx/issues/18520
repoPath = repoPath.TrimEnd('/');
FileAttributes attribs = File.GetAttributes(repoPath);
Assert.Equal(FileAttributes.Hidden, (attribs & FileAttributes.Hidden));
}
[Fact]
public void CanFetchFromRemoteByName()
{
string remoteName = "testRemote";
string url = "http://github.com/libgit2/TestGitRepository";
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
repo.Network.Remotes.Add(remoteName, url);
// We will first fetch without specifying any Tag options.
// After we verify this fetch, we will perform a second fetch
// where we will download all tags, and verify that the
// nearly-dangling tag is now present.
// Set up structures for the expected results
// and verifying the RemoteUpdateTips callback.
TestRemoteInfo remoteInfo = TestRemoteInfo.TestRemoteInstance;
ExpectedFetchState expectedFetchState = new ExpectedFetchState(remoteName);
// Add expected branch objects
foreach (KeyValuePair<string, ObjectId> kvp in remoteInfo.BranchTips)
{
expectedFetchState.AddExpectedBranch(kvp.Key, ObjectId.Zero, kvp.Value);
}
// Add the expected tags
string[] expectedTagNames = { "blob", "commit_tree", "annotated_tag" };
foreach (string tagName in expectedTagNames)
{
TestRemoteInfo.ExpectedTagInfo expectedTagInfo = remoteInfo.Tags[tagName];
expectedFetchState.AddExpectedTag(tagName, ObjectId.Zero, expectedTagInfo);
}
// Perform the actual fetch
Commands.Fetch(repo, remoteName, new string[0], new FetchOptions { OnUpdateTips = expectedFetchState.RemoteUpdateTipsHandler }, null);
// Verify the expected state
expectedFetchState.CheckUpdatedReferences(repo);
// Now fetch the rest of the tags
Commands.Fetch(repo, remoteName, new string[0], new FetchOptions { TagFetchMode = TagFetchMode.All }, null);
// Verify that the "nearly-dangling" tag is now in the repo.
Tag nearlyDanglingTag = repo.Tags["nearly-dangling"];
Assert.NotNull(nearlyDanglingTag);
Assert.Equal(remoteInfo.Tags["nearly-dangling"].TargetId, nearlyDanglingTag.Target.Id);
}
}
[Fact]
public void CanReinitARepository()
{
string repoPath = InitNewRepository();
using (var repository = new Repository(repoPath))
{
string repoPath2 = Repository.Init(repoPath, false);
using (var repository2 = new Repository(repoPath2))
{
Assert.Equal(repository2.Info.Path, repository.Info.Path);
}
}
}
[Fact]
public void CreatingRepoWithBadParamsThrows()
{
Assert.Throws<ArgumentException>(() => Repository.Init(string.Empty));
Assert.Throws<ArgumentNullException>(() => Repository.Init(null));
}
private static void AssertInitializedRepository(IRepository repo, string expectedHeadTargetIdentifier)
{
Assert.NotNull(repo.Info.Path);
Assert.False(repo.Info.IsHeadDetached);
Assert.True(repo.Info.IsHeadUnborn);
Reference headRef = repo.Refs.Head;
Assert.NotNull(headRef);
Assert.Equal(expectedHeadTargetIdentifier, headRef.TargetIdentifier);
Assert.Null(headRef.ResolveToDirectReference());
Assert.NotNull(repo.Head);
Assert.True(repo.Head.IsCurrentRepositoryHead);
Assert.Equal(headRef.TargetIdentifier, repo.Head.CanonicalName);
Assert.Null(repo.Head.Tip);
Assert.Equal(0, repo.Commits.Count());
Assert.Equal(0, repo.Commits.QueryBy(new CommitFilter()).Count());
Assert.Equal(0, repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = repo.Refs.Head }).Count());
Assert.Equal(0, repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = repo.Head }).Count());
Assert.Equal(0, repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = "HEAD" }).Count());
Assert.Equal(0, repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = expectedHeadTargetIdentifier }).Count());
Assert.Null(repo.Head["subdir/I-do-not-exist"]);
Assert.Equal(0, repo.Branches.Count());
Assert.Equal(0, repo.Refs.Count());
Assert.Equal(0, repo.Tags.Count());
}
[Fact]
public void CanOpenBareRepositoryThroughAFullPathToTheGitDir()
{
string relPath = SandboxBareTestRepo();
string path = Path.GetFullPath(relPath);
using (var repo = new Repository(path))
{
Assert.NotNull(repo);
Assert.Null(repo.Info.WorkingDirectory);
}
}
[Fact]
public void CanOpenStandardRepositoryThroughAWorkingDirPath()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
Assert.NotNull(repo);
Assert.NotNull(repo.Info.WorkingDirectory);
}
}
[Fact]
public void OpeningStandardRepositoryThroughTheGitDirGuessesTheWorkingDirPath()
{
var path = SandboxStandardTestRepoGitDir();
using (var repo = new Repository(path))
{
Assert.NotNull(repo);
Assert.NotNull(repo.Info.WorkingDirectory);
}
}
[Fact]
public void CanOpenRepository()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.NotNull(repo.Info.Path);
Assert.Null(repo.Info.WorkingDirectory);
Assert.True(repo.Info.IsBare);
Assert.False(repo.Info.IsHeadDetached);
}
}
[Fact]
public void OpeningNonExistentRepoThrows()
{
Assert.Throws<RepositoryNotFoundException>(() => { new Repository("a_bad_path"); });
}
[Fact]
public void OpeningRepositoryWithBadParamsThrows()
{
Assert.Throws<ArgumentException>(() => new Repository(string.Empty));
Assert.Throws<ArgumentNullException>(() => new Repository(null));
}
[Fact]
public void CanLookupACommitByTheNameOfABranch()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
GitObject gitObject = repo.Lookup("refs/heads/master");
Assert.NotNull(gitObject);
Assert.IsType<Commit>(gitObject);
}
}
[Fact]
public void CanLookupACommitByTheNameOfALightweightTag()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
GitObject gitObject = repo.Lookup("refs/tags/lw");
Assert.NotNull(gitObject);
Assert.IsType<Commit>(gitObject);
}
}
[Fact]
public void CanLookupATagAnnotationByTheNameOfAnAnnotatedTag()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
GitObject gitObject = repo.Lookup("refs/tags/e90810b");
Assert.NotNull(gitObject);
Assert.IsType<TagAnnotation>(gitObject);
}
}
[Fact]
public void CanLookupObjects()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.NotNull(repo.Lookup(commitSha));
Assert.NotNull(repo.Lookup<Commit>(commitSha));
Assert.NotNull(repo.Lookup<GitObject>(commitSha));
}
}
[Fact]
public void CanLookupSameObjectTwiceAndTheyAreEqual()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
GitObject commit = repo.Lookup(commitSha);
GitObject commit2 = repo.Lookup(commitSha);
Assert.True(commit.Equals(commit2));
Assert.Equal(commit2.GetHashCode(), commit.GetHashCode());
}
}
[Fact]
public void LookupObjectByWrongShaReturnsNull()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Null(repo.Lookup(Constants.UnknownSha));
Assert.Null(repo.Lookup<GitObject>(Constants.UnknownSha));
}
}
[Fact]
public void LookupObjectByWrongTypeReturnsNull()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.NotNull(repo.Lookup(commitSha));
Assert.NotNull(repo.Lookup<Commit>(commitSha));
Assert.Null(repo.Lookup<TagAnnotation>(commitSha));
}
}
[Fact]
public void LookupObjectByUnknownReferenceNameReturnsNull()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Null(repo.Lookup("refs/heads/chopped/off"));
Assert.Null(repo.Lookup<GitObject>(Constants.UnknownSha));
}
}
[Fact]
public void CanLookupWhithShortIdentifers()
{
const string expectedAbbrevSha = "fe8410b";
const string expectedSha = expectedAbbrevSha + "6bfdf69ccfd4f397110d61f8070e46e40";
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
const string filename = "new.txt";
Touch(repo.Info.WorkingDirectory, filename, "one ");
Commands.Stage(repo, filename);
Signature author = Constants.Signature;
Commit commit = repo.Commit("Initial commit", author, author);
Assert.Equal(expectedSha, commit.Sha);
GitObject lookedUp1 = repo.Lookup(expectedSha);
Assert.Equal(commit, lookedUp1);
GitObject lookedUp2 = repo.Lookup(expectedAbbrevSha);
Assert.Equal(commit, lookedUp2);
}
}
[Fact]
public void CanLookupUsingRevparseSyntax()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Null(repo.Lookup<Tree>("master^"));
Assert.NotNull(repo.Lookup("master:new.txt"));
Assert.NotNull(repo.Lookup<Blob>("master:new.txt"));
Assert.NotNull(repo.Lookup("master^"));
Assert.NotNull(repo.Lookup<Commit>("master^"));
Assert.NotNull(repo.Lookup("master~3"));
Assert.NotNull(repo.Lookup("HEAD"));
Assert.NotNull(repo.Lookup("refs/heads/br2"));
}
}
[Fact]
public void CanResolveAmbiguousRevparseSpecs()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var o1 = repo.Lookup("e90810b"); // This resolves to a tag
Assert.Equal("7b4384978d2493e851f9cca7858815fac9b10980", o1.Sha);
var o2 = repo.Lookup("e90810b8"); // This resolves to a commit
Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", o2.Sha);
}
}
[Fact]
public void LookingUpWithBadParamsThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<ArgumentException>(() => repo.Lookup(string.Empty));
Assert.Throws<ArgumentException>(() => repo.Lookup<GitObject>(string.Empty));
Assert.Throws<ArgumentNullException>(() => repo.Lookup((string)null));
Assert.Throws<ArgumentNullException>(() => repo.Lookup((ObjectId)null));
Assert.Throws<ArgumentNullException>(() => repo.Lookup<Commit>((string)null));
Assert.Throws<ArgumentNullException>(() => repo.Lookup<Commit>((ObjectId)null));
}
}
[Fact]
public void LookingUpWithATooShortShaThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<AmbiguousSpecificationException>(() => repo.Lookup("e90"));
}
}
[Fact]
public void LookingUpByAWrongRevParseExpressionThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<InvalidSpecificationException>(() => repo.Lookup("tags/point_to_blob^{tree}"));
Assert.Throws<InvalidSpecificationException>(() => repo.Lookup("tags/point_to_blob^{commit}"));
Assert.Throws<InvalidSpecificationException>(() => repo.Lookup<Commit>("tags/point_to_blob^{commit}"));
Assert.Throws<InvalidSpecificationException>(() => repo.Lookup("master^{tree}^{blob}"));
Assert.Throws<InvalidSpecificationException>(() => repo.Lookup<Blob>("master^{blob}"));
Assert.Throws<PeelException>(() => repo.Lookup<Blob>("tags/e90810b^{blob}"));
}
}
[Fact]
public void LookingUpAGitLinkThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<ArgumentException>(() => repo.Lookup<GitLink>("e90810b"));
}
}
[Fact]
public void CanDiscoverABareRepoGivenTheRepoPath()
{
string path = Repository.Discover(BareTestRepoPath);
Assert.Equal(Path.GetFullPath(BareTestRepoPath + Path.DirectorySeparatorChar), path);
}
[Fact]
public void CanDiscoverABareRepoGivenASubDirectoryOfTheRepoPath()
{
string path = Repository.Discover(Path.Combine(BareTestRepoPath, "objects/4a"));
Assert.Equal(Path.GetFullPath(BareTestRepoPath + Path.DirectorySeparatorChar), path);
}
[Fact]
public void CanDiscoverAStandardRepoGivenTheRepoPath()
{
string path = Repository.Discover(StandardTestRepoPath);
Assert.Equal(Path.GetFullPath(StandardTestRepoPath + Path.DirectorySeparatorChar), path);
}
[Fact]
public void CanDiscoverAStandardRepoGivenASubDirectoryOfTheRepoPath()
{
string path = Repository.Discover(Path.Combine(StandardTestRepoPath, "objects/4a"));
Assert.Equal(Path.GetFullPath(StandardTestRepoPath + Path.DirectorySeparatorChar), path);
}
[Fact]
public void CanDiscoverAStandardRepoGivenTheWorkingDirPath()
{
string path = Sandbox(StandardTestRepoWorkingDirPath);
string found = Repository.Discover(path);
Assert.Equal(Path.GetFullPath(string.Format("{0}{1}.git{1}", path, Path.DirectorySeparatorChar)), found);
}
[Fact]
public void DiscoverReturnsNullWhenNoRepoCanBeFound()
{
string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
SelfCleaningDirectory scd = BuildSelfCleaningDirectory(path);
Directory.CreateDirectory(scd.RootedDirectoryPath);
Assert.Null(Repository.Discover(scd.RootedDirectoryPath));
}
[Fact]
public void CanDetectIfTheHeadIsOrphaned()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
string branchName = repo.Head.CanonicalName;
Assert.False(repo.Info.IsHeadUnborn);
repo.Refs.Add("HEAD", "refs/heads/orphan", true);
Assert.True(repo.Info.IsHeadUnborn);
repo.Refs.Add("HEAD", branchName, true);
Assert.False(repo.Info.IsHeadUnborn);
}
}
[Fact]
public void QueryingTheRemoteForADetachedHeadBranchReturnsNull()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
Console.WriteLine("head, {0}", repo.Head);
Commands.Checkout(repo, repo.Head.Tip.Sha, new CheckoutOptions() { CheckoutModifiers = CheckoutModifiers.Force });
Branch trackLocal = repo.Head;
Console.WriteLine("head, {0}", repo.Head);
Assert.Null(trackLocal.RemoteName);
}
}
[Fact]
public void ReadingEmptyRepositoryMessageReturnsNull()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Assert.Null(repo.Info.Message);
}
}
[Fact]
public void CanReadRepositoryMessage()
{
string testMessage = "This is a test message!";
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Touch(repo.Info.Path, "MERGE_MSG", testMessage);
Assert.Equal(testMessage, repo.Info.Message);
}
}
[Fact]
public void AccessingADeletedHeadThrows()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Assert.NotNull(repo.Head);
File.Delete(Path.Combine(repo.Info.Path, "HEAD"));
Assert.Throws<LibGit2SharpException>(() => repo.Head);
}
}
[Fact]
public void CanDetectShallowness()
{
var path = Sandbox(ShallowTestRepoPath);
using (var repo = new Repository(path))
{
Assert.True(repo.Info.IsShallow);
}
path = SandboxStandardTestRepoGitDir();
using (var repo = new Repository(path))
{
Assert.False(repo.Info.IsShallow);
}
}
[Fact]
public void CanCreateInMemoryRepository()
{
using (var repo = new Repository())
{
Assert.True(repo.Info.IsBare);
Assert.Null(repo.Info.Path);
Assert.Null(repo.Info.WorkingDirectory);
Assert.Throws<BareRepositoryException>(() => { var idx = repo.Index; });
}
}
[SkippableFact]
public void CanListRemoteReferencesWithCredentials()
{
InconclusiveIf(() => string.IsNullOrEmpty(Constants.PrivateRepoUrl),
"Populate Constants.PrivateRepo* to run this test");
IEnumerable<Reference> references = Repository.ListRemoteReferences(Constants.PrivateRepoUrl,
Constants.PrivateRepoCredentials);
foreach (var reference in references)
{
Assert.NotNull(reference);
}
}
[Theory]
[InlineData("http://github.com/libgit2/TestGitRepository")]
[InlineData("https://github.com/libgit2/TestGitRepository")]
[InlineData("git://github.com/libgit2/TestGitRepository.git")]
public void CanListRemoteReferences(string url)
{
IEnumerable<Reference> references = Repository.ListRemoteReferences(url).ToList();
List<Tuple<string, string>> actualRefs = references.
Select(reference => new Tuple<string, string>(reference.CanonicalName, reference.ResolveToDirectReference().TargetIdentifier)).ToList();
Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs.Count, actualRefs.Count);
Assert.True(references.Single(reference => reference.CanonicalName == "HEAD") is SymbolicReference);
for (int i = 0; i < TestRemoteRefs.ExpectedRemoteRefs.Count; i++)
{
Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs[i].Item2, actualRefs[i].Item2);
Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs[i].Item1, actualRefs[i].Item1);
}
}
[Fact]
public void CanListRemoteReferencesWithDetachedRemoteHead()
{
string originalRepoPath = SandboxStandardTestRepo();
string detachedHeadSha;
using (var originalRepo = new Repository(originalRepoPath))
{
detachedHeadSha = originalRepo.Head.Tip.Sha;
Commands.Checkout(originalRepo, detachedHeadSha);
Assert.True(originalRepo.Info.IsHeadDetached);
}
IEnumerable<Reference> references = Repository.ListRemoteReferences(originalRepoPath);
Reference head = references.SingleOrDefault(reference => reference.CanonicalName == "HEAD");
Assert.NotNull(head);
Assert.True(head is DirectReference);
Assert.Equal(detachedHeadSha, head.TargetIdentifier);
}
[Theory]
[InlineData("http://github.com/libgit2/TestGitRepository")]
public void ReadingReferenceRepositoryThroughListRemoteReferencesThrows(string url)
{
IEnumerable<Reference> references = Repository.ListRemoteReferences(url);
foreach (var reference in references)
{
IBelongToARepository repositoryReference = reference;
Assert.Throws<InvalidOperationException>(() => repositoryReference.Repository);
}
}
[Theory]
[InlineData("http://github.com/libgit2/TestGitRepository")]
public void ReadingReferenceTargetFromListRemoteReferencesThrows(string url)
{
IEnumerable<Reference> references = Repository.ListRemoteReferences(url);
foreach (var reference in references)
{
Assert.Throws<InvalidOperationException>(() =>
{
var target = reference.ResolveToDirectReference().Target;
});
}
}
}
}
| 36.878827 | 152 | 0.577353 | [
"MIT"
] | 7b3cbaf1/GTA | LibGit2Sharp.Tests/RepositoryFixture.cs | 28,915 | C# |
// <copyright file="AspNetMvc5.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
#if NET461
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Datadog.Trace.TestHelpers;
using Xunit;
using Xunit.Abstractions;
#pragma warning disable SA1402 // File may only contain a single class
#pragma warning disable SA1649 // File name must match first type name
namespace Datadog.Trace.Security.IntegrationTests
{
[Collection("IisTests")]
public class AspNetMvc5CallTargetIntegratedWithSecurity : AspNetMvc5
{
public AspNetMvc5CallTargetIntegratedWithSecurity(IisFixture iisFixture, ITestOutputHelper output)
: base(iisFixture, output, classicMode: false, enableSecurity: true, blockingEnabled: true)
{
}
}
[Collection("IisTests")]
public class AspNetMvc5CallTargetIntegratedWithSecurityWithoutBlocking : AspNetMvc5
{
public AspNetMvc5CallTargetIntegratedWithSecurityWithoutBlocking(IisFixture iisFixture, ITestOutputHelper output)
: base(iisFixture, output, classicMode: false, enableSecurity: true, blockingEnabled: false)
{
}
}
[Collection("IisTests")]
public class AspNetMvc5CallTargetIntegratedWithoutSecurity : AspNetMvc5
{
public AspNetMvc5CallTargetIntegratedWithoutSecurity(IisFixture iisFixture, ITestOutputHelper output)
: base(iisFixture, output, classicMode: false, enableSecurity: false, blockingEnabled: false)
{
}
}
[Collection("IisTests")]
public class AspNetMvc5CallTargetClassicWithSecurity : AspNetMvc5
{
public AspNetMvc5CallTargetClassicWithSecurity(IisFixture iisFixture, ITestOutputHelper output)
: base(iisFixture, output, classicMode: true, enableSecurity: true, blockingEnabled: true)
{
}
}
[Collection("IisTests")]
public class AspNetMvc5CallTargetClassicWithSecurityWithoutBlocking : AspNetMvc5
{
public AspNetMvc5CallTargetClassicWithSecurityWithoutBlocking(IisFixture iisFixture, ITestOutputHelper output)
: base(iisFixture, output, classicMode: true, enableSecurity: true, blockingEnabled: false)
{
}
}
[Collection("IisTests")]
public class AspNetMvc5CallTargetClassicWithoutSecurity : AspNetMvc5
{
public AspNetMvc5CallTargetClassicWithoutSecurity(IisFixture iisFixture, ITestOutputHelper output)
: base(iisFixture, output, classicMode: true, enableSecurity: false, blockingEnabled: false)
{
}
}
public abstract class AspNetMvc5 : AspNetBase, IClassFixture<IisFixture>
{
private readonly IisFixture _iisFixture;
private readonly bool _enableSecurity;
private readonly bool _blockingEnabled;
private readonly string _testName;
public AspNetMvc5(IisFixture iisFixture, ITestOutputHelper output, bool classicMode, bool enableSecurity, bool blockingEnabled)
: base(nameof(AspNetMvc5), output, @"test\test-applications\security\aspnet")
{
SetCallTargetSettings(true);
SetSecurity(enableSecurity);
SetAppSecBlockingEnabled(blockingEnabled);
_iisFixture = iisFixture;
_enableSecurity = enableSecurity;
_blockingEnabled = blockingEnabled;
_iisFixture.TryStartIis(this, classicMode ? IisAppType.AspNetClassic : IisAppType.AspNetIntegrated);
_testName = nameof(AspNetMvc5)
+ (classicMode ? ".Classic" : ".Integrated")
+ (RuntimeInformation.ProcessArchitecture == Architecture.X64 ? ".X64" : ".X86"); // assume that arm is the same
SetHttpPort(iisFixture.HttpPort);
}
[Trait("Category", "EndToEnd")]
[Trait("RunOnWindows", "True")]
[Trait("LoadFromGAC", "True")]
[Fact]
public Task TestSecurity()
{
// if blocking is enabled, request stops before reaching asp net mvc integrations intercepting before action methods, so no more spans are generated
// NOTE: by integrating the latest version of the WAF, blocking was disabled, as it does not support blocking yet
return TestBlockedRequestAsync(_iisFixture.Agent, _enableSecurity, _enableSecurity && _blockingEnabled ? HttpStatusCode.OK : HttpStatusCode.OK, _enableSecurity && _blockingEnabled ? 10 : 10, new Action<TestHelpers.MockTracerAgent.Span>[]
{
s => Assert.Matches("aspnet(-mvc)?.request", s.Name),
s => Assert.Equal("sample", s.Service),
s => Assert.Equal("web", s.Type)
});
}
}
}
#endif
| 42.803419 | 249 | 0.696685 | [
"Apache-2.0"
] | ganeshkumarsv/dd-trace-dotnet | test/Datadog.Trace.Security.IntegrationTests/AspNetMvc5.cs | 5,008 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WPFChatClientServer.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.766667 | 151 | 0.585275 | [
"MIT"
] | vacnex/C--WPF-Client-Server-chat-application | WPFChatClientServer/Properties/Settings.Designer.cs | 1,075 | C# |
using System.Threading.Tasks;
namespace AdjustNamespace.Adjusting.Fixer
{
public interface IFixer
{
void AddSubject(object o);
Task FixAsync(string filePath);
}
}
| 15 | 41 | 0.671795 | [
"MIT"
] | lsoft/AdjustNamespace | AdjustNamespace.VsixShared/Adjusting/Fixer/IFixer.cs | 197 | C# |
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
namespace EasyAbp.EShop.Baskets.EntityFrameworkCore
{
[ConnectionStringName(BasketsDbProperties.ConnectionStringName)]
public interface IBasketsDbContext : IEfCoreDbContext
{
/* Add DbSet for each Aggregate Root here. Example:
* DbSet<Question> Questions { get; }
*/
}
} | 28.538462 | 68 | 0.714286 | [
"Apache-2.0"
] | p041911070/EShop | modules/EasyAbp.EShop.Baskets/src/EasyAbp.EShop.Baskets.EntityFrameworkCore/EntityFrameworkCore/IBasketsDbContext.cs | 373 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.