content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Gui;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Model;
using EditorObjects.SaveClasses;
#if !FRB_MDX
using FlatRedBall.Graphics.Animation3D;
#endif
using FlatRedBall.IO;
namespace EditorObjects.Gui
{
public class PositionedModelPropertyGrid : PropertyGrid<PositionedModel>
{
#region Fields
ComboBox mCurrentAnimationComboBox;
Button mAddAnimationButton;
Button mRemoveAllAnimationDataButton;
ListDisplayWindow mAnimationListDisplayWindow;
FileTextBox mHierarchyFileTextBox;
#endregion
#region Properties
public static List<BuildToolAssociation> BuildToolAssociationList
{
get;
set;
}
public override PositionedModel SelectedObject
{
get
{
return base.SelectedObject;
}
set
{
base.SelectedObject = value;
if (!Visible && (SelectedObject != null))
{
GuiManager.BringToFront(this);
}
Visible = (SelectedObject != null);
}
}
#endregion
#region Event Methods
void AddAnimationClick(Window callingWindow)
{
FileWindow fileWindow = GuiManager.AddFileWindow();
List<string> fileTypes = new List<string>(2);
fileTypes.Add("waa");
fileTypes.Add("wam");
fileWindow.SetFileType(fileTypes);
fileWindow.SetToLoad();
fileWindow.OkClick += new GuiMessage(AddAnimationOK);
}
void AddAnimationOK(Window callingWindow)
{
#if !FRB_MDX
string sourceFile = ((FileWindow)callingWindow).Results[0];
string destinationFile = "";
string extension = FileManager.GetExtension(sourceFile);
BuildToolAssociation toolForExtension = GetToolForExtension(extension);
if (toolForExtension != null)
{
destinationFile =
FileManager.UserApplicationDataForThisApplication +
FileManager.RemovePath(FileManager.RemoveExtension(sourceFile)) + "." + toolForExtension.DestinationFileType;
toolForExtension.PerformBuildOn(sourceFile, destinationFile, null, null, null);
}
else
{
destinationFile = sourceFile;
}
mAnimationListDisplayWindow.UpdateToList();
#endif
}
#if FRB_XNA
void RemoveAllAnimationButtonClick(Window callingWindow)
{
OkCancelWindow window = GuiManager.ShowOkCancelWindow("Are you sure you want to remove all animation information from this model?" +
"All objects attached to any joints will be detached.", "Remove anim info");
window.OkText = "Yes";
window.CancelText = "No";
window.OkClick += new GuiMessage(OnRemoveAllAnimationOk);
}
void OnRemoveAllAnimationOk(Window callingWindow)
{
SelectedObject.Animate = false;
for (int i = SelectedObject.Children.Count - 1; i > -1; i--)
{
PositionedObject child = SelectedObject.Children[i];
if (!string.IsNullOrEmpty(child.ParentBone))
{
child.Detach();
}
}
}
#endif
void ShowAnimationPropertyGrid(Window callingWindow)
{
GuiManager.ObjectDisplayManager.GetObjectDisplayerForObject(mAnimationListDisplayWindow.GetFirstHighlightedObject());
}
void StrongSelectAnimation(Window callingWindow)
{
}
void LoadSkeleton(Window callingWindow)
{
#if !FRB_MDX
FileTextBox fileTextBox = callingWindow as FileTextBox;
string sourceFile = fileTextBox.Text;
string destinationFile = "";
string extension = FileManager.GetExtension(sourceFile);
BuildToolAssociation toolForExtension = GetToolForExtension(extension);
if (toolForExtension != null)
{
destinationFile =
FileManager.UserApplicationDataForThisApplication +
FileManager.RemovePath(FileManager.RemoveExtension(sourceFile)) + "." + toolForExtension.DestinationFileType;
toolForExtension.PerformBuildOn(sourceFile, destinationFile, null, null, null);
}
else
{
destinationFile = sourceFile;
}
#endif
}
#endregion
#region Methods
#region Constructor
public PositionedModelPropertyGrid(Cursor cursor)
: base(cursor)
{
ExcludeAllMembers();
#region Include Basic Members
IncludeMember("X", "Basic");
IncludeMember("Y", "Basic");
IncludeMember("Z", "Basic");
IncludeMember("RotationX", "Basic");
IncludeMember("RotationY", "Basic");
IncludeMember("RotationZ", "Basic");
// IncludeMember("Visible", "Basic");
IncludeMember("CursorSelectable", "Basic");
IncludeMember("Name", "Basic");
IncludeMember("IsAutomaticallyUpdated", "Basic");
IncludeMember("Visible", "Basic");
#endregion
#region Include "Scale" members
IncludeMember("ScaleX", "Scale");
IncludeMember("ScaleY", "Scale");
IncludeMember("ScaleZ", "Scale");
#if !FRB_MDX
IncludeMember("FlipX", "Scale");
IncludeMember("FlipY", "Scale");
IncludeMember("FlipZ", "Scale");
#endif
#endregion
#region Include "Rendering" members
IncludeMember("FaceCullMode", "Rendering");
#endregion
#region Include Relative Members
IncludeMember("RelativeX", "Relative");
IncludeMember("RelativeY", "Relative");
IncludeMember("RelativeZ", "Relative");
IncludeMember("RelativeRotationX", "Relative");
IncludeMember("RelativeRotationY", "Relative");
IncludeMember("RelativeRotationZ", "Relative");
#endregion
#region Include Animation Members
#if FRB_XNA
//IncludeMember("HasAnimation", "Animation");
//IncludeMember("Animate", "Animation");
//IncludeMember("CurrentAnimation", "Animation");
//mCurrentAnimationComboBox = new ComboBox(GuiManager.Cursor);
//mCurrentAnimationComboBox.ScaleX = 6;
//ReplaceMemberUIElement("CurrentAnimation", mCurrentAnimationComboBox);
mHierarchyFileTextBox = new FileTextBox(GuiManager.Cursor);
mHierarchyFileTextBox.ScaleY = 1.5f;
mHierarchyFileTextBox.ScaleX = 15;
List<string> fileTypes = new List<string>();
fileTypes.Add("wbi");
fileTypes.Add("whe");
mHierarchyFileTextBox.SetFileType(fileTypes);
this.AddWindow(mHierarchyFileTextBox, "Animation");
mHierarchyFileTextBox.FileSelect += new GuiMessage(LoadSkeleton);
mAnimationListDisplayWindow = new ListDisplayWindow(cursor);
mAnimationListDisplayWindow.ScaleX = 15;
mAnimationListDisplayWindow.ScaleY = 15;
mAnimationListDisplayWindow.ListBox.StrongSelect += new GuiMessage(StrongSelectAnimation);
mAnimationListDisplayWindow.ListBox.Highlight += new GuiMessage(ShowAnimationPropertyGrid);
this.AddWindow(mAnimationListDisplayWindow, "Animation");
mAddAnimationButton = new Button(GuiManager.Cursor);
mAddAnimationButton.Text = "Add Animation";
mAddAnimationButton.ScaleX = 8.5f;
mAddAnimationButton.ScaleY = 1.5f;
this.AddWindow(mAddAnimationButton, "Animation");
mAddAnimationButton.Click += new GuiMessage(AddAnimationClick);
mRemoveAllAnimationDataButton = new Button(cursor);
mRemoveAllAnimationDataButton.Text = "Remove All Anim Data";
mRemoveAllAnimationDataButton.ScaleX = 8.5f;
mRemoveAllAnimationDataButton.ScaleY = 1.5f;
this.AddWindow(mRemoveAllAnimationDataButton, "Animation");
mRemoveAllAnimationDataButton.Click += new GuiMessage(RemoveAllAnimationButtonClick);
mAnimationListDisplayWindow.EnableRemovingFromList();
#endif
#endregion
#region Remove Uncategorized and set default category
RemoveCategory("Uncategorized");
SelectCategory("Basic");
#endregion
#if FRB_XNA
PropertyGrid.SetPropertyGridTypeAssociation(typeof(Animation3DInstance), typeof(Animation3DInstancePropertyGrid));
#endif
ShowIColorableProperties();
this.X = this.ScaleX;
this.Y = this.ScaleY + Window.MoveBarHeight + 3;
}
#endregion
#region Public Methods
public void ShowIColorableProperties()
{
IncludeMember("ColorOperation", "Color");
IncludeMember("Red", "Color");
IncludeMember("Green", "Color");
IncludeMember("Blue", "Color");
}
private BuildToolAssociation GetToolForExtension(string extension)
{
if (BuildToolAssociationList == null)
{
return null;
}
foreach (BuildToolAssociation bta in BuildToolAssociationList)
{
if (bta.SourceFileType == extension)
{
return bta;
}
}
return null;
}
public override void UpdateDisplayedProperties()
{
base.UpdateDisplayedProperties();
#if !FRB_MDX
#endif
}
#endregion
#endregion
}
}
| 28.220386 | 145 | 0.590102 | [
"MIT"
] | coldacid/FlatRedBall | FRBDK/FRBDK Supporting Projects/EditorObjects/Gui/PositionedModelPropertyGrid.cs | 10,244 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicMan : MonoBehaviour
{
public Level currentLevel;
private AudioSource _audioSource;
public void UpdateLevel(Level newLevel)
{
currentLevel = newLevel;
if (currentLevel.MusicIntro != null)
{
_audioSource.loop = false;
_audioSource.clip = currentLevel.MusicIntro;
_audioSource.Play();
}
}
// Start is called before the first frame update
void Start()
{
_audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (!_audioSource.isPlaying)
{
_audioSource.clip = currentLevel.MusicLoop;
_audioSource.Play();
_audioSource.loop = true;
}
}
}
| 22.307692 | 56 | 0.601149 | [
"MIT"
] | BadRAM/Miz-Jam-1 | Assets/Scripts/MusicMan.cs | 872 | 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("MarkovChain")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MarkovChain")]
[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("e96c0900-b2fb-4e53-a86a-fb0f62474a21")]
// 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.702703 | 84 | 0.744803 | [
"MIT"
] | schnappischnap/MarkovChain | MarkovChain/Properties/AssemblyInfo.cs | 1,398 | C# |
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using XFPINView.Helpers;
namespace XFPINView
{
public partial class PINView : ContentView
{
#region Fields
/// <summary>
/// A TapGuesture Recognizer to invoke when user tap on any PIN box.
/// This will help bring up the soft keyboard
/// </summary>
private readonly TapGestureRecognizer boxTapGestureRecognizer;
/// <summary>
/// An event which is raised/invoked when PIN entry is completed
/// This will help user to execute any code when entry completed
/// </summary>
public event EventHandler<PINCompletedEventArgs> PINEntryCompleted;
#endregion
#region Constructor and Initializations
public PINView()
{
InitializeComponent();
hiddenTextEntry.TextChanged += PINView_TextChanged;
boxTapGestureRecognizer = new TapGestureRecognizer() { Command = new Command(() => { BoxTapCommandExecute(); }) };
CreateControl();
}
/// <summary>
/// Calling this, will bring up the soft keyboard, or will help focus the control
/// </summary>
public void FocusBox()
{
boxTapGestureRecognizer?.Command?.Execute(null);
}
#endregion
#region Methods
/// <summary>
/// Initializes the UI for the PINView
/// </summary>
public void CreateControl()
{
hiddenTextEntry.MaxLength = PINLength;
var count = PINBoxContainer.Children.Count;
if (count < PINLength)
{
int newBoxesToAdd = PINLength - count;
for (int i = 1; i <= newBoxesToAdd; i++)
{
BoxTemplate boxTemplate = CreateBox();
PINBoxContainer.Children.Add(boxTemplate);
}
}
else if (count > PINLength)
{
int boxesToRemove = count - PINLength;
for (int i = 1; i <= boxesToRemove; i++)
{
PINBoxContainer.Children.RemoveAt(PINBoxContainer.Children.Count - 1);
}
}
}
/// <summary>
/// Creates the instance of one single PIN box UI
/// </summary>
/// <returns></returns>
private BoxTemplate CreateBox()
{
BoxTemplate boxTemplate = new BoxTemplate();
boxTemplate.HeightRequest = BoxSize;
boxTemplate.WidthRequest = BoxSize;
boxTemplate.Box.BackgroundColor = BoxBackgroundColor;
SetRadius(boxTemplate, BoxShape);
boxTemplate.GestureRecognizers.Add(boxTapGestureRecognizer);
return boxTemplate;
}
/// <summary>
/// Applies the Corner Radius to the PIN Box based on the ShapeType
/// </summary>
/// <param name="boxTemplate"></param>
/// <param name="shapeType"></param>
private void SetRadius(BoxTemplate boxTemplate, BoxShapeType shapeType)
{
if (shapeType == BoxShapeType.Circle)
{
boxTemplate.Box.CornerRadius = (float)boxTemplate.Box.HeightRequest / 2;
}
else if (shapeType == BoxShapeType.Squere)
{
boxTemplate.Box.CornerRadius = 0;
}
else if (shapeType == BoxShapeType.RoundCorner)
{
boxTemplate.Box.CornerRadius = 10;
}
}
#endregion
#region Events
/// <summary>
/// Invokes when user type the PIN or text changes in the hidden textbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PINView_TextChanged(object sender, TextChangedEventArgs e)
{
PINValue = e.NewTextValue;
if (e.NewTextValue.Length == PINLength)
{
PINEntryCompleted?.Invoke(this, new PINCompletedEventArgs(PINValue));
PINEntryCompletedCommand?.Execute(PINValue);
// Dismiss the keyboard, once entry is completed up to the defined length and if AutoDismissKeyboard property is true
if (AutoDismissKeyboard == true)
{
(sender as Entry).Unfocus();
}
}
}
#endregion
#region Commands and Executes
/// <summary>
/// Invokes when user tap on the PINView, this will bring up the soft keyboard
/// </summary>
private async void BoxTapCommandExecute()
{
if (Device.RuntimePlatform == Device.UWP)
{
// https://xamarin.github.io/bugzilla-archives/55/55245/bug.html
await Task.Delay(1);
}
hiddenTextEntry.Focus();
}
#endregion
}
}
| 32.296774 | 134 | 0.544946 | [
"MIT"
] | xamarindevelopervietnam/XFPINView | XFPINView/PINView.xaml.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 ProvinceMapper.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.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;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("D:\\Victoria 2\\map")]
public string srcMapFolder
{
get
{
return ((string)(this["srcMapFolder"]));
}
set
{
this["srcMapFolder"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("D:\\Hearts of Iron III\\map")]
public string destMapFolder
{
get
{
return ((string)(this["destMapFolder"]));
}
set
{
this["destMapFolder"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("vic")]
public string srcTag
{
get
{
return ((string)(this["srcTag"]));
}
set
{
this["srcTag"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("hoi")]
public string destTag
{
get
{
return ((string)(this["destTag"]));
}
set
{
this["destTag"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("province_mappings.txt")]
public string mappingFile
{
get
{
return ((string)(this["mappingFile"]));
}
set
{
this["mappingFile"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool fitMaps
{
get
{
return ((bool)(this["fitMaps"]));
}
set
{
this["fitMaps"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool showRivers
{
get
{
return ((bool)(this["showRivers"]));
}
set
{
this["showRivers"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Localization")]
public string namesFrom
{
get
{
return ((string)(this["namesFrom"]));
}
set
{
this["namesFrom"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool invertSource
{
get
{
return ((bool)(this["invertSource"]));
}
set
{
this["invertSource"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool invertDest
{
get
{
return ((bool)(this["invertDest"]));
}
set
{
this["invertDest"] = value;
}
}
}
}
| 24.40884 | 148 | 0.671118 | [
"MIT"
] | IhateTrains/provinceMapper | Properties/Settings.Designer.cs | 4,420 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HurtPlayer : MonoBehaviour
{
public bool killAtOnce = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (killAtOnce)
{
if (other.tag == "Player")
{
HealthManager.instance.HurtDeath();
}
}
else
{
if (other.tag == "Player")
{
HealthManager.instance.Hurt();
}
}
}
} | 19 | 52 | 0.511696 | [
"MIT"
] | uvg-cc3063/proyecto-libre-alejandro-diego-ukron | Assets/Scripts/HurtPlayer.cs | 686 | C# |
#region Using Statements
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
#endregion
namespace Delight
{
/// <summary>
/// Controls a collection of animators.
/// </summary>
public class Animation : List<Animator>
{
#region Methods
/// <summary>
/// Starts the animation.
/// </summary>
public Task Animate(LayoutRoot layoutRoot, float initialDelay, string currentState)
{
return Task.WhenAll(this.Select(x => x.Animate(layoutRoot, initialDelay, currentState)));
}
/// <summary>
/// Stops the animation.
/// </summary>
public void StopAnimation()
{
for (int i = 0; i < Count; ++i)
{
this[i].StopAnimation();
}
}
/// <summary>
/// Resets and stops animation.
/// </summary>
public void ResetAndStopAnimation()
{
for (int i = 0; i < Count; ++i)
{
this[i].ResetAndStopAnimation();
}
}
/// <summary>
/// Reverses the animation. Resumes the animation if paused.
/// </summary>
public void ReverseAnimation()
{
for (int i = 0; i < Count; ++i)
{
this[i].ReverseAnimation();
}
}
/// <summary>
/// Pauses animation.
/// </summary>
public void PauseAnimation()
{
for (int i = 0; i < Count; ++i)
{
this[i].PauseAnimation();
}
}
/// <summary>
/// Resumes paused animation.
/// </summary>
public void ResumeAnimation()
{
for (int i = 0; i < Count; ++i)
{
this[i].ResumeAnimation();
}
}
/// <summary>
/// Resets the animation to its initial state (doesn't stop it).
/// </summary>
public void ResetAnimation()
{
for (int i = 0; i < Count; ++i)
{
this[i].ResetAnimation();
}
}
#endregion
#region Properties
/// <summary>
/// Gets a boolean indicating whether this animation is active.
/// </summary>
public virtual bool IsRunning
{
get
{
return this.Any(x => x.IsRunning);
}
}
/// <summary>
/// Gets a boolean indicating whether this animation is reversing.
/// </summary>
public virtual bool IsReversing
{
get
{
return this.Any(x => x.IsReversing);
}
}
/// <summary>
/// Gets a boolean indicating whether this animation is completed.
/// </summary>
public virtual bool IsCompleted
{
get
{
return this.All(x => x.IsCompleted);
}
set
{
this.ForEach(x => x.IsCompleted = value);
}
}
/// <summary>
/// Gets a boolean indicating whether this animation is paused.
/// </summary>
public virtual bool IsPaused
{
get
{
return this.All(x => x.IsPaused);
}
}
#endregion
}
}
| 23.844595 | 101 | 0.452536 | [
"MIT"
] | delight-dev/Delight | UnityProject/Delight/Assets/Delight/Source/Animation.cs | 3,531 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Starlight.Server.Data;
namespace Starlight.Server.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200810062846_AddInitialCharactersModel")]
partial class AddInitialCharactersModel
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
.HasAnnotation("ProductVersion", "3.1.6")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("Starlight.Server.Models.Character", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ModifiedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int?>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Character");
});
modelBuilder.Entity("Starlight.Server.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ModifiedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PasswordSalt")
.HasColumnType("text");
b.Property<string>("Username")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Starlight.Server.Models.Character", b =>
{
b.HasOne("Starlight.Server.Models.User", null)
.WithMany("Characters")
.HasForeignKey("UserId");
});
#pragma warning restore 612, 618
}
}
}
| 37.034483 | 128 | 0.548107 | [
"MIT"
] | Eclipse-Origins/Starlight | src/Starlight.Server/Data/Migrations/20200810062846_AddInitialCharactersModel.Designer.cs | 3,224 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("WindowsFormsApp1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsFormsApp1")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("aa7a5908-da1f-4c05-a223-04b9b8900a7e")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.783784 | 99 | 0.765157 | [
"MIT"
] | Kola14/CalculatorWinForms | CalculatorWinForms/Properties/AssemblyInfo.cs | 2,015 | C# |
// -----------------------------------------------------------------------
// <copyright file="RoleInputDto.cs" company="OSharp开源团队">
// Copyright (c) 2014-2015 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2015-10-14 3:38</last-date>
// -----------------------------------------------------------------------
using System.ComponentModel.DataAnnotations;
using OSharp.Core.Data;
namespace OSharp.Demo.Dtos.Identity
{
public class RoleInputDto : IInputDto<int>
{
/// <summary>
/// 获取或设置 角色名称
/// </summary>
[Required, StringLength(50)]
public string Name { get; set; }
/// <summary>
/// 获取或设置 角色描述
/// </summary>
[StringLength(500)]
public string Remark { get; set; }
/// <summary>
/// 获取或设置 是否是管理员
/// </summary>
public bool IsAdmin { get; set; }
/// <summary>
/// 获取或设置 是否系统角色
/// </summary>
public bool IsSystem { get; set; }
/// <summary>
/// 获取或设置 是否锁定
/// </summary>
public bool IsLocked { get; set; }
/// <summary>
/// 获取或设置 组织机构编号
/// </summary>
public int? OrganizationId { get; set; }
/// <summary>
/// 获取或设置 主键,唯一标识
/// </summary>
public int Id { get; set; }
}
} | 25.535714 | 75 | 0.462937 | [
"Apache-2.0"
] | VictorTzeng/osharp | samples/OSharp.Demo.Core/Dtos/Identity/RoleInputDto.cs | 1,590 | C# |
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Roslynator.CSharp.Analysis
{
public static class ConvertMethodGroupToAnonymousFunctionAnalysis
{
public static bool IsFixable(IdentifierNameSyntax identifierName, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (CanBeMethodGroup(identifierName))
{
IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(identifierName, cancellationToken);
if (methodSymbol != null)
return true;
}
return false;
}
public static bool IsFixable(MemberAccessExpressionSyntax memberAccessExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (CanBeMethodGroup(memberAccessExpression))
{
IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(memberAccessExpression, cancellationToken);
if (methodSymbol != null)
return true;
}
return false;
}
public static bool CanBeMethodGroup(ExpressionSyntax expression)
{
expression = expression.WalkUpParentheses();
SyntaxNode parent = expression.Parent;
switch (parent.Kind())
{
case SyntaxKind.Argument:
case SyntaxKind.ArrayInitializerExpression:
case SyntaxKind.ArrowExpressionClause:
case SyntaxKind.CollectionInitializerExpression:
case SyntaxKind.EqualsValueClause:
case SyntaxKind.ReturnStatement:
case SyntaxKind.YieldReturnStatement:
return true;
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.CoalesceAssignmentExpression:
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
return object.ReferenceEquals(((AssignmentExpressionSyntax)parent).Right, expression);
case SyntaxKind.SwitchExpressionArm:
return object.ReferenceEquals(((SwitchExpressionArmSyntax)parent).Expression, expression);
default:
return false;
}
}
}
}
| 38.820896 | 156 | 0.640907 | [
"Apache-2.0"
] | ProphetLamb-Organistion/Roslynator | src/Common/CSharp/Analysis/ConvertMethodGroupToAnonymousFunctionAnalysis.cs | 2,603 | C# |
using System;
using System.IO;
using System.Text;
using static WinSW.Native.ConsoleApis;
namespace WinSW.Native
{
internal static class ConsoleEx
{
internal static Handle OpenConsoleInput()
{
return FileApis.CreateFileW(
"CONIN$",
FileApis.GenericAccess.Read | FileApis.GenericAccess.Write,
FileShare.Read | FileShare.Write,
IntPtr.Zero,
FileMode.Open,
0,
IntPtr.Zero);
}
internal static Handle OpenConsoleOutput()
{
return FileApis.CreateFileW(
"CONOUT$",
FileApis.GenericAccess.Write,
FileShare.Write,
IntPtr.Zero,
FileMode.Open,
0,
IntPtr.Zero);
}
/// <exception cref="CommandException" />
internal static string ReadPassword()
{
using var consoleInput = OpenConsoleInput();
using var consoleOutput = OpenConsoleOutput();
if (!GetConsoleMode(consoleInput, out uint mode))
{
Throw.Command.Win32Exception("Failed to get console mode.");
}
uint newMode = mode;
newMode &= ~ENABLE_PROCESSED_INPUT;
newMode &= ~ENABLE_LINE_INPUT;
newMode &= ~ENABLE_ECHO_INPUT;
newMode &= ~ENABLE_MOUSE_INPUT;
if (newMode != mode)
{
if (!SetConsoleMode(consoleInput, newMode))
{
Throw.Command.Win32Exception("Failed to set console mode.");
}
}
try
{
var buffer = new StringBuilder();
while (true)
{
if (!ReadConsoleW(consoleInput, out char key, 1, out _, IntPtr.Zero))
{
Throw.Command.Win32Exception("Failed to read console.");
}
if (key == (char)3)
{
// Ctrl+C
Write(consoleOutput, Environment.NewLine);
Throw.Command.Win32Exception(Errors.ERROR_CANCELLED);
}
else if (key == '\r')
{
Write(consoleOutput, Environment.NewLine);
break;
}
else if (key == '\b')
{
if (buffer.Length > 0)
{
buffer.Remove(buffer.Length - 1, 1);
Write(consoleOutput, "\b \b");
}
}
else
{
buffer.Append(key);
Write(consoleOutput, "*");
}
}
return buffer.ToString();
}
finally
{
if (newMode != mode)
{
if (!SetConsoleMode(consoleInput, mode))
{
Throw.Command.Win32Exception("Failed to set console mode.");
}
}
}
}
internal static void Write(Handle consoleOutput, string value)
{
if (!WriteConsoleW(consoleOutput, value, value.Length, out _, IntPtr.Zero))
{
Throw.Command.Win32Exception("Failed to write console.");
}
}
}
}
| 30.680672 | 89 | 0.421802 | [
"MIT"
] | 15806122600/winsw | src/WinSW.Core/Native/ConsoleEx.cs | 3,653 | C# |
// <auto-generated />
using Ejercicio3;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Ejercicio3.Migrations
{
[DbContext(typeof(SustitucionesContext))]
[Migration("20201122223723_CreateSustitucionesDB")]
partial class CreateSustitucionesDB
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0");
modelBuilder.Entity("Ejercicio3.Sustituciones", b =>
{
b.Property<int>("SustitucionesId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Texto")
.HasColumnType("nvarchar(max)");
b.Property<int>("idPadre")
.HasColumnType("int");
b.HasKey("SustitucionesId");
b.ToTable("Sustituciones");
b.HasDiscriminator<string>("Discriminator").HasValue("Sustituciones");
});
modelBuilder.Entity("Ejercicio3.SustitucionesCompuestas", b =>
{
b.HasBaseType("Ejercicio3.Sustituciones");
b.HasDiscriminator().HasValue("SustitucionesCompuestas");
});
modelBuilder.Entity("Ejercicio3.SustitucionesTeclado", b =>
{
b.HasBaseType("Ejercicio3.Sustituciones");
b.HasDiscriminator().HasValue("SustitucionesTeclado");
});
modelBuilder.Entity("Ejercicio3.SustitucionesTexto", b =>
{
b.HasBaseType("Ejercicio3.Sustituciones");
b.HasDiscriminator().HasValue("SustitucionesTexto");
});
#pragma warning restore 612, 618
}
}
}
| 34.140845 | 90 | 0.560231 | [
"MIT"
] | fcojaviCervera/EjerciciosVocali | Ejercicio3/Migrations/20201122223723_CreateSustitucionesDB.Designer.cs | 2,426 | C# |
// Copyright (c) The Vignette Authors
// Licensed under BSD 3-Clause License. See LICENSE for details.
using System.Runtime.InteropServices;
namespace Oxide.Graphics.Drivers.Vertices
{
[StructLayout(LayoutKind.Sequential)]
public struct Vertex_2f_4ub_2f_2f_28f
{
[MarshalAs(UnmanagedType.LPArray, SizeConst = 2)]
public float[] Pos;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public byte[] Color;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 2)]
public float[] Tex;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 2)]
public float[] Obj;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public float[] Data0;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public float[] Data1;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public float[] Data2;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public float[] Data3;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public float[] Data4;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public float[] Data5;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 4)]
public float[] Data6;
}
}
| 27.911111 | 64 | 0.647293 | [
"BSD-3-Clause"
] | vignetteapp/Mikomi | src/Oxide/Graphics/Drivers/Vertices/Vertex_2f_4ub_2f_2f_28f.cs | 1,256 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
// CTRL + R + R
public class NavEnemy : Enemy
{
#region Variables
//waypoint variables
[Header("Pathfinding")]
public EditofPathScript PathToFollow;
public Transform[] pathToFollowList;
public NavMeshAgent agent;
public int CurrentWayPointID = 0;
public float speed;
public float rotationSpeed = 5.0f;
public string pathName;
//Enemy attack and damage variables
[Header("Attack & Damage")]
public GateHealth currentGate;
public CastleHealth currentCastle;
private EditofPathScript path;
private Vector3 last_position;
private Vector3 current_position;
private float reachDistance = 1.0f;
private float attackTimer = 0f;
#endregion
// Note (Manny): You don't need a region for every function, i.e, 'Start' doesn't need a '#region Start'
#region Unity Events
void OnDrawGizmosSelected()
{
// Draw the attack sphere around Tower
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
// Use this for initialization
void Start()
{
CurrentWayPointID = 0;
pathToFollowList = this.GetComponentInParent<WaveSpawner>().waypoints;
CurrentWayPointID = Random.Range(0, pathToFollowList.Length);
path = pathToFollowList[CurrentWayPointID].GetComponent<EditofPathScript>();
//additional randomised waypoints that I couldn't get working
//PathToFollow = GameObject.Find(pathName).GetComponent<EditofPathScript>();
last_position = transform.position;
//NavMesh agent tutorial setting up the agent with NavMeshAgent
agent = GetComponent<NavMeshAgent>(); // Note (Manny): "NPC.GetComponent" will only get it from the prefab! Not the Instance!
}
// Update is called once per frame
void Update()
{
// Note (Manny): Cache these variables or else your project will get much much slower!
// Also, it's easier to read!
List<Transform> currentPath = path.path_objs;
Transform waypoint = currentPath[CurrentWayPointID];
// Find waypoint ID
float distance = Vector3.Distance(waypoint.position, transform.position);
// Move to waypoint at speed
transform.position = Vector3.MoveTowards(transform.position, waypoint.position, Time.deltaTime * speed);
//return path following
// Rotate agent to face the waypoint
var rotation = Quaternion.LookRotation(waypoint.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationSpeed);
//tutorial example given of how to attach waypoints to the navmesh agent
agent.SetDestination(waypoint.position);
// send agent to next waypoint
if (distance <= reachDistance)
{
CurrentWayPointID++;
}
// End movement on waypoint and attack gates
if (CurrentWayPointID >= currentPath.Count)
{
CurrentWayPointID = currentPath.Count - 1;
SmashGates();
}
/*if (currentGate = null)
{
DestroyCastle();
}*/
}
#endregion
#region Internal
void DetectGates()
{
// Reset current enemy
currentGate = null;
// Perform OverlapSphere and get the hits
Collider[] hits = Physics.OverlapSphere(transform.position, attackRange);
// Loop through everything we hit
foreach (var hit in hits)
{
// If the thing we hit is an enemy
GateHealth gate = hit.GetComponent<GateHealth>();
if (gate)
{
// Set current enemy to that one
currentGate = gate;
}
}
}
#endregion
#region External
// Aims at a given enemy every frame
public override void Aim(GateHealth g)
{
print("MoveOnPath is aiming at '" + g.name + "'");
}
// Attacks at a given enemy only when 'attacking'
public override void Attack(GateHealth g)
{
print("MoveOnPath is attacking '" + g.name + "'");
g.TakeDamage(damage);
// Note (Manny): The way you're using Inheritance & Polymorphism here is wrong. Come and see me for more details.
}
/*public virtual void AimC(CastleHealth c)
{
print("I am aiming at '" + c.name + "'");
}
public virtual void AttackC(CastleHealth c)
{
print("I am attacking '" + c.name + "'");
c.TakeDamage(damage);
}*/
// Protected - Accessible to Cannon / Other Tower classes
// Virtual - Able to change what this function does in derived classes
public void SmashGates()
{
// Detect enemies before performing attack logic
DetectGates();
// Count up the timer
attackTimer += Time.deltaTime; // Note (Manny): This script needs to run every frame or else this doesn't make sense.
// if there's an enemy
if (currentGate)
{
// Aim at the enemy
Aim(currentGate);
// Is attack timer ready?
if (attackTimer >= attackRate)
{
// Attack the enemy!
Attack(currentGate);
// Reset timer
attackTimer = 0f;
}
}
}
/*public void DetectCastle()
{
// Reset current enemy
currentCastle = null;
// Perform OverlapSphere and get the hits
Collider[] hits = Physics.OverlapSphere(transform.position, attackRange);
// Loop through everything we hit
foreach (var hit in hits)
{
// If the thing we hit is an enemy
CastleHealth castle = hit.GetComponent<CastleHealth>();
if (castle)
{
// Set current enemy to that one
currentCastle = castle;
}
}
}
public void DestroyCastle()
{
DetectCastle();
attackTimer += Time.deltaTime;
AimC(currentCastle);
// Is attack timer ready?
if (attackTimer >= attackRate)
{
// Attack the enemy!
Attack(currentGate);
// Reset timer
attackTimer = 0f;
}*/
#endregion
}
| 32.424242 | 133 | 0.604984 | [
"MIT"
] | MyopicMuppet/NSICert4-TowerDefenseProject | Assets/Scripts/Enemy/NavEnemy.cs | 6,422 | C# |
/*
MIT License
Copyright (c) 2019
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.Collections.ObjectModel;
using System.IO;
using TextualRealityGameBookCreator.Interfaces;
using TextualRealityGameBookCreator.SectionPrimitives;
namespace TextualRealityGameBookCreator.Parser
{
public partial class ParseFile : IParseFile
{
private List<string> _rawFile;
private IBook _book;
private List<string> _errors;
private int _lineCounter = 0;
private ParserState _parserState = ParserState.OutsideDefine;
private IBookSection _currentParsedSection;
private IBookParagraph _currentParsedParagraph;
private readonly Stack<string> _fileStack;
public ParseFile()
{
_book = new Book();
_rawFile = new List<string>();
_errors = new List<string>();
_lineCounter = 0;
_parserState = ParserState.OutsideDefine;
_fileStack = new Stack<string>();
_book.Compiled = false;
_book.Linked = false;
}
public ReadOnlyCollection<string> RawFile
{
get
{
return new ReadOnlyCollection<string>(_rawFile);
}
}
public ReadOnlyCollection<string> ErrorList
{
get
{
return new ReadOnlyCollection<string>(_errors);
}
}
public IBook Parse(List<string> rawFile)
{
try
{
ProcessFile(rawFile);
while (_fileStack.Count > 0)
{
string fileName = _fileStack.Pop();
var path = Path.GetFullPath(Environment.CurrentDirectory);
var fullFilename = Path.GetFullPath(path + fileName);
if (File.Exists(fullFilename))
{
_rawFile = new List<string>(File.ReadAllLines(fullFilename));
return Parse(_rawFile);
}
else
{
ErrorAndThrow("File on line <" + _lineCounter + "> (" + fullFilename + ") doesn't exist.");
}
}
}
catch (InvalidOperationException) { }
_book.Compiled = true;
_book.Linked = false;
return _book;
}
private void ProcessFile(List<string> rawFile)
{
foreach (var line in rawFile)
{
_lineCounter++;
var strippedLine = line.Trim();
if (string.IsNullOrEmpty(strippedLine))
{
continue;
}
if (CheckForComments(strippedLine))
{
continue;
}
ProcessDefine(strippedLine);
}
}
public IBook Parse(string fileName)
{
var path = Path.GetFullPath(Environment.CurrentDirectory);
var fullFilename = Path.GetFullPath(path + fileName);
if (File.Exists(fullFilename))
{
_rawFile = new List<string>(File.ReadAllLines(fullFilename));
return Parse(_rawFile);
}
throw new FileNotFoundException("Input file not found.", fileName);
}
private bool CheckForComments(string line)
{
if (line.StartsWith("//", StringComparison.Ordinal))
{
return true;
}
return false;
}
private void ProcessDefine(string strippedLine)
{
switch (_parserState)
{
case ParserState.OutsideDefine:
ProcessOutsideBlocks(strippedLine);
break;
case ParserState.Section:
ProcessInsideSection(strippedLine);
break;
case ParserState.Paragraph:
ProcessInsideParagraph(strippedLine);
break;
case ParserState.Contents:
ProcessInsideContents(strippedLine);
break;
}
}
private void ErrorAndThrow(string errorMessage)
{
_errors.Add(errorMessage);
throw new InvalidOperationException(errorMessage);
}
private string[] SplitInnerLine(char charToSplit, string inputString)
{
string[] split = inputString.Split(charToSplit);
if (split.Length != 2)
{
ErrorAndThrow("Error on line " + _lineCounter + " <" + inputString + ">.");
}
return split;
}
}
}
| 31.185185 | 114 | 0.557346 | [
"MIT"
] | stephenhaunts/TextualRealityGameBookCreator | TextualRealityGameBookCreator/Parser/ParseFile.cs | 5,896 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Search.Models
{
using Common;
public partial class DataSource : IResourceWithETag
{
/// <summary>
/// Creates a new DataSource to connect to an Azure SQL database.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the Azure SQL database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureSql(
string name,
string sqlConnectionString,
string tableOrViewName,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
return CreateSqlDataSource(name, sqlConnectionString, tableOrViewName, description, null, deletionDetectionPolicy);
}
/// <summary>
/// Creates a new DataSource to connect to an Azure SQL database with change detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the Azure SQL database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureSql(
string name,
string sqlConnectionString,
string tableOrViewName,
DataChangeDetectionPolicy changeDetectionPolicy,
string description = null)
{
Throw.IfArgumentNull(changeDetectionPolicy, nameof(changeDetectionPolicy));
return CreateSqlDataSource(name, sqlConnectionString, tableOrViewName, description, changeDetectionPolicy);
}
/// <summary>
/// Creates a new DataSource to connect to an Azure SQL database with change detection and deletion detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the Azure SQL database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource. Note that only high watermark change detection is
/// allowed for Azure SQL when deletion detection is enabled.</param>
/// <param name="deletionDetectionPolicy">The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureSql(
string name,
string sqlConnectionString,
string tableOrViewName,
HighWaterMarkChangeDetectionPolicy changeDetectionPolicy,
DataDeletionDetectionPolicy deletionDetectionPolicy,
string description = null)
{
Throw.IfArgumentNull(changeDetectionPolicy, nameof(changeDetectionPolicy));
Throw.IfArgumentNull(deletionDetectionPolicy, nameof(deletionDetectionPolicy));
return CreateSqlDataSource(name, sqlConnectionString, tableOrViewName, description, changeDetectionPolicy, deletionDetectionPolicy);
}
/// <summary>
/// Creates a new DataSource to connect to a VM-hosted SQL Server database.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the SQL Server database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource SqlServerOnAzureVM(
string name,
string sqlConnectionString,
string tableOrViewName,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
return AzureSql(name, sqlConnectionString, tableOrViewName, deletionDetectionPolicy, description);
}
/// <summary>
/// Creates a new DataSource to connect to a VM-hosted SQL Server database with change detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the SQL Server database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource SqlServerOnAzureVM(
string name,
string sqlConnectionString,
string tableOrViewName,
DataChangeDetectionPolicy changeDetectionPolicy,
string description = null)
{
return AzureSql(name, sqlConnectionString, tableOrViewName, changeDetectionPolicy, description);
}
/// <summary>
/// Creates a new DataSource to connect to a VM-hosted SQL Server database with change detection and deletion detection enabled.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="sqlConnectionString">The connection string for the SQL Server database.</param>
/// <param name="tableOrViewName">The name of the table or view from which to read rows.</param>
/// <param name="changeDetectionPolicy">The change detection policy for the datasource. Note that only high watermark change detection is
/// allowed for SQL Server when deletion detection is enabled.</param>
/// <param name="deletionDetectionPolicy">The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource SqlServerOnAzureVM(
string name,
string sqlConnectionString,
string tableOrViewName,
HighWaterMarkChangeDetectionPolicy changeDetectionPolicy,
DataDeletionDetectionPolicy deletionDetectionPolicy,
string description = null)
{
return AzureSql(name, sqlConnectionString, tableOrViewName, changeDetectionPolicy, deletionDetectionPolicy, description);
}
/// <summary>
/// Creates a new DataSource to connect to a DocumentDb database.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="documentDbConnectionString">The connection string for the DocumentDb database. It must follow this format:
/// "AccountName|AccountEndpoint=[your account name or endpoint];AccountKey=[your account key];Database=[your database name]"</param>
/// <param name="collectionName">The name of the collection from which to read documents.</param>
/// <param name="query">Optional. A query that is applied to the collection when reading documents.</param>
/// <param name="useChangeDetection">Optional. Indicates whether to use change detection when indexing. Default is true.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource DocumentDb(
string name,
string documentDbConnectionString,
string collectionName,
string query = null,
bool useChangeDetection = true,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(collectionName, nameof(collectionName));
Throw.IfArgumentNullOrEmpty(documentDbConnectionString, nameof(documentDbConnectionString));
return new DataSource()
{
Type = DataSourceType.DocumentDb,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = collectionName,
Query = query
},
Credentials = new DataSourceCredentials(documentDbConnectionString),
DataChangeDetectionPolicy = useChangeDetection ? new HighWaterMarkChangeDetectionPolicy("_ts") : null,
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
/// <summary>
/// Creates a new DataSource to connect to an Azure Blob container.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="storageConnectionString">The connection string for the Azure Storage account. It must follow this format:
/// "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key];" Note that HTTPS is required.</param>
/// <param name="containerName">The name of the container from which to read blobs.</param>
/// <param name="pathPrefix">Optional. If specified, the datasource will include only blobs with names starting with this prefix. This is
/// useful when blobs are organized into "virtual folders", for example.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureBlobStorage(
string name,
string storageConnectionString,
string containerName,
string pathPrefix = null,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(containerName, nameof(containerName));
Throw.IfArgumentNullOrEmpty(storageConnectionString, nameof(storageConnectionString));
return new DataSource()
{
Type = DataSourceType.AzureBlob,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = containerName,
Query = pathPrefix
},
Credentials = new DataSourceCredentials(storageConnectionString),
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
/// <summary>
/// Creates a new DataSource to connect to an Azure Table.
/// </summary>
/// <param name="name">The name of the datasource.</param>
/// <param name="storageConnectionString">The connection string for the Azure Storage account. It must follow this format:
/// "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key];" Note that HTTPS is required.</param>
/// <param name="tableName">The name of the table from which to read rows.</param>
/// <param name="query">Optional. A query that is applied to the table when reading rows.</param>
/// <param name="deletionDetectionPolicy">Optional. The data deletion detection policy for the datasource.</param>
/// <param name="description">Optional. Description of the datasource.</param>
/// <returns>A new DataSource instance.</returns>
public static DataSource AzureTableStorage(
string name,
string storageConnectionString,
string tableName,
string query = null,
DataDeletionDetectionPolicy deletionDetectionPolicy = null,
string description = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(tableName, nameof(tableName));
Throw.IfArgumentNullOrEmpty(storageConnectionString, nameof(storageConnectionString));
return new DataSource()
{
Type = DataSourceType.AzureTable,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = tableName,
Query = query
},
Credentials = new DataSourceCredentials(storageConnectionString),
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
private static DataSource CreateSqlDataSource(
string name,
string sqlConnectionString,
string tableOrViewName,
string description,
DataChangeDetectionPolicy changeDetectionPolicy = null,
DataDeletionDetectionPolicy deletionDetectionPolicy = null)
{
Throw.IfArgumentNullOrEmpty(name, nameof(name));
Throw.IfArgumentNullOrEmpty(tableOrViewName, nameof(tableOrViewName));
Throw.IfArgumentNullOrEmpty(sqlConnectionString, nameof(sqlConnectionString));
return new DataSource()
{
Type = DataSourceType.AzureSql,
Name = name,
Description = description,
Container = new DataContainer()
{
Name = tableOrViewName
},
Credentials = new DataSourceCredentials(sqlConnectionString),
DataChangeDetectionPolicy = changeDetectionPolicy,
DataDeletionDetectionPolicy = deletionDetectionPolicy
};
}
}
}
| 54.099644 | 147 | 0.647217 | [
"MIT"
] | 216Giorgiy/azure-sdk-for-net | src/SDKs/Search/DataPlane/Microsoft.Azure.Search.Service/Customizations/DataSources/Models/DataSource.Customization.cs | 15,202 | 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 Moq;
using VSLangProj;
namespace VSLangProj80
{
internal static class Reference3Factory
{
public static Reference3 CreateComReference()
{
var mock = new Mock<Reference3>();
mock.SetupGet(r => r.Type)
.Returns(prjReferenceType.prjReferenceTypeActiveX);
return mock.Object;
}
public static Reference3 CreateAssemblyReference(
string name,
string? version = null,
string? path = null,
prjReferenceType type = prjReferenceType.prjReferenceTypeAssembly,
__PROJECTREFERENCETYPE refType = __PROJECTREFERENCETYPE.PROJREFTYPE_ASSEMBLY)
{
var mock = new Mock<Reference3>();
mock.SetupGet(r => r.Name)
.Returns(name);
mock.SetupGet<string?>(r => r.Version)
.Returns(version);
mock.SetupGet<string?>(r => r.Path)
.Returns(path);
mock.SetupGet(r => r.Resolved)
.Returns(path != null);
mock.SetupGet(r => r.Type)
.Returns(type);
mock.SetupGet(r => r.RefType)
.Returns((uint)refType);
return mock.Object;
}
}
}
| 30.285714 | 162 | 0.549191 | [
"Apache-2.0"
] | MSLukeWest/project-system | tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/Mocks/Reference3Factory.cs | 1,438 | C# |
/**************************************************************************************
Toolkit for WPF
Copyright (C) 2007-2017 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
*************************************************************************************/
using System.Windows.Media;
using System.Windows.Controls;
using System;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Diagnostics;
namespace Xceed.Wpf.Toolkit.LiveExplorer.Samples.Chart.Views
{
/// <summary>
/// Interaction logic for ChartStylingPieSeriesView.xaml
/// </summary>
public partial class ChartStylingPieSeriesView : DemoView
{
public ChartStylingPieSeriesView()
{
InitializeComponent();
}
}
}
| 29.405405 | 88 | 0.624081 | [
"MIT"
] | 0xflotus/Materia | wpftoolkit-master/wpftoolkit-master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit.LiveExplorer/Samples/Chart/Views/ChartStylingPieSeriesView.xaml.cs | 1,090 | 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 firehose-2015-08-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KinesisFirehose.Model
{
/// <summary>
/// Describes an update for a destination in Amazon S3.
/// </summary>
public partial class S3DestinationUpdate
{
private string _bucketARN;
private BufferingHints _bufferingHints;
private CloudWatchLoggingOptions _cloudWatchLoggingOptions;
private CompressionFormat _compressionFormat;
private EncryptionConfiguration _encryptionConfiguration;
private string _prefix;
private string _roleARN;
/// <summary>
/// Gets and sets the property BucketARN.
/// <para>
/// The ARN of the S3 bucket.
/// </para>
/// </summary>
public string BucketARN
{
get { return this._bucketARN; }
set { this._bucketARN = value; }
}
// Check to see if BucketARN property is set
internal bool IsSetBucketARN()
{
return this._bucketARN != null;
}
/// <summary>
/// Gets and sets the property BufferingHints.
/// <para>
/// The buffering option. If no value is specified, <code>BufferingHints</code> object
/// default values are used.
/// </para>
/// </summary>
public BufferingHints BufferingHints
{
get { return this._bufferingHints; }
set { this._bufferingHints = value; }
}
// Check to see if BufferingHints property is set
internal bool IsSetBufferingHints()
{
return this._bufferingHints != null;
}
/// <summary>
/// Gets and sets the property CloudWatchLoggingOptions.
/// <para>
/// The CloudWatch logging options for your delivery stream.
/// </para>
/// </summary>
public CloudWatchLoggingOptions CloudWatchLoggingOptions
{
get { return this._cloudWatchLoggingOptions; }
set { this._cloudWatchLoggingOptions = value; }
}
// Check to see if CloudWatchLoggingOptions property is set
internal bool IsSetCloudWatchLoggingOptions()
{
return this._cloudWatchLoggingOptions != null;
}
/// <summary>
/// Gets and sets the property CompressionFormat.
/// <para>
/// The compression format. If no value is specified, the default is <code>UNCOMPRESSED</code>.
/// </para>
///
/// <para>
/// The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified
/// for Amazon Redshift destinations because they are not supported by the Amazon Redshift
/// <code>COPY</code> operation that reads from the S3 bucket.
/// </para>
/// </summary>
public CompressionFormat CompressionFormat
{
get { return this._compressionFormat; }
set { this._compressionFormat = value; }
}
// Check to see if CompressionFormat property is set
internal bool IsSetCompressionFormat()
{
return this._compressionFormat != null;
}
/// <summary>
/// Gets and sets the property EncryptionConfiguration.
/// <para>
/// The encryption configuration. If no value is specified, the default is no encryption.
/// </para>
/// </summary>
public EncryptionConfiguration EncryptionConfiguration
{
get { return this._encryptionConfiguration; }
set { this._encryptionConfiguration = value; }
}
// Check to see if EncryptionConfiguration property is set
internal bool IsSetEncryptionConfiguration()
{
return this._encryptionConfiguration != null;
}
/// <summary>
/// Gets and sets the property Prefix.
/// <para>
/// The "YYYY/MM/DD/HH" time format prefix is automatically used for delivered Amazon
/// S3 files. You can specify an extra prefix to be added in front of the time format
/// prefix. If the prefix ends with a slash, it appears as a folder in the S3 bucket.
/// For more information, see <a href="http://docs.aws.amazon.com/firehose/latest/dev/basic-deliver.html#s3-object-name">Amazon
/// S3 Object Name Format</a> in the <i>Amazon Kinesis Data Firehose Developer Guide</i>.
/// </para>
/// </summary>
public string Prefix
{
get { return this._prefix; }
set { this._prefix = value; }
}
// Check to see if Prefix property is set
internal bool IsSetPrefix()
{
return this._prefix != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// The Amazon Resource Name (ARN) of the AWS credentials.
/// </para>
/// </summary>
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
}
} | 33.707182 | 135 | 0.598099 | [
"Apache-2.0"
] | awesomeunleashed/aws-sdk-net | sdk/src/Services/KinesisFirehose/Generated/Model/S3DestinationUpdate.cs | 6,101 | C# |
using AtheletesSingleResponsibility.Athletes;
using System;
using System.Collections.Generic;
using System.Text;
namespace AtheletesSingleResponsibility.Data
{
public static class Database
{
public static List<Athelete> Atheletes = new List<Athelete>
{
new HighJumper("High", "Jumper", Gender.Male, "ZA"),
new HighJumper("Girl", "Jumper", Gender.Female, "US"),
new LongJumper("Super", "Long", Gender.Male, "ZA"),
new LongJumper("Mike", "Triple", Gender.Male, "US"),
new Runner("Usain", "Bolt", Gender.Male, "JM"),
new Runner("Caster", "Semenya", Gender.Female, "ZA"),
new Swimmer("Fast", "Swimm", Gender.Female, "NZ"),
new Swimmer("Michael", "Phelps", Gender.Male, "US"),
};
}
}
| 35.347826 | 67 | 0.599016 | [
"Apache-2.0"
] | newteq/DevelopmentFundamentals | Practical/AthletesSingleResponsibility/Data/Database.cs | 815 | C# |
using Mono.Options;
using System;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Text.Json;
namespace TouchPortalSDK.Extensions.Tool
{
class Program
{
static void Main(string[] args)
{
var entry = false;
var package = false; //TODO: find a configuration that works. And why not toggle with a output file path?
var help = false;
var outdir = ".";
var assemblyName = string.Empty;
//"h|help", "show this message and exit"
var options = new OptionSet
{
{ "o|outdir=", "The output directory of the build, ex. $(OutDir) if using variable.", o => outdir = o },
{ "a|assemblyName=", "Assembly name of the plugin, ex. $(AssemblyName) if using variable.", a => assemblyName = a },
{ "e|entry", "Creates the entry.tp file.", (e) => entry = e != null },
{ "p|package", "Creates the .tpp package file.", (p) => package = p != null },
{ "h|help", "Show this message and exit", (h) => help = h != null }
//TODO: LogLevel, error, warn, verbose...
};
options.Parse(args);
if (string.IsNullOrWhiteSpace(outdir) || string.IsNullOrWhiteSpace(assemblyName) || help)
{
ShowHelp(options);
return;
}
if (entry)
{
CreateEntryFile(outdir, assemblyName);
}
if (package)
{
//TODO: Publish path... On publish trigger?
//PackageTppFile(assemblyName, "", "");
}
}
private static void CreateEntryFile(string outdir, string assemblyName)
{
var assemblyPath = GetAssemblyPath(outdir, assemblyName);
var assemblyFile = Assembly.LoadFrom(assemblyPath);
var versionString = assemblyFile
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion;
Console.WriteLine("Test: -------- ");
Console.WriteLine($"Generating from assembly: '{assemblyFile.Location}', version: '{versionString}'");
var context = Reflection.PluginTreeBuilder.Build(assemblyFile);
var entryFileObject = Reflection.EntryFileBuilder.BuildEntryFile(context);
var entryFileContents = JsonSerializer.Serialize(entryFileObject, new JsonSerializerOptions
{
WriteIndented = true
});
var entryFilePath = Path.Combine(outdir, "entry.tp");
File.WriteAllText(entryFilePath, entryFileContents);
}
private static void PackageTppFile(string pluginId, string publishPath, string outputPath)
{
//Find entry.tp before archiving...
var files = Directory.GetFiles(publishPath, "*");
if (File.Exists(outputPath))
File.Delete(outputPath);
using (var archive = ZipFile.Open(outputPath, ZipArchiveMode.Create))
{
//The "secret sauce" to get this working in Java:
var directory = archive.CreateEntry($"{pluginId}/");
foreach (var file in files)
{
var pluginEntryName = Path.Combine(pluginId, Path.GetFileName(file));
archive.CreateEntryFromFile(file, pluginEntryName);
}
}
}
private static void ShowHelp(OptionSet options)
{
Console.WriteLine("Usage: dotnet tool run TouchPortalSDK [OPTIONS]+");
//Missing required parameter xxx.
Console.WriteLine("Generates the entry.tp file from reflection of your Plugin Assembly.");
//Console.WriteLine("If no xxx is specified, a xxx is used.");
Console.WriteLine();
Console.WriteLine("Options:");
options.WriteOptionDescriptions(Console.Out);
}
private static string GetAssemblyPath(string outDir, string assemblyName)
{
string PathOrNull(string fileName)
{
var filePath = Path.Combine(outDir, fileName);
return File.Exists(filePath)
? filePath
: null;
}
var extension = Path.GetExtension(assemblyName).ToLower();
return extension is ".dll" or ".exe"
? PathOrNull(assemblyName)
: PathOrNull($"{assemblyName}.dll") ?? PathOrNull($"{assemblyName}.exe");
}
}
}
| 37.56 | 132 | 0.552716 | [
"MIT"
] | oddbear/TouchPortalSDK.Extensions | TouchPortalSDK.Extensions.Tool/Program.cs | 4,697 | C# |
// Developed by Softeq Development Corporation
// http://www.softeq.com
using System.Threading.Tasks;
namespace Softeq.XToolkit.Chat.Models.Interfaces
{
public interface IChatAuthService
{
string UserId { get; }
Task<string> GetAccessToken();
Task RefreshToken();
}
}
| 18.294118 | 48 | 0.672026 | [
"MIT"
] | Softeq/XToolkit.Chat | Softeq.XToolkit.Chat.Models/Interfaces/IChatAuthService.cs | 313 | C# |
using System.Collections.Generic;
using System.Linq;
using DemoWebApi.Entity;
namespace DemoWebApi.Models
{
public class EmployeeQuery
{
/// <summary>
/// Return All Employee
/// </summary>
/// <returns>Employee</returns>
public IEnumerable<Employee> GetEmployee()
{
var listEmployee = new List<Employee>
{
new Employee {Id = 1, FirstName = "Joe", Age = 25},
new Employee {Id = 2, FirstName = "Jack", Age = 30},
new Employee {Id = 3, FirstName = "Allen", Age = 35}
};
return listEmployee.ToList();
}
/// <summary>
/// Return Employee By Id
/// </summary>
/// <param name="id">Employee Id</param>
/// <returns>Employee</returns>
public IEnumerable<Employee> GetRemoveEmployeeById(int id)
{
var list = GetEmployee().Select(c => c).ToList();
list.Remove(new Employee{Id = id});
return list;
}
/// <summary>
/// Remove Employee By Id
/// </summary>
/// <param name="id">Employee Id</param>
public void RemoveEmployeeById(int id)
{
var list = GetEmployee().Select(c => c).ToList();
list.Remove(new Employee { Id = id });
}
}
} | 28.625 | 68 | 0.508734 | [
"MIT"
] | Shulyakovskiy/HttpClientSE | DemoWebApi/Models/EmployeeQuery.cs | 1,376 | C# |
using System;
using System.Text.Json.Serialization;
using BinancePayDotnetSdk.Common.Converters;
using BinancePayDotnetSdk.Common.Enums;
namespace BinancePayDotnetSdk.Common.Models
{
/// <summary>
/// https://developers.binance.com/docs/binance-pay/api-order-create#child-attribute
/// </summary>
public class CreateOrderResponseDataModel
{
/// <summary>
/// Unique id generated by binance.
/// Letter or digit, no other symbol allowed.
/// </summary>
[JsonPropertyName("prepayId")]
public string PrepayId { get; init; }
/// <summary>
/// Operate entrance.
/// </summary>
[JsonPropertyName("tradeType")]
[JsonConverter(typeof(JsonStringEnumConverter))]
public TradeType TradeType { get; init; }
/// <summary>
/// Expire time.
/// </summary>
[JsonPropertyName("expireTime")]
[JsonConverter(typeof(JsonMillisecondsDateTimeOffsetConverter))]
public DateTimeOffset ExpireTime { get; init; }
/// <summary>
/// QrCode img link.
/// </summary>
[JsonPropertyName("qrcodeLink")]
public string QrCodeLink { get; init; }
/// <summary>
/// Qr content info.
/// </summary>
[JsonPropertyName("qrContent")]
public string QrContent { get; init; }
}
} | 30.913043 | 88 | 0.587904 | [
"MIT"
] | Tusquito/binance-pay-dotnet-sdk | srcs/BinancePayDotnetSdk.Common/Models/CreateOrderResponseDataModel.cs | 1,424 | C# |
using HL7Data.Contracts.Fields;
using HL7Data.Models.Base;
using HL7Data.Models.Types;
namespace HL7Data.Models.Fields
{
public class MoneyAndCode : BaseField, IMoneyAndCode
{
public override ElementDataType DataType => ElementDataType.MOC;
}
#if TODO
[CombineOrder(Order = 1, Name = ".1")]
#endif
} | 21.666667 | 72 | 0.72 | [
"MIT"
] | amenkes/HL7Parser | Models/Fields/MoneyAndCode.cs | 325 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Negate_Vector128_Int32()
{
var test = new SimpleUnaryOpTest__Negate_Vector128_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__Negate_Vector128_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__Negate_Vector128_Int32 testClass)
{
var result = AdvSimd.Negate(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__Negate_Vector128_Int32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
{
var result = AdvSimd.Negate(
AdvSimd.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar1;
private Vector128<Int32> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__Negate_Vector128_Int32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleUnaryOpTest__Negate_Vector128_Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Negate(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Negate(
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Negate), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Negate), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Negate(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Negate(
AdvSimd.LoadVector128((Int32*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Negate(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Negate(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__Negate_Vector128_Int32();
var result = AdvSimd.Negate(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__Negate_Vector128_Int32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
{
var result = AdvSimd.Negate(
AdvSimd.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Negate(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
{
var result = AdvSimd.Negate(
AdvSimd.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Negate(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Negate(
AdvSimd.LoadVector128((Int32*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Negate(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Negate)}<Int32>(Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 37.581633 | 187 | 0.572957 | [
"MIT"
] | Davilink/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/Negate.Vector128.Int32.cs | 18,415 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace HeroesData.FileWriter.Tests.EmoticonData
{
[TestClass]
public class EmoticonDataOutputJsonTests : EmoticonDataOutputBase
{
public EmoticonDataOutputJsonTests()
{
FileOutputType = FileOutputType.Json;
}
[TestMethod]
public override void WriterColoredTextTest()
{
base.WriterColoredTextTest();
}
[TestMethod]
public override void WriterColoredTextWithScalingTest()
{
base.WriterColoredTextWithScalingTest();
}
[TestMethod]
public override void WriterGameStringLocalizedTests()
{
base.WriterGameStringLocalizedTests();
}
[TestMethod]
public override void WriterHasBuildNumberTest()
{
base.WriterHasBuildNumberTest();
}
[TestMethod]
public override void WriterMinifiedTest()
{
base.WriterMinifiedTest();
}
[TestMethod]
public override void WriterNoBuildNumberTest()
{
base.WriterNoBuildNumberTest();
}
[TestMethod]
public override void WriterPlainTextTest()
{
base.WriterPlainTextTest();
}
[TestMethod]
public override void WriterPlainTextWithNewLinesTest()
{
base.WriterPlainTextWithNewLinesTest();
}
[TestMethod]
public override void WriterPlainTextWithScalingTest()
{
base.WriterPlainTextWithScalingTest();
}
[TestMethod]
public override void WriterPlainTextWithScalingWithNewlinesTest()
{
base.WriterPlainTextWithScalingWithNewlinesTest();
}
[TestMethod]
public override void WriterRawDescriptionTest()
{
base.WriterRawDescriptionTest();
}
}
}
| 24.4375 | 73 | 0.596419 | [
"MIT"
] | HeroesToolChest/HeroesDataParser | Tests/HeroesData.FileWriter.Tests/EmoticonData/EmoticonDataOutputJsonTests.cs | 1,957 | C# |
using System;
using System.Text.RegularExpressions;
namespace ddd.Repository
{
class Name
{
private readonly string value;
public Name(string value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (!ValidateName(value)) throw new ArgumentException(nameof(value));
this.value = value;
}
private bool ValidateName(string str)
{
return Regex.IsMatch(str, @"^[a-zA-Z0-9]+$");
}
public override string ToString()
{
return value;
}
}
}
| 21.821429 | 81 | 0.556465 | [
"MIT"
] | kaleidot725/ddd | ddd_introduction/ddd/ddd/Repository/Name.cs | 613 | 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("Serialization.Shared")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Serialization.Shared")]
[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("7575b2d1-2fa7-4ca2-b1bf-710fb30ad1e8")]
// 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.189189 | 84 | 0.746638 | [
"MIT"
] | tonysneed/Experimental | vCurrent/Serialization/Serialization.Shared/Properties/AssemblyInfo.cs | 1,416 | C# |
//! \file ImageCHD.cs
//! \date 2017 Dec 09
//! \brief Forest image format.
//
// Copyright (C) 2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
namespace GameRes.Formats.Forest
{
internal class ChdMetaData : ImageMetaData
{
public uint FirstOffset;
}
/// <summary>
/// ShiinaRio images predecessor.
/// </summary>
[Export(typeof(ImageFormat))]
public class ChdFormat : ImageFormat
{
public override string Tag { get { return "CHD"; } }
public override string Description { get { return "Forest image format"; } }
public override uint Signature { get { return 0x444843; } } // 'CHD'
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
file.Position = 4;
int count = file.ReadInt32();
if (count < 0 || count > 0xFFFFF)
return null;
file.ReadInt32();
uint first_offset = 0;
for (int i = 0; i < count && 0 == first_offset; ++i)
first_offset = file.ReadUInt32();
if (0 == first_offset)
return null;
file.Position = first_offset;
var info = new ChdMetaData();
info.Width = file.ReadUInt32();
info.Height = file.ReadUInt32();
info.OffsetX = file.ReadInt32();
info.OffsetY = file.ReadInt32();
info.FirstOffset = first_offset+0x10;
info.BPP = 32;
return info;
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new ChdReader (file, (ChdMetaData)info);
var pixels = reader.Unpack();
return ImageData.Create (info, PixelFormats.Gray8, null, pixels);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("ChdFormat.Write not implemented");
}
}
internal class ChdReader
{
IBinaryStream m_input;
int m_width;
int m_height;
uint m_origin;
public ChdReader (IBinaryStream input, ChdMetaData info)
{
m_input = input;
m_width = (int)info.Width;
m_height = (int)info.Height;
m_origin = info.FirstOffset;
}
public byte[] Unpack ()
{
m_input.Position = m_origin;
var rows = new uint[m_height];
for (int i = 0; i < m_height; ++i)
rows[i] = m_input.ReadUInt32();
var output = new byte[m_height*m_width];
for (int y = 0; y < m_height; ++y)
{
m_input.Position = rows[y];
int dst = y * m_width;
for (int w = m_width; w > 0; )
{
int count = m_input.ReadUInt8();
if (0xFF == count)
count = m_input.ReadUInt16();
int x = w - count;
if (0 == x)
break;
count = m_input.ReadUInt8();
if (0 == count)
count = m_input.ReadUInt16();
m_input.Read (output, dst, count);
for (int i = 0; i < count; ++i)
output[dst+i] += 0x57;
dst += count;
w = x - count;
}
}
return output;
}
}
}
| 35.946565 | 89 | 0.551922 | [
"MIT"
] | 1127815807/GARbro | ArcFormats/ShiinaRio/ImageCHD.cs | 4,709 | C# |
using System;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Sentry.Infrastructure;
using Sentry.Protocol;
using Sentry.Reflection;
namespace Sentry.Extensions.Logging
{
/// <summary>
/// Sentry Logger Provider.
/// </summary>
[ProviderAlias("Sentry")]
public class SentryLoggerProvider : ILoggerProvider
{
private readonly ISystemClock _clock;
private readonly SentryLoggingOptions _options;
private readonly IDisposable? _scope;
private readonly IDisposable? _disposableHub;
internal IHub Hub { get; }
internal static readonly SdkVersion NameAndVersion
= typeof(SentryLogger).Assembly.GetNameAndVersion();
private static readonly string ProtocolPackageName = "nuget:" + NameAndVersion.Name;
/// <summary>
/// Creates a new instance of <see cref="SentryLoggerProvider"/>.
/// </summary>
/// <param name="options">The Options.</param>
/// <param name="hub">The Hub.</param>
public SentryLoggerProvider(IOptions<SentryLoggingOptions> options, IHub hub)
: this(hub,
SystemClock.Clock,
options.Value)
{ }
internal SentryLoggerProvider(
IHub hub,
ISystemClock clock,
SentryLoggingOptions options)
{
Debug.Assert(options != null);
Debug.Assert(clock != null);
Debug.Assert(hub != null);
_disposableHub = hub as IDisposable;
Hub = hub;
_clock = clock;
_options = options;
if (hub.IsEnabled)
{
_scope = hub.PushScope();
hub.ConfigureScope(s =>
{
if (s.Sdk is { } sdk)
{
sdk.Name = Constants.SdkName;
sdk.Version = NameAndVersion.Version;
if (NameAndVersion.Version is {} version)
{
sdk.AddPackage(ProtocolPackageName, version);
}
}
});
// Add scope configuration to hub from options
foreach (var callback in options.ConfigureScopeCallbacks)
{
hub.ConfigureScope(callback);
}
}
}
/// <summary>
/// Creates a logger for the category.
/// </summary>
/// <param name="categoryName">Category name.</param>
/// <returns>A logger.</returns>
public ILogger CreateLogger(string categoryName) => new SentryLogger(categoryName, _options, _clock, Hub);
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
_scope?.Dispose();
_disposableHub?.Dispose();
}
}
}
| 30.659794 | 114 | 0.535642 | [
"MIT"
] | bruno-garcia/sentry-dotnet | src/Sentry.Extensions.Logging/SentryLoggerProvider.cs | 2,974 | C# |
#if LESSTHAN_NET47 || LESSTHAN_NETCOREAPP20 || LESSTHAN_NETSTANDARD20
namespace System.Runtime.CompilerServices
{
/// <summary>Indicates whether a method is an asynchronous iterator.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute
{
/// <summary>Initializes a new instance of the <see cref="AsyncIteratorStateMachineAttribute" /> class.</summary>
/// <param name="stateMachineType">The type object for the underlying state machine type that's used to implement a state machine method.</param>
public AsyncIteratorStateMachineAttribute(Type stateMachineType)
: base(stateMachineType)
{
// Empty
}
}
}
#endif | 41.842105 | 153 | 0.719497 | [
"MIT"
] | Emik03/Theraot | Framework.Core/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.cs | 797 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Model\EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Windows Information Protection App Learning Summary.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class WindowsInformationProtectionAppLearningSummary : Entity
{
/// <summary>
/// Gets or sets application name.
/// Application Name
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "applicationName", Required = Newtonsoft.Json.Required.Default)]
public string ApplicationName { get; set; }
/// <summary>
/// Gets or sets application type.
/// Application Type Possible values are: universal, desktop.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "applicationType", Required = Newtonsoft.Json.Required.Default)]
public ApplicationType? ApplicationType { get; set; }
/// <summary>
/// Gets or sets device count.
/// Device Count
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "deviceCount", Required = Newtonsoft.Json.Required.Default)]
public Int32? DeviceCount { get; set; }
}
}
| 39.833333 | 153 | 0.616632 | [
"MIT"
] | mlafleur/msgraph-sdk-dotnet | src/Microsoft.Graph/Models/Generated/WindowsInformationProtectionAppLearningSummary.cs | 1,912 | C# |
using System;
using System.Drawing;
using System.Linq;
using ScottPlot.Ticks;
using ScottPlot.Drawing;
using ScottPlot.Renderable;
using ScottPlot.Statistics;
using System.Data;
namespace ScottPlot.Plottable
{
public class PopulationPlot : IPlottable
{
public readonly PopulationMultiSeries popMultiSeries;
public int groupCount { get { return popMultiSeries.groupCount; } }
public int seriesCount { get { return popMultiSeries.seriesCount; } }
public string[] labels { get { return popMultiSeries.seriesLabels; } }
public bool IsVisible { get; set; } = true;
public int HorizontalAxisIndex { get; set; } = 0;
public int VerticalAxisIndex { get; set; } = 0;
public enum DisplayItems { BoxOnly, BoxAndScatter, ScatterAndBox, ScatterOnly };
public enum BoxStyle { BarMeanStDev, BarMeanStdErr, BoxMeanStdevStderr, BoxMedianQuartileOutlier, MeanAndStdev, MeanAndStderr };
public bool displayDistributionCurve = true;
public LineStyle distributionCurveLineStyle = LineStyle.Solid;
public Color distributionCurveColor = Color.Black;
public Color scatterOutlineColor = Color.Black;
public DisplayItems displayItems = DisplayItems.BoxAndScatter;
public BoxStyle boxStyle = BoxStyle.BoxMedianQuartileOutlier;
public PopulationPlot(PopulationMultiSeries groupedSeries)
{
popMultiSeries = groupedSeries;
}
public PopulationPlot(Population[] populations, string label = null, Color? color = null)
{
var ps = new PopulationSeries(populations, label, color ?? Color.LightGray);
popMultiSeries = new PopulationMultiSeries(new PopulationSeries[] { ps });
}
public PopulationPlot(PopulationSeries populationSeries)
{
popMultiSeries = new PopulationMultiSeries(new PopulationSeries[] { populationSeries });
}
public PopulationPlot(Population population, string label = null, Color? color = null)
{
var populations = new Population[] { population };
var ps = new PopulationSeries(populations, label, color ?? Color.LightGray);
popMultiSeries = new PopulationMultiSeries(new PopulationSeries[] { ps });
}
public override string ToString()
{
return $"PlottableSeries with {popMultiSeries.groupCount} groups, {popMultiSeries.seriesCount} series, and {PointCount} total points";
}
public int PointCount
{
get
{
int pointCount = 0;
foreach (var group in popMultiSeries.multiSeries)
foreach (var population in group.populations)
pointCount += population.count;
return pointCount;
}
}
public void ValidateData(bool deep = false)
{
if (popMultiSeries is null)
throw new InvalidOperationException("population multi-series cannot be null");
}
public LegendItem[] GetLegendItems() => popMultiSeries.multiSeries
.Select(x => new LegendItem() { label = x.seriesLabel, color = x.color, lineWidth = 10 })
.ToArray();
public AxisLimits GetAxisLimits()
{
double minValue = double.PositiveInfinity;
double maxValue = double.NegativeInfinity;
foreach (var series in popMultiSeries.multiSeries)
{
foreach (var population in series.populations)
{
minValue = Math.Min(minValue, population.min);
minValue = Math.Min(minValue, population.minus3stDev);
maxValue = Math.Max(maxValue, population.max);
maxValue = Math.Max(maxValue, population.plus3stDev);
}
}
double positionMin = 0;
double positionMax = popMultiSeries.groupCount - 1;
// padd slightly
positionMin -= .5;
positionMax += .5;
return new AxisLimits(positionMin, positionMax, minValue, maxValue);
}
public void Render(PlotDimensions dims, Bitmap bmp, bool lowQuality = false)
{
Random rand = new Random(0);
double groupWidth = .8;
var popWidth = groupWidth / seriesCount;
for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++)
{
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++)
{
var series = popMultiSeries.multiSeries[seriesIndex];
var population = series.populations[groupIndex];
var groupLeft = groupIndex - groupWidth / 2;
var popLeft = groupLeft + popWidth * seriesIndex;
Position scatterPos, boxPos;
switch (displayItems)
{
case DisplayItems.BoxAndScatter:
boxPos = Position.Left;
scatterPos = Position.Right;
break;
case DisplayItems.BoxOnly:
boxPos = Position.Center;
scatterPos = Position.Hide;
break;
case DisplayItems.ScatterAndBox:
boxPos = Position.Right;
scatterPos = Position.Left;
break;
case DisplayItems.ScatterOnly:
boxPos = Position.Hide;
scatterPos = Position.Center;
break;
default:
throw new NotImplementedException();
}
Scatter(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, scatterOutlineColor, 128, scatterPos);
if (displayDistributionCurve)
Distribution(dims, bmp, lowQuality, population, rand, popLeft, popWidth, distributionCurveColor, scatterPos, distributionCurveLineStyle);
switch (boxStyle)
{
case BoxStyle.BarMeanStdErr:
Bar(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: true);
break;
case BoxStyle.BarMeanStDev:
Bar(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: false);
break;
case BoxStyle.BoxMeanStdevStderr:
Box(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, BoxFormat.StdevStderrMean);
break;
case BoxStyle.BoxMedianQuartileOutlier:
Box(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, BoxFormat.OutlierQuartileMedian);
break;
case BoxStyle.MeanAndStderr:
MeanAndError(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: true);
break;
case BoxStyle.MeanAndStdev:
MeanAndError(dims, bmp, lowQuality, population, rand, popLeft, popWidth, series.color, boxPos, useStdErr: false);
break;
default:
throw new NotImplementedException();
}
}
}
}
public enum Position { Hide, Center, Left, Right }
public static void Scatter(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand,
double popLeft, double popWidth, Color fillColor, Color edgeColor, byte alpha, Position position)
{
// adjust edges to accomodate special positions
if (position == Position.Hide) return;
if (position == Position.Left || position == Position.Right) popWidth /= 2;
if (position == Position.Right) popLeft += popWidth;
// contract edges slightly to encourage padding between elements
double edgePaddingFrac = 0.2;
popLeft += popWidth * edgePaddingFrac;
popWidth -= (popWidth * edgePaddingFrac) * 2;
float radius = 5;
using (Graphics gfx = GDI.Graphics(bmp, dims, lowQuality))
using (Pen penEdge = GDI.Pen(Color.FromArgb(alpha, edgeColor)))
using (Brush brushFill = GDI.Brush(Color.FromArgb(alpha, fillColor)))
{
foreach (double value in pop.values)
{
double yPx = dims.GetPixelY(value);
double xPx = dims.GetPixelX(popLeft + rand.NextDouble() * popWidth);
gfx.FillEllipse(brushFill, (float)(xPx - radius), (float)(yPx - radius), radius * 2, radius * 2);
gfx.DrawEllipse(penEdge, (float)(xPx - radius), (float)(yPx - radius), radius * 2, radius * 2);
}
}
}
public static void Distribution(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand,
double popLeft, double popWidth, Color color, Position position, LineStyle lineStyle)
{
// adjust edges to accomodate special positions
if (position == Position.Hide) return;
if (position == Position.Left || position == Position.Right) popWidth /= 2;
if (position == Position.Right) popLeft += popWidth;
// contract edges slightly to encourage padding between elements
double edgePaddingFrac = 0.2;
popLeft += popWidth * edgePaddingFrac;
popWidth -= (popWidth * edgePaddingFrac) * 2;
double[] ys = DataGen.Range(pop.minus3stDev, pop.plus3stDev, dims.UnitsPerPxY);
if (ys.Length == 0)
return;
double[] ysFrac = pop.GetDistribution(ys, normalize: false);
PointF[] points = new PointF[ys.Length];
for (int i = 0; i < ys.Length; i++)
{
float x = (float)dims.GetPixelX(popLeft + popWidth * ysFrac[i]);
float y = (float)dims.GetPixelY(ys[i]);
points[i] = new PointF(x, y);
}
using (Graphics gfx = GDI.Graphics(bmp, dims, lowQuality))
using (Pen pen = GDI.Pen(color, 1, lineStyle, true))
{
gfx.DrawLines(pen, points);
}
}
public static void MeanAndError(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand,
double popLeft, double popWidth, Color color, Position position, bool useStdErr = false)
{
// adjust edges to accomodate special positions
if (position == Position.Hide) return;
if (position == Position.Left || position == Position.Right) popWidth /= 2;
if (position == Position.Right) popLeft += popWidth;
// determine the center point and calculate bounds
double centerX = popLeft + popWidth / 2;
double xPx = dims.GetPixelX(centerX);
double yPx = dims.GetPixelY(pop.mean);
double errorMaxPx, errorMinPx;
if (useStdErr)
{
errorMaxPx = dims.GetPixelY(pop.mean + pop.stdErr);
errorMinPx = dims.GetPixelY(pop.mean - pop.stdErr);
}
else
{
errorMaxPx = dims.GetPixelY(pop.mean + pop.stDev);
errorMinPx = dims.GetPixelY(pop.mean - pop.stDev);
}
// make cap width a fraction of available space
double capWidthFrac = .38;
double capWidth = popWidth * capWidthFrac;
double capPx1 = dims.GetPixelX(centerX - capWidth / 2);
double capPx2 = dims.GetPixelX(centerX + capWidth / 2);
float radius = 5;
using (Graphics gfx = GDI.Graphics(bmp, dims, lowQuality))
using (Pen pen = GDI.Pen(color, 2))
using (Brush brush = GDI.Brush(color))
{
gfx.FillEllipse(brush, (float)(xPx - radius), (float)(yPx - radius), radius * 2, radius * 2);
gfx.DrawLine(pen, (float)xPx, (float)errorMinPx, (float)xPx, (float)errorMaxPx);
gfx.DrawLine(pen, (float)capPx1, (float)errorMinPx, (float)capPx2, (float)errorMinPx);
gfx.DrawLine(pen, (float)capPx1, (float)errorMaxPx, (float)capPx2, (float)errorMaxPx);
}
}
public static void Bar(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand,
double popLeft, double popWidth, Color color, Position position, bool useStdErr = false)
{
// adjust edges to accomodate special positions
if (position == Position.Hide) return;
if (position == Position.Left || position == Position.Right) popWidth /= 2;
if (position == Position.Right) popLeft += popWidth;
// determine the center point and calculate bounds
double centerX = popLeft + popWidth / 2;
double xPx = dims.GetPixelX(centerX);
double yPxTop = dims.GetPixelY(pop.mean);
double yPxBase = dims.GetPixelY(0);
double errorMaxPx, errorMinPx;
if (useStdErr)
{
errorMaxPx = dims.GetPixelY(pop.mean + pop.stdErr);
errorMinPx = dims.GetPixelY(pop.mean - pop.stdErr);
}
else
{
errorMaxPx = dims.GetPixelY(pop.mean + pop.stDev);
errorMinPx = dims.GetPixelY(pop.mean - pop.stDev);
}
// make cap width a fraction of available space
double capWidthFrac = .38;
double capWidth = popWidth * capWidthFrac;
double capPx1 = dims.GetPixelX(centerX - capWidth / 2);
double capPx2 = dims.GetPixelX(centerX + capWidth / 2);
// contract edges slightly to encourage padding between elements
double edgePaddingFrac = 0.2;
popLeft += popWidth * edgePaddingFrac;
popWidth -= (popWidth * edgePaddingFrac) * 2;
double leftPx = dims.GetPixelX(popLeft);
double rightPx = dims.GetPixelX(popLeft + popWidth);
RectangleF rect = new RectangleF((float)leftPx, (float)yPxTop, (float)(rightPx - leftPx), (float)(yPxBase - yPxTop));
using (Graphics gfx = GDI.Graphics(bmp, dims, lowQuality))
using (Pen pen = GDI.Pen(Color.Black))
using (Brush brush = GDI.Brush(color))
{
gfx.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height);
gfx.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
gfx.DrawLine(pen, (float)xPx, (float)errorMinPx, (float)xPx, (float)errorMaxPx);
gfx.DrawLine(pen, (float)capPx1, (float)errorMinPx, (float)capPx2, (float)errorMinPx);
gfx.DrawLine(pen, (float)capPx1, (float)errorMaxPx, (float)capPx2, (float)errorMaxPx);
}
}
public enum BoxFormat { StdevStderrMean, OutlierQuartileMedian }
public enum HorizontalAlignment { Left, Center, Right }
public static void Box(PlotDimensions dims, Bitmap bmp, bool lowQuality, Population pop, Random rand,
double popLeft, double popWidth, Color color, Position position, BoxFormat boxFormat,
HorizontalAlignment errorAlignment = HorizontalAlignment.Right)
{
// adjust edges to accomodate special positions
if (position == Position.Hide) return;
if (position == Position.Left || position == Position.Right) popWidth /= 2;
if (position == Position.Right) popLeft += popWidth;
double errorMaxPx, errorMinPx;
double yPxTop, yPxBase;
double yPx;
if (boxFormat == BoxFormat.StdevStderrMean)
{
errorMaxPx = dims.GetPixelY(pop.mean + pop.stDev);
errorMinPx = dims.GetPixelY(pop.mean - pop.stDev);
yPxTop = dims.GetPixelY(pop.mean + pop.stdErr);
yPxBase = dims.GetPixelY(pop.mean - pop.stdErr);
yPx = dims.GetPixelY(pop.mean);
}
else if (boxFormat == BoxFormat.OutlierQuartileMedian)
{
errorMaxPx = dims.GetPixelY(pop.maxNonOutlier);
errorMinPx = dims.GetPixelY(pop.minNonOutlier);
yPxTop = dims.GetPixelY(pop.Q3);
yPxBase = dims.GetPixelY(pop.Q1);
yPx = dims.GetPixelY(pop.median);
}
else
{
throw new NotImplementedException();
}
// make cap width a fraction of available space
double capWidthFrac = .38;
double capWidth = popWidth * capWidthFrac;
// contract edges slightly to encourage padding between elements
double edgePaddingFrac = 0.2;
popLeft += popWidth * edgePaddingFrac;
popWidth -= (popWidth * edgePaddingFrac) * 2;
double leftPx = dims.GetPixelX(popLeft);
double rightPx = dims.GetPixelX(popLeft + popWidth);
RectangleF rect = new RectangleF(
x: (float)leftPx,
y: (float)yPxTop,
width: (float)(rightPx - leftPx),
height: (float)(yPxBase - yPxTop));
// determine location of errorbars and caps
double capPx1, capPx2, errorPxX;
switch (errorAlignment)
{
case HorizontalAlignment.Center:
double centerX = popLeft + popWidth / 2;
errorPxX = dims.GetPixelX(centerX);
capPx1 = dims.GetPixelX(centerX - capWidth / 2);
capPx2 = dims.GetPixelX(centerX + capWidth / 2);
break;
case HorizontalAlignment.Right:
errorPxX = dims.GetPixelX(popLeft + popWidth);
capPx1 = dims.GetPixelX(popLeft + popWidth - capWidth / 2);
capPx2 = dims.GetPixelX(popLeft + popWidth);
break;
case HorizontalAlignment.Left:
errorPxX = dims.GetPixelX(popLeft);
capPx1 = dims.GetPixelX(popLeft);
capPx2 = dims.GetPixelX(popLeft + capWidth / 2);
break;
default:
throw new NotImplementedException();
}
using (Graphics gfx = GDI.Graphics(bmp, dims, lowQuality))
using (Pen pen = GDI.Pen(Color.Black))
using (Brush brush = GDI.Brush(color))
{
// draw the box
gfx.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height);
gfx.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
// draw the line in the center
gfx.DrawLine(pen, rect.X, (float)yPx, rect.X + rect.Width, (float)yPx);
// draw errorbars and caps
gfx.DrawLine(pen, (float)errorPxX, (float)errorMinPx, (float)errorPxX, rect.Y + rect.Height);
gfx.DrawLine(pen, (float)errorPxX, (float)errorMaxPx, (float)errorPxX, rect.Y);
gfx.DrawLine(pen, (float)capPx1, (float)errorMinPx, (float)capPx2, (float)errorMinPx);
gfx.DrawLine(pen, (float)capPx1, (float)errorMaxPx, (float)capPx2, (float)errorMaxPx);
}
}
}
}
| 46.359447 | 161 | 0.560288 | [
"MIT"
] | SommerEngineering/ScottPlot | src/ScottPlot/Plottable/PopulationPlot.cs | 20,122 | C# |
using Nancy.Bootstrapper;
using Nancy.Session;
using Nancy.TinyIoc;
namespace NancyTest
{
using Nancy;
using Nancy.Conventions;
public class Bootstrapper : DefaultNancyBootstrapper
{
// The bootstrapper enables you to reconfigure the composition of the framework,
// by overriding the various methods and properties.
// For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
protected override void ConfigureConventions(NancyConventions nancyConventions)
{
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/Scripts"));
nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/Content"));
}
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
CookieBasedSessions.Enable(pipelines);
}
}
} | 36.444444 | 117 | 0.707317 | [
"MIT"
] | ActiveDbSoft/active-query-builder-3-asp-net-samples-csharp | NancyFX/Bootstrapper.cs | 986 | C# |
/* =======================================================================
Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace BoSSS.Solution.Gnuplot {
/// <summary>
/// Default gnuplot line colors
/// </summary>
public enum LineColors {
/// <summary>
///
/// </summary>
Red = 1,
/// <summary>
///
/// </summary>
Green = 2,
/// <summary>
///
/// </summary>
Blue = 3,
/// <summary>
///
/// </summary>
Magenta = 4,
///// <summary>
/////
///// </summary>
//LightBlue = 5,
/// <summary>
///
/// </summary>
Yellow = 6,
/// <summary>
///
/// </summary>
Black = 7,
/// <summary>
///
/// </summary>
Orange = 8,
/// <summary>
///
/// </summary>
Grey = 9
}
}
| 23.471429 | 110 | 0.475959 | [
"Apache-2.0"
] | FDYdarmstadt/BoSSS | src/L3-solution/BoSSS.Solution.Gnuplot/LineColors.cs | 1,576 | C# |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class KeySettings : MonoBehaviour {
public ClassSettingsDictionary allSettingData = new ClassSettingsDictionary();
[System.Serializable]
public class ClassSettingsDictionary : SDictionary<string, ClassSettingData> { }
[System.Serializable]
public class ClassSettingData {
public string friendlyName;
public string fullTypeName;
public bool enabled = true;
public FieldSettingsDictionary fields = new FieldSettingsDictionary();
}
[System.Serializable]
public class FieldSettingsDictionary : SDictionary<string, FieldSettingData> { }
[System.Serializable]
public class FieldSettingData {
public string fieldName;
public KeyCode keyCode;
}
#if UNITY_EDITOR
public void resetEnabled() {
foreach (var s in allSettingData.Values.Where(s => s.enabled)) {
s.fields.Clear();
}
findAll();
}
public void enableAll() {
foreach (var pair in allSettingData) {
pair.Value.enabled = true;
}
}
public void disableAll() {
foreach (var pair in allSettingData) {
pair.Value.enabled = false;
}
}
public void resetClass(object fullClassName) {
allSettingData.Remove((string)fullClassName);
findAll();
}
private void findAll() {
IEnumerable<MonoScript> assets = AssetDatabase.FindAssets("t:" + typeof(MonoScript).Name)
.Select(guid => AssetDatabase.GUIDToAssetPath(guid))
.Select(path => AssetDatabase.LoadAssetAtPath(path, typeof(MonoScript)))
.Select(obj => (MonoScript)obj);
ClassSettingsDictionary previousSettings = allSettingData;
allSettingData = new ClassSettingsDictionary();
foreach (MonoScript script in assets) {
System.Type type = script.GetClass();
if (type == null) {
continue;
}
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
ClassSettingData classSettingData;
if (!previousSettings.TryGetValue(type.FullName, out classSettingData)) {
classSettingData = new ClassSettingData();
classSettingData.friendlyName = type.Name;
classSettingData.fullTypeName = type.FullName;
classSettingData.fields = new FieldSettingsDictionary();
}
foreach (FieldInfo field in fields) {
if (field.FieldType == typeof(KeyCode)) {
FieldSettingData fieldSettingData;
if (!classSettingData.fields.TryGetValue(field.Name, out fieldSettingData)) {
fieldSettingData = new FieldSettingData();
fieldSettingData.fieldName = field.Name;
fieldSettingData.keyCode = (KeyCode)field.GetValue(null);
}
classSettingData.fields[field.Name] = fieldSettingData;
}
}
if (classSettingData.fields.Count != 0) {
allSettingData[type.FullName] = classSettingData;
}
}
}
#endif
void Awake() {
if (Application.isPlaying) {
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (ClassSettingData classSetting in allSettingData.Values) {
System.Type type = assembly.GetType(classSetting.fullTypeName);
if (type == null) continue;
foreach (FieldSettingData fieldSetting in classSetting.fields.Values) {
FieldInfo field = type.GetField(fieldSetting.fieldName, BindingFlags.Static | BindingFlags.Public);
if (field == null) continue;
if (classSetting.enabled) {
field.SetValue(null, fieldSetting.keyCode);
} else {
field.SetValue(null, KeyCode.None);
}
}
}
} else {
#if UNITY_EDITOR
KeySettings[] allKeySettings = FindObjectsOfType<KeySettings>();
if (allKeySettings.Length != 1) {
Debug.LogError("Cannot have more than one KeySettings component in the scene!");
DestroyImmediate(this);
return;
}
findAll();
#endif
}
}
}
| 33.367647 | 119 | 0.607536 | [
"Apache-2.0"
] | leapmotion-examples/SpaceLeap | Assets/Scripts/Utility/Options/KeySettings.cs | 4,540 | C# |
using System.Management.Automation;
using PrtgAPI.PowerShell.Base;
namespace PrtgAPI.PowerShell.Cmdlets
{
/// <summary>
/// <para type="synopsis">Removes a notification trigger from a PRTG Object.</para>
///
/// <para type="description">The Remove-NotificationTrigger cmdlet removes a notification trigger from a PRTG Object.
/// Notification triggers can only be removed from the objects on which they are explicitly defined. Attempting to
/// remove a notification trigger from an object which inherits the trigger from its parent will generate an exception.</para>
/// <para type="description">If invoked with no arguments other than the notification trigger to be deleted, Remove-NotificationTrigger
/// will prompt for confirmation of each trigger to be deleted. If you wish to remove multiple triggers, it is recommended to
/// first run Remove-NotificationTrigger with the -WhatIf parameter, and then re-run with the -Force parameter if the results of
/// -WhatIf look correct</para>
/// <para type="description">When invoked with -WhatIf, Remove-NotificationTrigger will list all notification triggers that would have been removed,
/// along with the OnNotificationAction and Sub ID of the notification trigger and the object ID of the object to which the triggers are applied.
/// Even if you are sure of the triggers you wish to delete, it is recommended to always run with -WhatIf first to confirm you have specified
/// the correct triggers and that PrtgAPI has interpreted your request in the way you intended.</para>
///
/// <example>
/// <code>
/// C:\> Get-Device dc-1 | Get-NotificationTrigger | Remove-NotificationTrigger -WhatIf
/// "What if: Performing operation "Remove-NotificationTrigger" on target "'Email to Administrator' (Object ID: 2002, Sub ID: 1)""
/// </code>
/// <para>Preview what will happen when you attempt all triggers from all devices with the name 'dc-1'</para>
/// <para/>
/// </example>
/// <example>
/// <code>C:\> Get-Device dc-1 | Get-NotificationTrigger | Remove-NotificationTrigger -Force</code>
/// <para>Remove all notification triggers from devices named 'dc-1' without prompting for confirmation.</para>
/// </example>
///
/// <para type="link" uri="https://github.com/lordmilko/PrtgAPI/wiki/Notification-Triggers#remove-1">Online version:</para>
/// <para type="link">Get-NotificationTrigger</para>
/// </summary>
[Cmdlet(VerbsCommon.Remove, "NotificationTrigger", SupportsShouldProcess = true)]
public class RemoveNotificationTrigger : PrtgOperationCmdlet
{
/// <summary>
/// <para type="description">Notification trigger to remove.</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The notification trigger to remove.")]
public NotificationTrigger Trigger { get; set; }
/// <summary>
/// <para type="description">Forces a notification trigger to be removed without displaying a confirmation prompt.</para>
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Remove the notification trigger without prompting for confirmation.")]
public SwitchParameter Force { get; set; }
/// <summary>
/// Performs enhanced record-by-record processing functionality for the cmdlet.
/// </summary>
protected override void ProcessRecordEx()
{
if (ShouldProcess($"'{Trigger.OnNotificationAction}' (Object ID: {Trigger.ObjectId}, Sub ID: {Trigger.SubId})"))
{
if (Force.IsPresent || ShouldContinue($"Are you sure you want to delete notification trigger '{Trigger.OnNotificationAction}' (Object ID: {Trigger.ObjectId}, Sub ID: {Trigger.SubId})", "WARNING!"))
ExecuteOperation(() => client.RemoveNotificationTrigger(Trigger), $"Removing notification trigger '{Trigger.OnNotificationAction}' from Object {Trigger.ObjectId}");
}
}
internal override string ProgressActivity => "Removing Notification Triggers";
}
}
| 62.507463 | 213 | 0.686724 | [
"MIT"
] | ericsp59/PrtgAPI | src/PrtgAPI.PowerShell/PowerShell/Cmdlets/ObjectManipulation/RemoveNotificationTrigger.cs | 4,190 | 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("7.Calculate")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("7.Calculate")]
[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("ef568907-6ab7-4cdd-bef2-499774048799")]
// 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.702703 | 84 | 0.743369 | [
"MIT"
] | snukal/All-Telerik-Homeworks | C#1/Loops/7.Calculate/Properties/AssemblyInfo.cs | 1,398 | C# |
using Melanchall.DryWetMidi.Common;
using Melanchall.DryWetMidi.Interaction;
using NUnit.Framework;
namespace Melanchall.DryWetMidi.Tests.Interaction
{
[TestFixture]
public sealed class NoteIdTests
{
#region Test methods
#region Equals
[Test]
public void Equals_NullObject()
{
var noteId = new NoteId(new FourBitNumber(), new SevenBitNumber());
Assert.AreNotEqual(noteId, null, "A null and non-null object are equal.");
}
[Test]
public void Equals_SameObject()
{
var noteId = new NoteId(new FourBitNumber(), new SevenBitNumber());
Assert.AreEqual(noteId, noteId, "An object is not equal to itself.");
}
[Test]
public void Equals_DifferentObjectType()
{
var noteId1 = new NoteId(new FourBitNumber(), new SevenBitNumber());
var noteId2 = new object();
Assert.AreNotEqual(noteId1, noteId2, "Objects of different types are equal.");
}
[Test]
public void Equals_SameValues()
{
var noteId1 = new NoteId(new FourBitNumber(1), new SevenBitNumber(2));
var noteId2 = new NoteId(new FourBitNumber(1), new SevenBitNumber(2));
Assert.AreEqual(noteId1, noteId2, "Identical objects are not equal.");
}
[Test]
public void Equals_DifferentChannelValues()
{
var noteId1 = new NoteId(new FourBitNumber(1), new SevenBitNumber(2));
var noteId2 = new NoteId(new FourBitNumber(2), new SevenBitNumber(2));
Assert.AreNotEqual(noteId1, noteId2, "Objects with mismatched channel values are equal.");
}
[Test]
public void Equals_DifferentNoteNumberValues()
{
var noteId1 = new NoteId(new FourBitNumber(1), new SevenBitNumber(2));
var noteId2 = new NoteId(new FourBitNumber(1), new SevenBitNumber(3));
Assert.AreNotEqual(noteId1, noteId2, "Objects with mismatched note number values are equal.");
}
#endregion
#region GetHashCode
[Test]
public void GetHashCode_Empty()
{
var noteId1 = new NoteId(new FourBitNumber(), new SevenBitNumber());
var noteId2 = new NoteId(new FourBitNumber(), new SevenBitNumber());
Assert.AreEqual(noteId1.GetHashCode(), noteId2.GetHashCode(), "Hash codes for identical empty objects are different.");
}
[Test]
public void GetHashCode_Same()
{
var noteId1 = new NoteId(new FourBitNumber(1), new SevenBitNumber(2));
var noteId2 = new NoteId(new FourBitNumber(1), new SevenBitNumber(2));
Assert.AreEqual(noteId1.GetHashCode(), noteId2.GetHashCode(), "Hash codes for identical objects are different.");
}
[Test]
public void GetHashCode_Different()
{
var noteId1 = new NoteId(new FourBitNumber(1), new SevenBitNumber(2));
var noteId2 = new NoteId(new FourBitNumber(2), new SevenBitNumber(1));
Assert.AreNotEqual(noteId1.GetHashCode(), noteId2.GetHashCode(), "Hash codes for different objects are the same.");
}
#endregion
#endregion
}
}
| 35.473118 | 131 | 0.614732 | [
"MIT"
] | MoogleTroupe/drywetmidi | DryWetMidi.Tests/Interaction/Utilities/NodeId/NoteIdTests.cs | 3,301 | C# |
// this code is generated. don't modify this code.
using System.Text.Json;
namespace VrmValidator
{
// .animations[{0}].channels[{1}].target.extras
public class gltf__animations_ITEM__channels_ITEM__target__extras__Validator
{
ValidationContext m_context;
public gltf__animations_ITEM__channels_ITEM__target__extras__Validator(ValidationContext context)
{
m_context = context;
}
public void Validate(JsonElement json)
{
foreach(var kv in json.EnumerateObject())
{
// unknown key
m_context.AddMessage(MessageTypes.UnknownProperty, kv.Value, ".animations[{0}].channels[{1}].target.extras", kv.Name);
}
}
}
}
| 27.724138 | 135 | 0.603234 | [
"MIT"
] | ousttrue/vrm-protobuf | VrmJsonScheme/Validator/Generated/gltf__animations_ITEM__channels_ITEM__target__extras__Validator.cs | 806 | C# |
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace UnofficialGiphyUwp.Views
{
public sealed partial class SettingsPage : Page
{
Template10.Services.SerializationService.ISerializationService _SerializationService;
public SettingsPage()
{
InitializeComponent();
_SerializationService = Template10.Services.SerializationService.SerializationService.Json;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var index = _SerializationService.Deserialize<int>(e.Parameter?.ToString());
MyPivot.SelectedIndex = index;
}
}
}
| 29.416667 | 103 | 0.695467 | [
"MIT"
] | kg73/GiphyDotNet | UnofficialGiphyUwp/Views/SettingsPage.xaml.cs | 706 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using Microsoft.EntityFrameworkCore;
namespace JwtAuthApi.Entities
{
[Owned]
public class RefreshToken
{
[Key]
[JsonIgnore]
public int Id { get; set; }
public string Token { get; set; }
public DateTime Expires { get; set; }
public bool IsExpired => DateTime.UtcNow >= Expires;
public DateTime Created { get; set; }
public string CreatedByIp { get; set; }
public DateTime? Revoked { get; set; }
public string RevokedByIp { get; set; }
public string ReplacedByToken { get; set; }
public bool IsActive => Revoked == null && !IsExpired;
}
}
| 28.807692 | 62 | 0.632844 | [
"MIT"
] | Tianbowen/AspNetCore3xJwtAuthApiExample | JwtAuthApi/Entities/RefreshToken.cs | 751 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
namespace Microsoft.Dnx.Runtime.Json
{
internal class JsonNumber : JsonValue
{
private readonly string _raw;
private readonly double _double;
public JsonNumber(JsonToken token)
: base(token.Line, token.Column)
{
try
{
_raw = token.Value;
_double = double.Parse(_raw, NumberStyles.Float);
}
catch (FormatException ex)
{
throw new JsonDeserializerException(
JsonDeserializerResource.Format_InvalidFloatNumberFormat(_raw),
ex,
token.Line,
token.Column);
}
catch (OverflowException ex)
{
throw new JsonDeserializerException(
JsonDeserializerResource.Format_FloatNumberOverflow(_raw),
ex,
token.Line,
token.Column);
}
}
public double Double
{
get { return _double; }
}
public string Raw
{
get { return _raw; }
}
}
}
| 27.333333 | 111 | 0.517217 | [
"Apache-2.0"
] | cemoses/aspnet | dnx-dev/src/Microsoft.Dnx.Runtime.Json.Sources/JsonNumber.cs | 1,396 | C# |
// Copyright © 2020 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp.DevTools.Browser
{
/// <summary>
/// Chrome histogram.
/// </summary>
[System.Runtime.Serialization.DataContractAttribute]
public class Histogram : CefSharp.DevTools.DevToolsDomainEntityBase
{
/// <summary>
/// Name.
/// </summary>
[System.Runtime.Serialization.DataMemberAttribute(Name = ("name"), IsRequired = (true))]
public string Name
{
get;
set;
}
/// <summary>
/// Sum of sample values.
/// </summary>
[System.Runtime.Serialization.DataMemberAttribute(Name = ("sum"), IsRequired = (true))]
public int Sum
{
get;
set;
}
/// <summary>
/// Total number of samples.
/// </summary>
[System.Runtime.Serialization.DataMemberAttribute(Name = ("count"), IsRequired = (true))]
public int Count
{
get;
set;
}
/// <summary>
/// Buckets.
/// </summary>
[System.Runtime.Serialization.DataMemberAttribute(Name = ("buckets"), IsRequired = (true))]
public System.Collections.Generic.IList<CefSharp.DevTools.Browser.Bucket> Buckets
{
get;
set;
}
}
} | 28.365385 | 100 | 0.545763 | [
"BSD-3-Clause"
] | campersau/CefSharp | CefSharp/DevTools/Browser/Histogram.cs | 1,476 | 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("Reverse Array In-place")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Reverse Array In-place")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("efbc3df8-1601-4578-8aa1-938be33850d7")]
// 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.297297 | 84 | 0.744531 | [
"MIT"
] | danielstaikov/List-and-others | Reverse Array In-place/Properties/AssemblyInfo.cs | 1,420 | C# |
using System;
using Caliburn.Micro;
using SharpDj.Models;
namespace SharpDj.ViewModels.SubViews.LeftMenuComponents
{
public class ObservedRoomViewModel : PropertyChangedBase
{
public BindableCollection<RoomModel> ObservedRoomCollection { get; private set; }
public ObservedRoomViewModel()
{
var dicPic = @"..\..\..\..\Images\3.jpg";
ObservedRoomCollection = new BindableCollection<RoomModel>()
{
new RoomModel(){AmountOfAdministration = 3, AmountOfPeople = 49, Id = 1, ImageSource = dicPic, Name = "Testowa nazwa pokoju"},
new RoomModel(){AmountOfAdministration = 4, AmountOfPeople = 23, Id = 2, ImageSource = dicPic, Name = "Pokój"},
};
}
}
}
| 33.565217 | 142 | 0.63342 | [
"MIT"
] | newbiedeveloper9/Sharpdj | Client/ViewModels/SubViews/LeftMenuComponents/ObservedRoomViewModel.cs | 775 | C# |
/*----------------------------------------------------------------
Copyright (C) 2022 Senparc
文件名:RequestMessageEvent_Location.cs
文件功能描述:事件之上报地理位置事件
创建标识:Senparc - 20150313
修改标识:Senparc - 20150313
修改描述:整理接口
----------------------------------------------------------------*/
namespace Senparc.Weixin.Work.Entities
{
/// <summary>
/// 上报地理位置事件
/// </summary>
public class RequestMessageEvent_Location : RequestMessageEventBase, IRequestMessageEventBase
{
public override Event Event
{
get { return Event.LOCATION; }
}
/// <summary>
/// 地理位置纬度
/// </summary>
public double Latitude { get; set; }
/// <summary>
/// 地理位置经度
/// </summary>
public double Longitude { get; set; }
/// <summary>
/// 地理位置精度
/// </summary>
public double Precision { get; set; }
}
}
| 23.9 | 97 | 0.465481 | [
"Apache-2.0"
] | AaronWu666/WeiXinMPSDK | src/Senparc.Weixin.Work/Senparc.Weixin.Work/Entities/Request/Event/RequestMessageEvent_Location.cs | 1,092 | C# |
using System.Threading;
using System.Threading.Tasks;
using Inshapardaz.Desktop.Common;
using Inshapardaz.Desktop.Common.Models;
using Inshapardaz.Desktop.Common.Queries;
using Microsoft.EntityFrameworkCore;
using Paramore.Darker;
namespace Inshapardaz.Desktop.Database.Client.QueryHandlers
{
public class GetDictionaryByIdQueryHandler : QueryHandlerAsync<GetDictionaryByIdQuery, DictionaryModel>
{
private readonly IProvideDatabase _databaseProvider;
public GetDictionaryByIdQueryHandler(IProvideDatabase databaseProvider)
{
_databaseProvider = databaseProvider;
}
public override async Task<DictionaryModel> ExecuteAsync(GetDictionaryByIdQuery query, CancellationToken cancellationToken = new CancellationToken())
{
using (var database = _databaseProvider.GetDatabaseForDictionary(query.Id))
{
var dictionary = await database.Dictionary.FirstOrDefaultAsync(d => d.Id == query.Id, cancellationToken);
var result = dictionary.Map<Data.Entities.Dictionary, DictionaryModel>();
result.WordCount = await database.Word.CountAsync(w => w.DictionaryId == dictionary.Id, cancellationToken);
return result;
}
}
}
} | 42.966667 | 157 | 0.719162 | [
"MIT"
] | inshapardaz/desktop-client | src/api/Inshapardaz.Desktop.Database.Client/QueryHandlers/GetDictionaryByIdQueryHandler.cs | 1,291 | C# |
using System.Reflection;
namespace NCop.Aspects.Engine
{
public interface IFunctionArgs<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TResult>
{
TArg1 Arg1 { get; set; }
TArg2 Arg2 { get; set; }
TArg3 Arg3 { get; set; }
TArg4 Arg4 { get; set; }
TArg5 Arg5 { get; set; }
TArg6 Arg6 { get; set; }
TArg7 Arg7 { get; set; }
TArg8 Arg8 { get; set; }
MethodInfo Method { get; set; }
TResult ReturnValue { get; set; }
}
}
| 27.315789 | 99 | 0.554913 | [
"MIT"
] | sagifogel/NCop | NCop.Aspects/Engine/IFunctionArgs`8.cs | 521 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Site
{
public partial class Logar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UNAME"]!=null && Request.Cookies["PWD"]!=null)
{
Usuario.Text = Request.Cookies["UNAME"].Value;
Senha.Attributes["value"]= Request.Cookies["PWD"].Value;
// CheckBox1.Checked = true;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["dadosConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("select * from Usuarios where Usuario='"+Usuario.Text+"' and Senha='"+Senha.Text+"'",con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);//para armazenar informaçoes no banco
DataTable dt = new DataTable();//criando uma nova tabela para prencehr os dados
sda.Fill(dt);
if (dt.Rows.Count!=0)// se a senha e o nome concedir com a tabela ele joga na UsuarioInicio
{
if (dt.Rows.Count!=0)
{
Response.Redirect("~/Default.aspx");
}
else
{
Response.Cookies["UNAME"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["PWD"].Expires = DateTime.Now.AddDays(-1);
}
Session["USERNAME"] = Usuario.Text;
Response.Redirect("~/Default.aspx");
}
else
{
lblError.Text = "Invalido Usuario e Senha !!!";
}
}
}
}
}
| 31.571429 | 135 | 0.50724 | [
"MIT"
] | williamsartijose/Trabalho-Cadastro-de-Aluno | Logar.aspx.cs | 2,213 | C# |
// Developed by Softeq Development Corporation
// http://www.softeq.com
using System.Net.Http;
using Softeq.HttpClient.Extension;
using Softeq.HttpClient.Extension.Utility;
namespace Softeq.NetKit.ProfileService.Utility.HttpClient
{
public class ProfileHttpClient : RestHttpClientBase
{
public ProfileHttpClient(IHttpClientFactory httpClientFactory, string clientName, IExceptionHandler exceptionHandler)
: base(httpClientFactory, clientName, exceptionHandler)
{
}
protected override string ApiUrl { get; }
}
} | 30 | 125 | 0.74386 | [
"MIT"
] | Softeq/NetKit.Profile | Softeq.NetKit.Profile.Service/Utility/HttpClient/ProfileHttpClient.cs | 572 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace no.teilin.turlogg.Models.ManageViewModels
{
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
}
| 22.117647 | 51 | 0.702128 | [
"MIT"
] | teilin/turlogg | src/Turlogg/Models/ManageViewModels/AddPhoneNumberViewModel.cs | 376 | C# |
using Sort_Algorithm_Visualiser.algorithms;
using Sort_Algorithm_Visualiser.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sort_Algorithm_Visualiser
{
static class main
{
private static gui mainGui;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(mainGui = new gui());
}
}
}
| 23.214286 | 65 | 0.655385 | [
"MIT"
] | ScarVite/Sort-Algorithm-Visualiser | main.cs | 652 | C# |
using System.Collections.Generic;
using System.Linq;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Shell.Applications.ContentEditor;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
using Sitecore.Web.UI.WebControls;
namespace Spe.Client.Controls
{
public class TreelistExtended : TreeList
{
protected new void Add()
{
if (Disabled)
return;
var viewStateString = GetViewStateString("ID");
var control1 = FindControl(viewStateString + "_all") as TreeviewEx;
Assert.IsNotNull(control1, typeof(DataTreeview));
var control2 = FindControl(viewStateString + "_selected") as Listbox;
Assert.IsNotNull(control2, typeof(Listbox));
var selectionItem = control1?.GetSelectionItem(Language.Parse(ItemLanguage), Version.Latest);
if (selectionItem == null)
{
SheerResponse.Alert("Select an item in the Content Tree.");
}
else
{
if (HasExcludeTemplateForSelection(selectionItem)) { return; }
if (IsDeniedMultipleSelection(selectionItem, control2))
{
SheerResponse.Alert("You cannot select the same item twice.");
}
else
{
if (!HasIncludeTemplateForSelection(selectionItem)) { return; }
SheerResponse.Eval($"scForm.browser.getControl('{viewStateString}_selected').selectedIndex=-1");
var listItem = new ListItem {ID = GetUniqueID("L")};
Sitecore.Context.ClientPage.AddControl(control2, listItem);
listItem.Header = GetHeaderValue(selectionItem);
listItem.Value = listItem.ID + "|" + selectionItem.ID;
SheerResponse.Refresh(control2);
SetModified();
}
}
}
private bool HasExcludeTemplateForSelection(Item item)
{
return item == null || HasItemTemplate(item, ExcludeTemplatesForSelection);
}
private bool HasIncludeTemplateForSelection(Item item)
{
Assert.ArgumentNotNull(item, nameof(item));
return IncludeTemplatesForSelection.Length == 0 || HasItemTemplate(item, IncludeTemplatesForSelection);
}
private bool IsDeniedMultipleSelection(Item item, Listbox listbox)
{
Assert.ArgumentNotNull(listbox, nameof(listbox));
if (item == null) { return true; }
if (AllowMultipleSelection) { return false; }
foreach (Control control in listbox.Controls)
{
var strArray = control.Value.Split('|');
if (strArray.Length >= 2 && strArray[1] == item.ID.ToString())
return true;
}
return false;
}
private static bool HasItemTemplate(Item item, string templateList)
{
Assert.ArgumentNotNull(templateList, nameof(templateList));
if (item == null || templateList.Length == 0) { return false; }
var templateNames = templateList.Split(',');
var templateOptions = new List<string>();
foreach (var templateName in templateNames)
{
templateOptions.Add(templateName.Trim().ToLowerInvariant());
}
var hasTemplate = templateOptions.Contains(item.TemplateName.Trim().ToLowerInvariant());
if (hasTemplate) return true;
var template = TemplateManager.GetTemplate(item);
var baseTemplates = template.GetBaseTemplates().Select(t => t.Name.Trim().ToLowerInvariant()).ToList();
foreach (var value in templateOptions)
{
if (Sitecore.Data.ID.IsID(value) && template.DescendsFromOrEquals(Sitecore.Data.ID.Parse(value)))
{
return true;
}
if (baseTemplates.Contains(value))
{
return true;
}
}
return false;
}
}
} | 38.446429 | 116 | 0.576173 | [
"MIT"
] | PavloGlazunov/Console | src/Spe/Client/Controls/TreelistExtended.cs | 4,308 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPFCadastroRegex
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
| 20.709677 | 45 | 0.711838 | [
"MIT"
] | DanielaLischeski/GitDani | WPF/WPFCadastroRegex/WPFCadastroRegex/MainWindow.xaml.cs | 644 | C# |
// <auto-generated />
namespace MOE.Common.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class EventCounts : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(EventCounts));
string IMigrationMetadata.Id
{
get { return "201802282114224_EventCounts"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27.166667 | 94 | 0.618405 | [
"Apache-2.0"
] | AndreRSanchez/ATSPM | MOE.Common/Migrations/201802282114224_EventCounts.Designer.cs | 815 | C# |
using Business.Communication;
using Business.Domain.Models;
using Business.Domain.Services;
using Business.Resources;
using Business.Resources.Location;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace API.Controllers
{
[Route("api/v1/location")]
public class LocationController : DongNguyenController<LocationResource, CreateLocationResource, UpdateLocationResource, Location>
{
#region Constructor
public LocationController(ILocationService locationService,
IOptionsMonitor<ResponseMessage> responseMessage) : base(locationService, responseMessage)
{
}
#endregion
#region Action
[HttpGet]
[Authorize(Roles = "viewer, editor, admin")]
[ProducesResponseType(typeof(BaseResponse<IEnumerable<LocationResource>>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(BaseResponse<IEnumerable<LocationResource>>), StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(BaseResponse<IEnumerable<LocationResource>>), StatusCodes.Status400BadRequest)]
public new async Task<IActionResult> GetAllAsync()
=> await base.GetAllAsync();
[HttpGet("{id:int}")]
[Authorize(Roles = "viewer, editor, admin")]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status400BadRequest)]
public new async Task<IActionResult> GetByIdAsync(int id)
=> await base.GetByIdAsync(id);
[HttpPost]
[Authorize(Roles = "editor, admin")]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status400BadRequest)]
public new async Task<IActionResult> CreateAsync([FromBody] CreateLocationResource resource)
=> await base.CreateAsync(resource);
[HttpPut("{id:int}")]
[Authorize(Roles = "editor, admin")]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status400BadRequest)]
public new async Task<IActionResult> UpdateAsync(int id, [FromBody] UpdateLocationResource resource)
=> await base.UpdateAsync(id, resource);
[HttpDelete("{id:int}")]
[Authorize(Roles = "admin")]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(BaseResponse<LocationResource>), StatusCodes.Status400BadRequest)]
public new async Task<IActionResult> DeleteAsync(int id)
=> await base.DeleteAsync(id);
#endregion
}
}
| 47.661538 | 134 | 0.729503 | [
"MIT"
] | dong-nguyen-hd/HR-Management | BE/API/Controllers/LocationController.cs | 3,100 | C# |
using BudgetScale.Application.Tests.Infrastructure;
using BudgetScale.Application.Users;
using NUnit.Framework;
namespace BudgetScale.Application.Tests.Users
{
public class UserModelsTests : BudgetScaleTestBase
{
[Test]
public void CredentialsModelValidator_ValidatesValidData()
{
var validator = new CredentialsBindingModelValidator();
var result = validator.Validate(new CredentialsBindingModel
{
Email = "this.is.Arandomm3il@gmail.com",
Password = "thisShouldB3AGoodPassword"
});
Assert.True(result.IsValid);
}
[Test]
public void CredentialsModelValidator_CatchesInvalidEmail()
{
var validator = new CredentialsBindingModelValidator();
var result = validator.Validate(new CredentialsBindingModel
{
Email = "invalidMail",
Password = "thisShouldB3AGoodPassword"
});
Assert.True(!result.IsValid);
}
[Test]
[TestCase("short")]
[TestCase("This is actually very long password that should not be fit in the model and should be discarded")]
public void CredentialsModelValidator_CatchesInvalidPassword(string password)
{
var validator = new CredentialsBindingModelValidator();
var result = validator.Validate(new CredentialsBindingModel
{
Email = "this.is.Arandomm3il@gmail.com",
Password = password
});
Assert.True(!result.IsValid);
}
[Test]
public void UserRegisterBindingModelValidator_ValidatesValidData()
{
var validator = new UserRegisterBindingModelValidator();
var result = validator.Validate(new UserRegisterBindingModel
{
Email = "this.is.Arandomm3il@gmail.com",
Password = "thisShouldB3AGoodPassword",
FullName = "A random name"
});
Assert.True(result.IsValid);
}
[Test]
public void UserRegisterBindingModelValidator_CatchesInvalidEmail()
{
var validator = new UserRegisterBindingModelValidator();
var result = validator.Validate(new UserRegisterBindingModel
{
Email = "invalidMail",
Password = "thisShouldB3AGoodPassword",
FullName = "A random name"
});
Assert.True(!result.IsValid);
}
[Test]
[TestCase("short")]
[TestCase("This is actually very long password that should not be fit in the model and should be discarded")]
public void UserRegisterBindingModelValidator_CatchesInvalidPassword(string password)
{
var validator = new UserRegisterBindingModelValidator();
var result = validator.Validate(new UserRegisterBindingModel
{
Email = "this.is.Arandomm3il@gmail.com",
Password = password,
FullName = "A random name"
});
Assert.True(!result.IsValid);
}
[Test]
public void UserRegisterBindingModelValidator_CatchesInvalidFullName()
{
var validator = new UserRegisterBindingModelValidator();
var result = validator.Validate(new UserRegisterBindingModel
{
Email = "invalidMail",
Password = "thisShouldB3AGoodPassword",
FullName = "A random name A random name A random name A random name A random name A random name A random name A random name A random name A random name A random name A random name A random name "
});
Assert.True(!result.IsValid);
}
}
} | 32.771186 | 211 | 0.593742 | [
"MIT"
] | NikolayPIvanov/Budget-Scale | tests/BudgetScale.Application.Tests/Users/UserModelsTests.cs | 3,869 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview
{
using Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.PowerShell;
/// <summary>tags to be updated</summary>
[System.ComponentModel.TypeConverter(typeof(ApplicationPatchTagsTypeConverter))]
public partial class ApplicationPatchTags
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ApplicationPatchTags"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal ApplicationPatchTags(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
// this type is a dictionary; copy elements from source to here.
CopyFrom(content);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ApplicationPatchTags"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal ApplicationPatchTags(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
// this type is a dictionary; copy elements from source to here.
CopyFrom(content);
AfterDeserializePSObject(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ApplicationPatchTags"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IApplicationPatchTags"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IApplicationPatchTags DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new ApplicationPatchTags(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.ApplicationPatchTags"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IApplicationPatchTags"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IApplicationPatchTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new ApplicationPatchTags(content);
}
/// <summary>
/// Creates a new instance of <see cref="ApplicationPatchTags" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api20210201Preview.IApplicationPatchTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// tags to be updated
[System.ComponentModel.TypeConverter(typeof(ApplicationPatchTagsTypeConverter))]
public partial interface IApplicationPatchTags
{
}
} | 58.474074 | 268 | 0.677857 | [
"MIT"
] | AndriiKalinichenko/azure-powershell | src/DesktopVirtualization/generated/api/Models/Api20210201Preview/ApplicationPatchTags.PowerShell.cs | 7,760 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Test.Apex;
using Microsoft.Test.Apex.VisualStudio;
namespace Microsoft.VisualStudio.ProjectSystem.VS
{
public abstract class IntegrationTestBase : VisualStudioHostTest
{
protected IntegrationTestBase()
{
// TestCleanup will fire up another instance of Visual Studio to reset
// the AutoloadExternalChanges if it thinks the default changed even if
// that was just caused by settings to be sync'd. Just turn this feature off.
SuppressReloadPrompt = false;
}
protected override bool IncludeReferencedAssembliesInHostComposition => false; // Do not add things we reference to the MEF Container
protected override VisualStudioHostConfiguration GetHostConfiguration()
{
return new ProjectSystemHostConfiguration();
}
protected override OperationsConfiguration GetOperationsConfiguration()
{
return new ProjectSystemOperationsConfiguration(TestContext);
}
public new void TryShutdownVisualStudioInstance()
{
base.TryShutdownVisualStudioInstance();
}
}
}
| 38 | 162 | 0.678363 | [
"Apache-2.0"
] | MSLukeWest/project-system | tests/Microsoft.VisualStudio.ProjectSystem.IntegrationTests/IntegrationTestBase.cs | 1,335 | C# |
using System;
using System.ComponentModel;
using System.Linq;
namespace Aigamo.Saruhashi
{
public class RadioButton : ButtonBase
{
private bool _autoCheck = true;
private bool _checked;
public RadioButton() : base()
{
IsChecked = () => Checked;
SetStyle(ControlStyles.StandardClick, false);
}
public Appearance Appearance { get; set; }
public bool AutoCheck
{
get => _autoCheck;
set
{
if (_autoCheck == value)
return;
_autoCheck = value;
PerformAutoUpdates();
}
}
public bool Checked
{
get => _checked;
set
{
if (_checked == value)
return;
_checked = value;
PerformAutoUpdates();
OnCheckedChanged(EventArgs.Empty);
}
}
protected Func<bool> IsChecked { get; set; }
public event EventHandler? CheckedChanged;
private CheckBoxState DetermineState(bool up)
{
var isChecked = IsChecked();
if (isChecked)
{
if (!up)
return CheckBoxState.CheckedPressed;
if (MouseIsOver)
return CheckBoxState.CheckedHot;
if (!IsEnabled())
return CheckBoxState.CheckedDisabled;
return CheckBoxState.CheckedNormal;
}
else
{
if (!up)
return CheckBoxState.UncheckedPressed;
if (MouseIsOver)
return CheckBoxState.UncheckedHot;
if (!IsEnabled())
return CheckBoxState.UncheckedDisabled;
return CheckBoxState.UncheckedNormal;
}
}
protected virtual void OnCheckedChanged(EventArgs e) => CheckedChanged?.Invoke(this, e);
protected override void OnClick(EventArgs e)
{
if (AutoCheck)
Checked = true;
base.OnClick(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (Capture && WindowManager.WindowFromPoint(PointToScreen(e.Location)) == this)
{
OnClick(EventArgs.Empty);
OnMouseClick(new MouseEventArgs(e.Button, e.Clicks, PointToClient(e.Location), e.Delta));
}
}
base.OnMouseUp(e);
}
protected override void OnPaint(PaintEventArgs e)
{
switch (Appearance)
{
case Appearance.Normal:
throw new NotImplementedException();
case Appearance.Button:
PushButtonState pushButtonState = DetermineState(!MouseIsDown) switch
{
CheckBoxState.UncheckedNormal => PushButtonState.Normal,
CheckBoxState.UncheckedHot => PushButtonState.Hot,
CheckBoxState.UncheckedPressed => PushButtonState.Pressed,
CheckBoxState.UncheckedDisabled => PushButtonState.Disabled,
CheckBoxState.CheckedNormal => PushButtonState.Pressed,
CheckBoxState.CheckedHot => PushButtonState.Pressed,
CheckBoxState.CheckedPressed => PushButtonState.Pressed,
CheckBoxState.CheckedDisabled => PushButtonState.Disabled,
_ => 0,
};
ButtonRenderer.DrawButton(e.Graphics, ClientRectangle, GetText(), Font, focused: false, pushButtonState);
break;
}
base.OnPaint(e);
}
private void PerformAutoUpdates()
{
if (!_autoCheck)
return;
if (Checked && Parent != null)
{
var radioButtons = Parent.Controls
.Where(c => c != this && c is RadioButton)
.Select(c => c as RadioButton)
.Where(b => b.AutoCheck && b.Checked);
foreach (var b in radioButtons)
{
var propDesc = TypeDescriptor.GetProperties(this)[nameof(Checked)];
propDesc.SetValue(b, false);
}
}
}
}
}
| 21.670968 | 110 | 0.673415 | [
"MIT"
] | ycanardeau/Saruhashi | Aigamo.Saruhashi/RadioButton.cs | 3,361 | C# |
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using Sce.Atf.VectorMath;
namespace Sce.Atf.Controls.Adaptable.Graphs
{
/// <summary>
/// OBSOLETE. Please use D2dCircuitRenderer instead.
/// Graph renderer that draws graph nodes as circuit elements, and edges as wires.
/// Elements have 0 or more output pins, where wires originate, and 0 or more input
/// pins, where wires end. Output pins are on the right and input pins are on the left
/// side of elements.</summary>
/// <typeparam name="TElement">Element type, must implement IElementType, and IGraphNode</typeparam>
/// <typeparam name="TWire">Wire type, must implement IGraphEdge</typeparam>
/// <typeparam name="TPin">Pin type, must implement ICircuitPin, IEdgeRoute</typeparam>
public class CircuitRenderer<TElement, TWire, TPin> : GraphRenderer<TElement, TWire, TPin>, IDisposable
where TElement : class, ICircuitElement
where TWire : class, IGraphEdge<TElement, TPin>
where TPin : class, ICircuitPin
{
/// <summary>
/// Constructor</summary>
/// <param name="theme">Diagram theme for rendering graph</param>
public CircuitRenderer(DiagramTheme theme)
{
Theme = theme;
SetPinSpacing();
}
/// <summary>
/// Disposes resources</summary>
/// <param name="disposing">If true, then Dispose() called this method and managed resources should
/// be released in addition to unmanaged resources. If false, then the finalizer called this method
/// and no managed objects should be called and only unmanaged resources should be released.</param>
protected override void Dispose(bool disposing)
{
DisposeElementInfo();
Theme = null;
base.Dispose(disposing);
}
/// <summary>
/// Gets or sets the diagram theme</summary>
public DiagramTheme Theme
{
get { return m_theme; }
set
{
if (m_theme != value)
{
if (m_theme != null)
m_theme.Redraw -= theme_Redraw;
m_theme = value;
if (m_theme != null)
m_theme.Redraw += theme_Redraw;
base.OnRedraw();
}
}
}
/// <summary>
/// Invalidates cached info for element type name</summary>
/// <param name="elementType">Element type to invalidate</param>
public void Invalidate(ICircuitElementType elementType)
{
m_elementTypeCache.Remove(elementType);
OnRedraw();
}
/// <summary>
/// Draws a graph node</summary>
/// <param name="element">Element to draw</param>
/// <param name="style">Diagram drawing style</param>
/// <param name="g">Graphics object</param>
public override void Draw(TElement element, DiagramDrawingStyle style, Graphics g)
{
switch (style)
{
case DiagramDrawingStyle.Normal:
Draw(element, g);
break;
case DiagramDrawingStyle.Selected:
case DiagramDrawingStyle.LastSelected:
case DiagramDrawingStyle.Hot:
default:
Draw(element, g);
DrawOutline(element, m_theme.GetPen(style), g);
break;
case DiagramDrawingStyle.Ghosted:
case DiagramDrawingStyle.Hidden:
DrawGhost(element, g);
break;
}
}
/// <summary>
/// Draws a graph edge</summary>
/// <param name="edge">Edge to draw</param>
/// <param name="style">Diagram drawing style</param>
/// <param name="g">Graphics object</param>
public override void Draw(TWire edge, DiagramDrawingStyle style, Graphics g)
{
TPin inputPin = edge.ToRoute;
TPin outputPin = edge.FromRoute;
Pen pen = (style == DiagramDrawingStyle.Normal) ? GetPen(inputPin) : m_theme.GetPen(style);
DrawWire(edge.FromNode, outputPin, edge.ToNode, inputPin, g, pen);
}
/// <summary>
/// Draws a partially defined graph edge</summary>
/// <param name="outputElement">Source element, or null</param>
/// <param name="outputPin">Source pin, or null</param>
/// <param name="inputElement">Destination element, or null</param>
/// <param name="inputPin">Destination pin, or null</param>
/// <param name="label">Edge label</param>
/// <param name="endPoint">Endpoint to substitute for source or destination, if null</param>
/// <param name="g">Graphics object</param>
public override void Draw(
TElement outputElement,
TPin outputPin,
TElement inputElement,
TPin inputPin,
string label,
Point endPoint,
Graphics g)
{
if (inputElement == null)
{
// dragging from output to endPoint
DrawWire(outputElement, outputPin, endPoint, true, g);
}
else if (outputElement == null)
{
// dragging from input to endPoint
DrawWire(inputElement, inputPin, endPoint, false, g);
}
else
{
// routed edge
Pen pen = GetPen(outputPin);
DrawWire(outputElement, outputPin, inputElement, inputPin, g, pen);
}
}
/// <summary>
/// Gets the bounding rect of a circuit element</summary>
/// <param name="element">Element to get the bounds for.</param>
/// <param name="g">Graphics object</param>
/// <returns>Rectangle completely bounding the node</returns>
public override Rectangle GetBounds(TElement element, Graphics g)
{
Rectangle result = GetElementBounds(element, g);
result.Height += PinMargin + m_rowSpacing; // label at bottom
return GdiUtil.Transform(g.Transform, result);
}
/// <summary>
/// Finds node and/or edge hit by the given point</summary>
/// <param name="graph">Graph to test</param>
/// <param name="priorityEdge">Graph edge to test before others</param>
/// <param name="p">Point to test</param>
/// <param name="g">Graphics object</param>
/// <returns>Hit record containing node and/or edge hit by the given point</returns>
public override GraphHitRecord<TElement, TWire, TPin> Pick(
IGraph<TElement, TWire, TPin> graph, TWire priorityEdge, Point p, Graphics g)
{
TElement pickedElement = null;
TPin pickedInput = null;
TPin pickedOutput = null;
TWire pickedWire = null;
if (priorityEdge != null &&
PickEdge(priorityEdge, p, g))
{
pickedWire = priorityEdge;
}
else
{
foreach (TWire edge in graph.Edges)
{
if (PickEdge(edge, p, g))
{
pickedWire = edge;
break;
}
}
}
foreach (TElement element in graph.Nodes.Reverse())
{
if (Pick(element, g, p))
{
pickedElement = element;
pickedInput = PickInput(element, g, p);
pickedOutput = PickOutput(element, g, p);
break;
}
}
if (pickedElement != null && pickedWire == null)
{
Rectangle bounds = GetElementBounds(pickedElement, g);
Rectangle labelBounds = new Rectangle(
bounds.Left, bounds.Bottom + PinMargin, bounds.Width, m_rowSpacing);
labelBounds = GdiUtil.Transform(g.Transform, labelBounds);
if (labelBounds.Contains(p))
{
DiagramLabel label = new DiagramLabel(
labelBounds,
TextFormatFlags.SingleLine |
TextFormatFlags.HorizontalCenter);
return new GraphHitRecord<TElement, TWire, TPin>(pickedElement, label);
}
}
return new GraphHitRecord<TElement, TWire, TPin>(pickedElement, pickedWire, pickedOutput, pickedInput);
}
private bool PickEdge(TWire edge, Point p, Graphics g)
{
ElementTypeInfo fromInfo = GetElementTypeInfo(edge.FromNode, g);
TPin inputPin = edge.ToRoute;
TPin outputPin = edge.FromRoute;
Point p1 = edge.FromNode.Bounds.Location;
int x1 = p1.X + fromInfo.Size.Width;
int y1 = p1.Y + GetPinOffset(outputPin.Index);
Point p2 = edge.ToNode.Bounds.Location;
int x2 = p2.X;
int y2 = p2.Y + GetPinOffset(inputPin.Index);
int tanLen = GetTangentLength(x1, x2);
BezierCurve2F curve = new BezierCurve2F(
new Vec2F(x1, y1),
new Vec2F(x1 + tanLen, y1),
new Vec2F(x2 - tanLen, y2),
new Vec2F(x2, y2));
Vec2F hitPoint = new Vec2F();
return BezierCurve2F.Pick(curve, new Vec2F(p.X, p.Y), m_theme.PickTolerance, ref hitPoint);
}
/// <summary>
/// Raises the Redraw event</summary>
protected override void OnRedraw()
{
DisposeElementInfo();
m_elementTypeCache.Clear(); // invalidate cached info
base.OnRedraw();
}
private void theme_Redraw(object sender, EventArgs e)
{
OnRedraw();
}
private void Draw(TElement element, Graphics g)
{
ElementTypeInfo info = GetElementTypeInfo(element, g);
Point p = element.Bounds.Location;
Rectangle bounds = new Rectangle(p, info.Size);
// clip to window
if (g.ClipBounds.IntersectsWith(bounds))
{
ICircuitElementType type = element.Type;
if (info.Path == null)
BuildGraphics(type, info, g);
s_pathTransform.Translate(p.X, p.Y);
info.Path.Transform(s_pathTransform);
// try to use custom brush if registered
Brush fillBrush = m_theme.GetCustomBrush(type.Name);
if (fillBrush != null)
{
g.FillPath(fillBrush, info.Path);
}
else
{
// use a default brush
using (LinearGradientBrush lgb = new LinearGradientBrush(
bounds,
Color.White,
Color.LightSteelBlue,
LinearGradientMode.Vertical))
{
g.FillPath(lgb, info.Path);
}
}
g.DrawPath(m_theme.OutlinePen, info.Path);
int titleHeight = m_rowSpacing + PinMargin;
g.DrawLine(m_theme.OutlinePen, p.X, p.Y + titleHeight, p.X + info.Size.Width, p.Y + titleHeight);
g.DrawString(type.Name, m_theme.Font, m_theme.TextBrush, p.X + PinMargin + 1, p.Y + PinMargin + 1);
int pinY = p.Y + titleHeight + PinMargin;
foreach (TPin inputPin in type.Inputs)
{
Pen pen = GetPen(inputPin);
if (pen != null)
g.DrawRectangle(pen, p.X + 1, pinY + m_pinOffset, m_pinSize, m_pinSize);
g.DrawString(inputPin.Name, m_theme.Font, m_theme.TextBrush, p.X + m_pinSize + PinMargin, pinY);
pinY += m_rowSpacing;
}
pinY = p.Y + titleHeight + PinMargin;
int i = 0;
foreach (TPin outputPin in type.Outputs)
{
Pen pen = GetPen(outputPin);
if (pen != null)
g.DrawRectangle(pen, p.X + info.Size.Width - m_pinSize, pinY + m_pinOffset, m_pinSize, m_pinSize);
g.DrawString(outputPin.Name, m_theme.Font, m_theme.TextBrush, p.X + info.OutputLeftX[i], pinY);
pinY += m_rowSpacing;
i++;
}
Image image = type.Image;
if (image != null)
g.DrawImage(image, p.X + info.Interior.X, p.Y + info.Interior.Y, info.Interior.Width, info.Interior.Height);
s_pathTransform.Translate(-2 * p.X, -2 * p.Y);
info.Path.Transform(s_pathTransform);
s_pathTransform.Reset();
string name = element.Name;
if (!string.IsNullOrEmpty(name))
{
RectangleF alignRect = new RectangleF(
bounds.Left - MaxNameOverhang, bounds.Bottom + PinMargin, bounds.Width + 2 * MaxNameOverhang, m_rowSpacing);
g.DrawString(name, m_theme.Font, m_theme.TextBrush, alignRect, m_theme.CenterStringFormat);
}
}
}
private void DrawGhost(TElement element, Graphics g)
{
ElementTypeInfo info = GetElementTypeInfo(element, g);
Point p = element.Bounds.Location;
Rectangle bounds = new Rectangle(p, info.Size);
// clip to window to speed up drawing when zoomed in
if (g.ClipBounds.IntersectsWith(bounds))
{
if (info.Path == null)
{
ICircuitElementType type = element.Type;
BuildGraphics(type, info, g);
}
s_pathTransform.Translate(p.X, p.Y);
info.Path.Transform(s_pathTransform);
g.FillPath(m_theme.GhostBrush, info.Path);
g.DrawPath(m_theme.GhostPen, info.Path);
s_pathTransform.Translate(-2 * p.X, -2 * p.Y);
info.Path.Transform(s_pathTransform);
s_pathTransform.Reset();
}
}
private void DrawOutline(TElement element, Pen pen, Graphics g)
{
ElementTypeInfo info = GetElementTypeInfo(element, g);
if (info.Path == null)
{
ICircuitElementType type = element.Type;
BuildGraphics(type, info, g);
}
Point p = element.Bounds.Location;
s_pathTransform.Translate(p.X, p.Y);
info.Path.Transform(s_pathTransform);
g.DrawPath(pen, info.Path);
s_pathTransform.Translate(2 * -p.X, 2 * -p.Y);
info.Path.Transform(s_pathTransform);
s_pathTransform.Reset();
}
private bool Pick(TElement element, Graphics g, Point p)
{
Rectangle bounds = GetBounds(element, g);
int pickTolerance = m_theme.PickTolerance;
bounds.Inflate(pickTolerance, pickTolerance);
return bounds.Contains(p.X, p.Y);
}
/// <summary>
/// Find input pin, if any, at given point</summary>
/// <param name="element">Element</param>
/// <param name="g">Graphics object</param>
/// <param name="p">Point to test</param>
/// <returns>Input pin hit by p; null otherwise</returns>
private TPin PickInput(TElement element, Graphics g, Point p)
{
Point ep = element.Bounds.Location;
int x = ep.X;
int y = ep.Y + m_rowSpacing + 2 * PinMargin + m_pinOffset;
int width = m_pinSize;
//if (IsDraggingWire)
//{
// ElementTypeInfo info = GetElementTypeInfo(element, g);
// width = info.Width / 2 - m_pickTolerance;
//}
Rectangle bounds = new Rectangle(x, y, width, m_pinSize);
int pickTolerance = m_theme.PickTolerance;
bounds.Inflate(pickTolerance, pickTolerance);
ICircuitElementType type = element.Type;
foreach (TPin input in type.Inputs)
{
if (bounds.Contains(p.X, p.Y))
return input;
bounds.Y += m_rowSpacing;
}
return null;
}
/// <summary>
/// Find output pin, if any, at given point</summary>
/// <param name="element">Element</param>
/// <param name="g">Graphics object</param>
/// <param name="p">Point to test</param>
/// <returns>Output pin hit by p; null otherwise</returns>
private TPin PickOutput(TElement element, Graphics g, Point p)
{
ElementTypeInfo info = GetElementTypeInfo(element, g);
Point ep = element.Bounds.Location;
int x = ep.X + info.Size.Width - m_pinSize;
int y = ep.Y + m_rowSpacing + 2 * PinMargin + m_pinOffset;
int width = m_pinSize;
Rectangle bounds = new Rectangle(x, y, width, m_pinSize);
int pickTolerance = m_theme.PickTolerance;
bounds.Inflate(pickTolerance, pickTolerance);
ICircuitElementType type = element.Type;
foreach (TPin output in type.Outputs)
{
if (bounds.Contains(p.X, p.Y))
return output;
bounds.Y += m_rowSpacing;
}
return null;
}
private ElementTypeInfo GetElementTypeInfo(TElement element, Graphics g)
{
// look it up in the cache
ICircuitElementType type = element.Type;
ElementTypeInfo cachedInfo;
if (m_elementTypeCache.TryGetValue(type, out cachedInfo))
return cachedInfo;
// not in cache, recompute
ElementSizeInfo sizeInfo = GetElementSizeInfo(type, g);
ElementTypeInfo info = new ElementTypeInfo
{
Size = sizeInfo.Size,
Interior = sizeInfo.Interior,
OutputLeftX = sizeInfo.OutputLeftX.ToArray()
};
m_elementTypeCache.Add(type, info);
return info;
}
/// <summary>
/// Computes interior and exterior size as well as the X positions of output pins</summary>
/// <param name="type">Circuit element type</param>
/// <param name="g">Graphics that can be used for measuring strings</param>
/// <returns>Element size info, must not be null</returns>
/// <remarks>Clients using customized rendering should override this method
/// to adjust sizes accordingly. These sizes will be used by drag-fram picking.</remarks>
protected virtual ElementSizeInfo GetElementSizeInfo(ICircuitElementType type, Graphics g)
{
SizeF typeNameSize = g.MeasureString(type.Name, m_theme.Font);
int width = (int)typeNameSize.Width + 2 * PinMargin;
IList<ICircuitPin> inputPins = type.Inputs;
IList<ICircuitPin> outputPins = type.Outputs;
int inputCount = inputPins.Count;
int outputCount = outputPins.Count;
int minRows = Math.Min(inputCount, outputCount);
int maxRows = Math.Max(inputCount, outputCount);
int[] outputLeftX = new int[outputCount];
int height = m_rowSpacing + 2 * PinMargin;
height += Math.Max(
maxRows * m_rowSpacing,
minRows * m_rowSpacing + type.InteriorSize.Height - PinMargin);
bool imageRight = true;
for (int i = 0; i < maxRows; i++)
{
double rowWidth = 2 * PinMargin;
if (inputCount > i)
{
SizeF labelSize = g.MeasureString(inputPins[i].Name, m_theme.Font);
rowWidth += labelSize.Width + m_pinSize + PinMargin;
}
else
{
rowWidth += type.InteriorSize.Width;
imageRight = false;
}
if (outputCount > i)
{
SizeF labelSize = g.MeasureString(outputPins[i].Name, m_theme.Font);
outputLeftX[i] = (int)labelSize.Width;
rowWidth += labelSize.Width + m_pinSize + PinMargin;
}
else
{
rowWidth += type.InteriorSize.Width;
}
width = Math.Max(width, (int)rowWidth);
}
if (inputCount == outputCount)
width = Math.Max(width, type.InteriorSize.Width + 2);
width = Math.Max(width, MinElementWidth);
height = Math.Max(height, MinElementHeight);
Size size = new Size(width, height);
Rectangle interior = new Rectangle(
imageRight ? width - type.InteriorSize.Width : 1,
height - type.InteriorSize.Height,
type.InteriorSize.Width,
type.InteriorSize.Height);
for (int i = 0; i < outputLeftX.Length; i++)
outputLeftX[i] = width - PinMargin - m_pinSize - outputLeftX[i];
return new ElementSizeInfo(size, interior, outputLeftX);
}
private void DisposeElementInfo()
{
foreach (ElementTypeInfo info in m_elementTypeCache.Values)
{
if (info.Path != null)
info.Path.Dispose();
}
}
private void BuildGraphics(ICircuitElementType elementType, ElementTypeInfo info, Graphics g)
{
int width = info.Size.Width;
int height = info.Size.Height;
// create rounded corner rect
GraphicsPath gp = new GraphicsPath();
const float r = 6;
const float d = 2 * r;
gp.AddLine(r, 0, width - d, 0);
gp.AddArc(width - d, 0, d, d, 270, 90);
gp.AddLine(width, r, width, height - d);
gp.AddArc(width - d, height - d, d, d, 0, 90);
gp.AddLine(width - d, height, r, height);
gp.AddArc(0, height - d, d, d, 90, 90);
gp.AddLine(0, height - d, 0, r);
gp.AddArc(0, 0, d, d, 180, 90);
info.Path = gp;
}
private void DrawWire(
TElement outputElement,
TPin outputPin,
TElement inputElement,
TPin inputPin,
Graphics g,
Pen pen)
{
ElementTypeInfo info = GetElementTypeInfo(outputElement, g);
Point op = outputElement.Bounds.Location;
int x1 = op.X + info.Size.Width;
int y1 = op.Y + GetPinOffset(outputPin.Index);
Point ip = inputElement.Bounds.Location;
int x2 = ip.X;
int y2 = ip.Y + GetPinOffset(inputPin.Index);
DrawWire(g, pen, x1, y1, x2, y2);
}
private void DrawWire(
TElement element,
TPin pin,
Point p,
bool fromOutput,
Graphics g)
{
ElementTypeInfo info = GetElementTypeInfo(element, g);
Point ep = element.Bounds.Location;
int x = ep.X;
int y = ep.Y + GetPinOffset(pin.Index);
if (fromOutput)
x += info.Size.Width;
Matrix inverse = g.Transform;
inverse.Invert();
Point end = GdiUtil.Transform(inverse, p);
Pen pen = GetPen(pin);
if (fromOutput)
DrawWire(g, pen, x, y, end.X, end.Y);
else
DrawWire(g, pen, end.X, end.Y, x, y);
}
private void DrawWire(Graphics g, Pen pen, int x1, int y1, int x2, int y2)
{
int tanLen = GetTangentLength(x1, x2);
try
{
g.DrawBezier(
pen,
new Point(x1, y1),
new Point(x1 + tanLen, y1),
new Point(x2 - tanLen, y2),
new Point(x2, y2));
}
catch (System.OutOfMemoryException ex)
{
// let it go, only missing some pixels
// see http://msdn2.microsoft.com/en-us/library/Graphics.drawarc.aspx
Outputs.WriteLine(OutputMessageType.Warning, ex.Message);
}
}
private int GetTangentLength(int x1, int x2)
{
const int minTanLen = 32;
int tanLen = Math.Abs(x1 - x2) / 2;
tanLen = Math.Max(tanLen, minTanLen);
return tanLen;
}
private Pen GetPen(TPin pin)
{
Pen pen = m_theme.GetCustomPen(pin.TypeName);
if (pen == null)
pen = m_theme.GhostPen;
return pen;
}
private int GetPinOffset(int index)
{
return m_rowSpacing + 2 * PinMargin + index * m_rowSpacing + m_pinOffset + m_pinSize / 2;
}
private void SetPinSpacing()
{
int fontHeight = m_theme.Font.Height;
m_rowSpacing = fontHeight + PinMargin;
m_pinOffset = (fontHeight - m_pinSize) / 2;
}
private Rectangle GetElementBounds(TElement element, Graphics g)
{
ElementTypeInfo info = GetElementTypeInfo(element, g);
return new Rectangle(element.Bounds.Location, info.Size);
}
#region Private Classes
/// <summary>
/// Class to hold cached element type layout</summary>
private class ElementTypeInfo
{
public Size Size;
public Rectangle Interior;
public int[] OutputLeftX;
public GraphicsPath Path; // built by DrawElement
}
/// <summary>
/// Size info for a CircuitElement Type</summary>
public class ElementSizeInfo
{
/// <summary>
/// Constructor with parameters</summary>
/// <param name="size">Size</param>
/// <param name="interior">Interior size</param>
/// <param name="outputLeftX">Horizontal offset of output pins in pixels</param>
public ElementSizeInfo(Size size, Rectangle interior, IEnumerable<int> outputLeftX)
{
m_size = size;
m_interior = interior;
m_outputLeftX = outputLeftX;
}
/// <summary>
/// Gets the size in pixels</summary>
public Size Size { get { return m_size; } }
/// <summary>
/// Gets the interior rectangle</summary>
public Rectangle Interior { get { return m_interior; } }
/// <summary>
/// Gets the horizontal offset of output pins in pixels</summary>
public IEnumerable<int> OutputLeftX { get { return m_outputLeftX; } }
private readonly Size m_size;
private readonly Rectangle m_interior;
private readonly IEnumerable<int> m_outputLeftX;
}
#endregion
private DiagramTheme m_theme;
private int m_rowSpacing;
private int m_pinSize = 8;
private int m_pinOffset;
private readonly Dictionary<ICircuitElementType, ElementTypeInfo> m_elementTypeCache =
new Dictionary<ICircuitElementType, ElementTypeInfo>();
private const int PinMargin = 2;
private const int MinElementWidth = 4;
private const int MinElementHeight = 4;
private const int HighlightingWidth = 3;
private const int MaxNameOverhang = 64;
private static readonly Matrix s_pathTransform = new Matrix();
}
} | 38.594452 | 133 | 0.517525 | [
"Apache-2.0"
] | HaKDMoDz/ATF | Framework/Atf.Gui.WinForms/Controls/Adaptable/Graphs/CircuitRenderer.cs | 28,463 | C# |
namespace p04._03.FindEvensOrOdds
{
using System;
using System.Collections.Generic;
using System.Linq;
class FindEvensOrOdds
{
static void Main(string[] args)
{
int[] numbers = Console.ReadLine()
.Split(' ',
StringSplitOptions
.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
string command = Console.ReadLine();
int startNum = numbers[0];
int endNum = numbers[1];
Predicate<int> predicate = TakeCondition(command);
Queue<int> result = new Queue<int>();
for (int i = startNum; i <= endNum; i++)
{
if (predicate(i))
{
result.Enqueue(i);
}
}
Console.WriteLine(string.Join(" ", result));
}
static Predicate<int> TakeCondition(string command)
{
if (command == "odd")
{
return x => x % 2 != 0;
}
else
{
return x => x % 2 == 0;
}
}
}
} | 24.428571 | 62 | 0.423559 | [
"MIT"
] | vesy53/SoftUni | C# Advanced/C#Adanced/LabEndExercises/10.01.FunctionalProgrammingExercises/p04.03.FindEvensOrOdds/FindEvensOrOdds.cs | 1,199 | C# |
using CommunityToolkit.Maui.Markup;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;
using RockPaperScissors.Extensions;
using RockPaperScissors.ViewModels;
using static CommunityToolkit.Maui.Markup.GridRowsColumns;
namespace RockPaperScissors.Views.Game
{
public class PlayGroundView : ContentView
{
private enum Column { Player, Middle, Enemy }
public PlayGroundView()
{
Content = new Grid
{
BackgroundColor = Color.FromArgb("06BEE1"),
ColumnDefinitions = Columns.Define(
(Column.Player, Star),
(Column.Middle, Star),
(Column.Enemy, Star)),
Children = {
new Image()
.SetCentered100pxImage()
.Column(Column.Player)
.Bind(Image.SourceProperty, nameof(PlayGroundViewModel.PlayerImage), BindingMode.TwoWay),
new Image()
.SetCentered100pxImage()
.Column(Column.Middle)
.Bind(Image.SourceProperty, nameof(PlayGroundViewModel.MiddleImage), BindingMode.TwoWay),
new Image()
.SetCentered100pxImage()
.Column(Column.Enemy)
.Bind(Image.SourceProperty, nameof(PlayGroundViewModel.EnemyImage), BindingMode.TwoWay),
}
};
}
}
}
| 35.97561 | 109 | 0.558644 | [
"MIT"
] | Gramli/maui-samples | src/RockPaperScissors/RockPaperScissors/Views/Game/PlayGroundView.cs | 1,477 | C# |
namespace FluentData
{
public partial class DbContext : IDbContext
{
public DbContextData Data { get; private set; }
public DbContext()
{
Data = new DbContextData();
}
internal void CloseSharedConnection()
{
if (Data.Connection == null)
return;
if (Data.UseTransaction
&& Data.Transaction != null)
Rollback();
Data.Connection.Close();
if (Data.OnConnectionClosed != null)
Data.OnConnectionClosed(new ConnectionEventArgs(Data.Connection));
}
public void Dispose()
{
CloseSharedConnection();
}
}
}
| 17 | 70 | 0.670232 | [
"MIT"
] | shuaiagain/orm-fluentdata | FluentData/sourceCode/sourceCode/Source/Main/FluentData/Context/DbContext.cs | 563 | C# |
using UnityEngine;
using System.Collections;
// this script was found on stackoverflow and slighty modified
//
// it realizes the upward drifting score display
[RequireComponent(typeof(TextMesh))]
public class RisingText : MonoBehaviour
{
// private variables:
Vector3 crds_delta;
float alpha;
float life_loss;
Camera cam;
// public variables - you can change this in Inspector if you need to
public Color color = Color.white;
// SETUP - call this once after having created the object, to make it
// "points" shows the points.
// "duration" is the lifespan of the object
// "rise speed" is how fast it will rise over time.
public void setup(int points, float duration, float rise_speed)
{
GetComponent<TextMesh>().text = points.ToString();
life_loss = 1f / duration;
crds_delta = new Vector3(0f, rise_speed, 0f);
}
void Start() // some default values. You still need to call "setup"
{
alpha = 1f;
cam = GameObject.Find("Main Camera").GetComponent<Camera>();
crds_delta = new Vector3(0f, 1f, 0f);
life_loss = 0.5f;
}
void Update ()
{
// move upwards :
transform.Translate(crds_delta * Time.deltaTime, Space.World);
// change alpha :
alpha -= Time.deltaTime * life_loss;
renderer.material.color = new Color(color.r,color.g,color.b,alpha);
// if completely faded out, die:
if (alpha <= 0f) Destroy(gameObject);
// make it face the camera:
transform.LookAt(cam.transform.position);
transform.rotation = cam.transform.rotation;
}
} | 27.836364 | 71 | 0.693011 | [
"MIT"
] | martinkro/tutorials-unity3d | BowArrow/Assets/bowandarrow/Scripts/RisingText.cs | 1,533 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osu.Game.Input.Bindings;
using osu.Game.Screens;
namespace osu.Game.Skinning.Editor
{
/// <summary>
/// A container which handles loading a skin editor on user request for a specified target.
/// This also handles the scaling / positioning adjustment of the target.
/// </summary>
public class SkinEditorOverlay : OverlayContainer, IKeyBindingHandler<GlobalAction>
{
private readonly ScalingContainer scalingContainer;
protected override bool BlockNonPositionalInput => true;
[CanBeNull]
private SkinEditor skinEditor;
[Resolved(canBeNull: true)]
private OsuGame game { get; set; }
private OsuScreen lastTargetScreen;
public SkinEditorOverlay(ScalingContainer scalingContainer)
{
this.scalingContainer = scalingContainer;
RelativeSizeAxes = Axes.Both;
}
public bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
switch (e.Action)
{
case GlobalAction.Back:
if (skinEditor?.State.Value != Visibility.Visible)
break;
Hide();
return true;
}
return false;
}
protected override void PopIn()
{
if (skinEditor != null)
{
skinEditor.Show();
return;
}
var editor = new SkinEditor();
editor.State.BindValueChanged(visibility => updateComponentVisibility());
skinEditor = editor;
LoadComponentAsync(editor, _ =>
{
if (editor != skinEditor)
return;
AddInternal(editor);
SetTarget(lastTargetScreen);
});
}
protected override void PopOut() => skinEditor?.Hide();
private void updateComponentVisibility()
{
Debug.Assert(skinEditor != null);
const float toolbar_padding_requirement = 0.18f;
if (skinEditor.State.Value == Visibility.Visible)
{
scalingContainer.SetCustomRect(new RectangleF(toolbar_padding_requirement, 0.2f, 0.8f - toolbar_padding_requirement, 0.7f), true);
game?.Toolbar.Hide();
game?.CloseAllOverlays();
}
else
{
scalingContainer.SetCustomRect(null);
if (lastTargetScreen?.HideOverlaysOnEnter != true)
game?.Toolbar.Show();
}
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
}
/// <summary>
/// Set a new target screen which will be used to find skinnable components.
/// </summary>
public void SetTarget(OsuScreen screen)
{
lastTargetScreen = screen;
if (skinEditor == null) return;
skinEditor.Save();
// ensure the toolbar is re-hidden even if a new screen decides to try and show it.
updateComponentVisibility();
// AddOnce with parameter will ensure the newest target is loaded if there is any overlap.
Scheduler.AddOnce(setTarget, screen);
}
private void setTarget(OsuScreen target)
{
Debug.Assert(skinEditor != null);
if (!target.IsLoaded)
{
Scheduler.AddOnce(setTarget, target);
return;
}
if (skinEditor.State.Value == Visibility.Visible)
skinEditor.UpdateTargetScreen(target);
else
{
skinEditor.Hide();
skinEditor.Expire();
skinEditor = null;
}
}
}
}
| 29.919463 | 147 | 0.550247 | [
"MIT"
] | Awesome-Of-the-Internet/osu | osu.Game/Skinning/Editor/SkinEditorOverlay.cs | 4,310 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Threading;
using osu.Framework.Utils;
using osu.Game.Graphics.Containers;
using osu.Game.Overlays;
using osuTK;
namespace osu.Game.Beatmaps.Drawables.Cards
{
public class BeatmapCardContent : CompositeDrawable
{
public Drawable MainContent
{
set => bodyContent.Child = value;
}
public Drawable ExpandedContent
{
set => dropdownScroll.Child = value;
}
public IBindable<bool> Expanded => expanded;
private readonly BindableBool expanded = new BindableBool();
private readonly Box background;
private readonly Container content;
private readonly Container bodyContent;
private readonly Container dropdownContent;
private readonly OsuScrollContainer dropdownScroll;
private readonly Container borderContainer;
public BeatmapCardContent(float height)
{
RelativeSizeAxes = Axes.X;
Height = height;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
InternalChild = content = new HoverHandlingContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
CornerRadius = BeatmapCard.CORNER_RADIUS,
Masking = true,
Unhovered = _ => updateFromHoverChange(),
Children = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both
},
bodyContent = new Container
{
RelativeSizeAxes = Axes.X,
Height = height,
CornerRadius = BeatmapCard.CORNER_RADIUS,
Masking = true,
},
dropdownContent = new HoverHandlingContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Margin = new MarginPadding { Top = height },
Alpha = 0,
Hovered = _ =>
{
updateFromHoverChange();
return true;
},
Unhovered = _ => updateFromHoverChange(),
Child = dropdownScroll = new ExpandedContentScrollContainer
{
RelativeSizeAxes = Axes.X,
ScrollbarVisible = false
}
},
borderContainer = new Container
{
RelativeSizeAxes = Axes.Both,
CornerRadius = BeatmapCard.CORNER_RADIUS,
Masking = true,
BorderThickness = 3,
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
AlwaysPresent = true
}
}
}
};
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
background.Colour = colourProvider.Background2;
borderContainer.BorderColour = colourProvider.Highlight1;
}
protected override void LoadComplete()
{
base.LoadComplete();
Expanded.BindValueChanged(_ => updateState(), true);
FinishTransforms(true);
}
private ScheduledDelegate? scheduledExpandedChange;
public void ExpandAfterDelay() => queueExpandedStateChange(true, 100);
public void CancelExpand() => scheduledExpandedChange?.Cancel();
private void updateFromHoverChange() =>
queueExpandedStateChange(content.IsHovered || dropdownContent.IsHovered, 100);
private void queueExpandedStateChange(bool newState, int delay = 0)
{
if (Expanded.Disabled)
return;
scheduledExpandedChange?.Cancel();
scheduledExpandedChange = Scheduler.AddDelayed(() => expanded.Value = newState, delay);
}
private void updateState()
{
// Scale value is intentionally chosen to fit in the spacing of listing displays, as to not overlap horizontally with adjacent cards.
// This avoids depth issues where a hovered (scaled) card to the right of another card would be beneath the card to the left.
this.ScaleTo(Expanded.Value ? 1.03f : 1, 500, Easing.OutQuint);
background.FadeTo(Expanded.Value ? 1 : 0, BeatmapCard.TRANSITION_DURATION, Easing.OutQuint);
dropdownContent.FadeTo(Expanded.Value ? 1 : 0, BeatmapCard.TRANSITION_DURATION, Easing.OutQuint);
borderContainer.FadeTo(Expanded.Value ? 1 : 0, BeatmapCard.TRANSITION_DURATION, Easing.OutQuint);
content.TweenEdgeEffectTo(new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Offset = new Vector2(0, 2),
Radius = 10,
Colour = Colour4.Black.Opacity(Expanded.Value ? 0.3f : 0f),
Hollow = true,
}, BeatmapCard.TRANSITION_DURATION, Easing.OutQuint);
}
private class ExpandedContentScrollContainer : OsuScrollContainer
{
public ExpandedContentScrollContainer()
{
ScrollbarVisible = false;
}
protected override void Update()
{
base.Update();
Height = Math.Min(Content.DrawHeight, 400);
}
private bool allowScroll => !Precision.AlmostEquals(DrawSize, Content.DrawSize);
protected override bool OnDragStart(DragStartEvent e)
{
if (!allowScroll)
return false;
return base.OnDragStart(e);
}
protected override void OnDrag(DragEvent e)
{
if (!allowScroll)
return;
base.OnDrag(e);
}
protected override void OnDragEnd(DragEndEvent e)
{
if (!allowScroll)
return;
base.OnDragEnd(e);
}
protected override bool OnScroll(ScrollEvent e)
{
if (!allowScroll)
return false;
return base.OnScroll(e);
}
}
}
}
| 35.166667 | 146 | 0.514827 | [
"MIT"
] | ArniDagur/osu | osu.Game/Beatmaps/Drawables/Cards/BeatmapCardContent.cs | 7,176 | C# |
using BlazorComponent;
using Microsoft.AspNetCore.Components;
namespace MASA.Blazor
{
public partial class MButtonGroup : MItemGroup
{
public MButtonGroup() : base(GroupType.ButtonGroup)
{
}
[Parameter]
public bool Borderless { get; set; }
[Parameter]
public bool Dense { get; set; }
[Parameter]
public bool Group { get; set; }
[Parameter]
public bool Rounded { get; set; }
[Parameter]
public bool Shaped { get; set; }
[Parameter]
public bool Tile { get; set; }
[Parameter]
public string BackgroundColor { get; set; }
[Parameter]
public string Color { get; set; }
protected override void SetComponentClass()
{
base.SetComponentClass();
CssProvider
.Merge(cssBuilder =>
{
cssBuilder
.Add("m-btn-toggle")
.AddIf("m-btn-toggle--borderless", () => Borderless)
.AddIf("m-btn-toggle--dense", () => Dense)
.AddIf("m-btn-toggle--group", () => Group)
.AddIf("m-btn-toggle--rounded", () => Rounded)
.AddIf("m-btn-toggle--shaped", () => Shaped)
.AddIf("m-btn-toggle--tile", () => Tile)
.AddTextColor(Color)
.AddBackgroundColor(BackgroundColor, () => !Group);
});
}
}
}
| 27.473684 | 76 | 0.474457 | [
"MIT"
] | BlazorComponent/MASA.Blazor | src/MASA.Blazor/Components/ItemGroup/MButtonGroup.cs | 1,568 | C# |
/******************************************************************************
* Gear: An open-world sandbox game for creative people. *
* http://github.com/cathode/gear/ *
* Copyright © 2009-2017 William 'cathode' Shelley. All Rights Reserved. *
* This software is released under the terms and conditions of the MIT *
* license. See the included LICENSE file for details. *
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProtoBuf;
namespace Gear.Net.Messages
{
/// <summary>
/// Represents a greeting sent to a peer. The receiving side should reply with a greeting message.
/// </summary>
[ProtoContract]
public class PeerGreetingMessage : IMessage
{
[ProtoIgnore]
int IMessage.DispatchId
{
get
{
return BuiltinMessageIds.PeerGreeting;
}
}
[ProtoMember(1)]
public PeerMetadata Metadata { get; set; }
[ProtoMember(2)]
public bool IsResponseRequested { get; set; }
}
}
| 32.717949 | 102 | 0.513323 | [
"MIT"
] | cathode/gear | Gear.Net/Messages/PeerGreetingMessage.cs | 1,279 | 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("04.Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mobiltel")]
[assembly: AssemblyProduct("04.Demo")]
[assembly: AssemblyCopyright("Copyright © Mobiltel 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("d7f9e4cb-d70f-414f-b67f-52f9f8eb111d")]
// 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.918919 | 84 | 0.744833 | [
"MIT"
] | tpulkov/CSharp-Part2 | Lections-Demo-Live/03.Methods and 04.Numeral Systems/04.Demo/Properties/AssemblyInfo.cs | 1,406 | C# |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
namespace RuneCircleGenerator
{
public class Generator : IDisposable
{
private const int _textureSize = 1024;
private const int _symbolCount = 20;
private static readonly float _penWidth = _textureSize * 0.016f;
private static readonly float _fontSize = _textureSize * 0.065f;
private static Color _greenColor = Color.FromArgb( 255, 156, 255, 134 );
private SolidBrush _transparentBrush = new SolidBrush( Color.Transparent );
private Pen _greenPen = new Pen( _greenColor, _penWidth );
private SolidBrush _greenBrush = new SolidBrush( _greenColor );
public Image GenerateRuneCircle()
{
var bitmap = new Bitmap( _textureSize, _textureSize );
using ( var g = Graphics.FromImage( bitmap ) )
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
FillWithTransparency( g );
RenderRings( g );
RenderSymbols( g );
}
return bitmap;
}
private void RenderSymbols( Graphics g )
{
float radius = _textureSize / 2 * 0.84f;
float centerX = _textureSize / 2;
float centerY = _textureSize / 2;
var symbols = GetSymbols();
using ( var font = new Font( "Meroitic - Hieroglyphics", _fontSize, FontStyle.Bold ) )
{
for ( int index = 0; index < _symbolCount; index++ )
{
char character = symbols[index];
float arc = 360f / _symbolCount;
float thetaDegrees = arc * index;
float thetaRadians = AsRadians( thetaDegrees );
var characterSize = MeasureCharacter( g, font, character );
var centerPoint = new PointF( centerX - characterSize.Width / 2, centerY - characterSize.Height / 2 );
float x = centerX + (float) Math.Cos( thetaRadians ) * radius;
float y = centerY + (float) Math.Sin( thetaRadians ) * radius;
g.TranslateTransform( x, y );
g.RotateTransform( thetaDegrees + 90 );
g.TranslateTransform( -x, -y );
g.TranslateTransform( -( characterSize.Width / 2 ), -( characterSize.Height / 2 ) );
g.DrawString( character.ToString(), font, _greenBrush, x, y );
g.ResetTransform();
}
}
}
private static char[] GetSymbols()
{
return new[]
{
'A', // 1
'B',
'C',
'D',
'E', // 5
'G',
'I',
'J',
'K',
'L', // 10
'M',
'N',
'O',
'P',
'Q', // 15
'R',
'T',
'U',
'W',
'Y', // 20
};
}
private float AsRadians( float theta )
=> theta * (float) Math.PI / 180f;
private SizeF MeasureCharacter( Graphics g, Font font, char c )
=> g.MeasureString( c.ToString(), font );
private void RenderRings( Graphics g )
{
float outerMargin = _textureSize * 0.02f;
float innerMargin = _textureSize * 0.14f;
g.DrawEllipse( _greenPen, outerMargin, outerMargin, _textureSize - outerMargin * 2, _textureSize - outerMargin * 2 );
g.DrawEllipse( _greenPen, innerMargin, innerMargin, _textureSize - innerMargin * 2, _textureSize - innerMargin * 2 );
}
private void FillWithTransparency( Graphics g )
=> g.FillRectangle( _transparentBrush, 0, 0, _textureSize, _textureSize );
#region IDisposable members
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
private void Dispose( bool disposing )
{
if ( disposing )
{
_transparentBrush?.Dispose();
_greenPen?.Dispose();
_greenBrush?.Dispose();
}
}
#endregion
}
}
| 30.05036 | 126 | 0.539143 | [
"MIT"
] | alexwnovak/TF2Maps | jump_mirage/src/RuneCircleGenerator/RuneCircleGenerator/Generator.cs | 4,179 | C# |
namespace Vodamep.ReportBase
{
public interface INamedPerson : IPerson
{
string FamilyName { get; }
string GivenName { get; }
}
} | 19.75 | 43 | 0.613924 | [
"MIT"
] | connexiadev/Vodamep | src/Vodamep/ReportBase/INamedPerson.cs | 160 | C# |
using System.Diagnostics;
using AppName.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace AppName.Web.Controllers
{
[AllowAnonymous]
public class HomeController : Controller
{
private readonly IOptions<AppSettings> _appSettings;
public HomeController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings;
}
public IActionResult Index()
{
ViewData["Title"] = _appSettings.Value.Application.AppName;
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
public IActionResult Random()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 23.929825 | 112 | 0.58871 | [
"MIT"
] | ryanrodemoyer/AppNameWeb | src/presentation/AppName.Web/Controllers/HomeController.cs | 1,366 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQ(object o)
{
return Helper.Compare((GCHandle)o, Helper.Create(default(GCHandle)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((GCHandle?)o, Helper.Create(default(GCHandle)));
}
private static int Main()
{
GCHandle? s = Helper.Create(default(GCHandle));
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| 24.366667 | 78 | 0.659371 | [
"MIT"
] | belav/runtime | src/tests/JIT/jit64/valuetypes/nullable/box-unbox/box-unbox/box-unbox017.cs | 731 | C# |
using Newtonsoft.Json;
using VkApi.Wrapper.Objects;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace VkApi.Wrapper.Responses
{
public class GroupsGetCallbackServersResponse
{
[JsonProperty("count")]
public int Count { get; set; }
[JsonProperty("items")]
public GroupsCallbackServer[] Items { get; set; }
}
} | 25.117647 | 57 | 0.709602 | [
"MIT"
] | FrediKats/VkLibrary | VkApi.Wrapper/Responses/Groups/GroupsGetCallbackServersResponse.cs | 427 | C# |
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace GZ_SpotGate.Core
{
class MyConsole
{
private static MyConsole _output;
private static readonly ILog log4 = log4net.LogManager.GetLogger("MyConsole");
private static object _sync = new object();
public static MyConsole Current
{
get
{
if (_output == null)
{
lock (_sync)
{
if (_output == null)
{
_output = new MyConsole();
}
}
}
return _output;
}
}
private MyConsole()
{
}
private TextBox _textbox;
public void Init(TextBox textbox)
{
_textbox = textbox;
}
private string prefix
{
get
{
return DateTime.Now.HMS() + "->";
}
}
public void Log(string log)
{
Log(new[] { log });
}
public void Log(string[] lines)
{
try
{
var sb = new StringBuilder();
foreach (var line in lines)
{
log4.Debug(line);
sb.Append(prefix + line + "\r");
}
//lock (_sync)
//{
Application.Current.Dispatcher.Invoke(() =>
{
if (_textbox.LineCount >= 500)
{
_textbox.Clear();
}
_textbox.AppendText(sb.ToString());
_textbox.ScrollToEnd();
});
//};
}
catch (Exception ex)
{
var str = "";
}
}
}
}
| 23.755556 | 86 | 0.381197 | [
"MIT"
] | ysjr-2002/GZ-SpotGate | GZ-SpotGate/Core/MyConsole.cs | 2,140 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Web.WebPages.OAuth;
using Ko.PoC.Web.Models;
namespace Ko.PoC.Web
{
public static class AuthConfig
{
public static void RegisterAuth()
{
// To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
// you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166
//OAuthWebSecurity.RegisterMicrosoftClient(
// clientId: "",
// clientSecret: "");
//OAuthWebSecurity.RegisterTwitterClient(
// consumerKey: "",
// consumerSecret: "");
//OAuthWebSecurity.RegisterFacebookClient(
// appId: "",
// appSecret: "");
//OAuthWebSecurity.RegisterGoogleClient();
}
}
}
| 28.969697 | 127 | 0.596234 | [
"MIT"
] | chualuoi/KnockoutMVC | Ko.PoC.Web old/App_Start/AuthConfig.cs | 958 | C# |
using System;
using System.Text;
namespace LinqToDB.DataProvider.Informix
{
using Mapping;
using SqlQuery;
public class InformixMappingSchema : MappingSchema
{
static readonly char[] _extraEscapes = { '\r', '\n' };
public InformixMappingSchema() : this(ProviderName.Informix)
{
}
protected InformixMappingSchema(string configuration) : base(configuration)
{
ColumnNameComparer = StringComparer.OrdinalIgnoreCase;
SetValueToSqlConverter(typeof(bool), (sb,dt,v) => sb.Append("'").Append((bool)v ? 't' : 'f').Append("'"));
SetDataType(typeof(string), new SqlDataType(DataType.NVarChar, typeof(string), 255));
SetValueToSqlConverter(typeof(String), (sb,dt,v) => ConvertStringToSql (sb, v.ToString()));
SetValueToSqlConverter(typeof(Char), (sb,dt,v) => ConvertCharToSql (sb, (char)v));
SetValueToSqlConverter(typeof(DateTime), (sb,dt,v) => ConvertDateTimeToSql(sb, dt, (DateTime)v));
}
static void AppendConversion(StringBuilder stringBuilder, int value)
{
// chr works with values in 0..255 range, bigger/smaller values will be converted to byte
// this is fine as long as we don't have out-of-range characters in _extraEscapes
stringBuilder
.Append("chr(")
.Append(value)
.Append(")")
;
}
static void ConvertStringToSql(StringBuilder stringBuilder, string value)
{
DataTools.ConvertStringToSql(stringBuilder, "||", null, AppendConversion, value, _extraEscapes);
}
static void ConvertCharToSql(StringBuilder stringBuilder, char value)
{
switch (value)
{
case '\r':
case '\n':
AppendConversion(stringBuilder, value);
break;
default:
DataTools.ConvertCharToSql(stringBuilder, "'", AppendConversion, value);
break;
}
}
static void ConvertDateTimeToSql(StringBuilder stringBuilder, SqlDataType dataType, DateTime value)
{
string format;
if (value.Millisecond != 0)
format = "TO_DATE('{0:yyyy-MM-dd HH:mm:ss.fffff}', '%Y-%m-%d %H:%M:%S.%F5')";
else
format = value.Hour == 0 && value.Minute == 0 && value.Second == 0
? "TO_DATE('{0:yyyy-MM-dd}', '%Y-%m-%d')"
: "TO_DATE('{0:yyyy-MM-dd HH:mm:ss}', '%Y-%m-%d %H:%M:%S')";
stringBuilder.AppendFormat(format, value);
}
}
}
| 30.893333 | 110 | 0.655589 | [
"MIT"
] | Arithmomaniac/linq2db | Source/LinqToDB/DataProvider/Informix/InformixMappingSchema.cs | 2,319 | C# |
//
// Mono.VisualC.Interop.CppInstancePtr.cs: Represents a pointer to a native C++ instance
//
// Author:
// Alexander Corrado (alexander.corrado@gmail.com)
// Andreia Gaita (shana@spoiledcat.net)
//
// Copyright (C) 2010 Alexander Corrado
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Mono.VisualC.Interop.ABI;
namespace Mono.VisualC.Interop {
public struct CppInstancePtr : ICppObject {
private IntPtr ptr;
private bool manage_memory;
private static Dictionary<Type,object> implCache = null;
// TODO: the managed instance argument may only be NULL if all methods in TWrapper
// that correspond to the virtual methods in Iface are static.
public static CppInstancePtr ForManagedObject<Iface,TWrapper> (TWrapper managed)
where Iface : ICppClassOverridable<TWrapper>
{
object cachedImpl;
Iface impl;
if (implCache == null)
implCache = new Dictionary<Type,object> ();
if (!implCache.TryGetValue (typeof (Iface), out cachedImpl))
{
VirtualOnlyAbi virtualABI = new VirtualOnlyAbi (VTable.BindToSignature);
impl = virtualABI.ImplementClass<Iface> (typeof (TWrapper), new CppLibrary (string.Empty), string.Empty);
implCache.Add (typeof (Iface), impl);
}
else
impl = (Iface)cachedImpl;
CppInstancePtr instance = impl.Alloc (managed);
impl.TypeInfo.VTable.InitInstance ((IntPtr)instance);
return instance;
}
// Alloc a new C++ instance
internal CppInstancePtr (int nativeSize, object managedWrapper)
{
// Under the hood, we're secretly subclassing this C++ class to store a
// handle to the managed wrapper.
int allocSize = nativeSize + Marshal.SizeOf (typeof (IntPtr));
ptr = Marshal.AllocHGlobal (allocSize);
// zero memory for sanity
byte[] zeroArray = new byte [allocSize];
Marshal.Copy (zeroArray, 0, ptr, allocSize);
IntPtr handlePtr = GetGCHandle (managedWrapper);
Marshal.WriteIntPtr (ptr, nativeSize, handlePtr);
manage_memory = true;
}
// Alloc a new C++ instance when there is no managed wrapper.
public CppInstancePtr (int nativeSize)
{
ptr = Marshal.AllocHGlobal (nativeSize);
manage_memory = true;
}
// Get a CppInstancePtr for an existing C++ instance from an IntPtr
public CppInstancePtr (IntPtr native)
{
if (native == IntPtr.Zero)
throw new ArgumentOutOfRangeException ("native cannot be null pointer");
ptr = native;
manage_memory = false;
}
// Provide casts to/from IntPtr:
public static implicit operator CppInstancePtr (IntPtr native)
{
return new CppInstancePtr (native);
}
// cast from CppInstancePtr -> IntPtr is explicit because we lose information
public static explicit operator IntPtr (CppInstancePtr ip)
{
return ip.Native;
}
public IntPtr Native {
get {
if (ptr == IntPtr.Zero)
throw new ObjectDisposedException ("CppInstancePtr");
return ptr;
}
}
CppInstancePtr ICppObject.Native {
get { return this; }
}
public bool IsManagedAlloc {
get { return manage_memory; }
}
internal static IntPtr GetGCHandle (object managedWrapper)
{
// TODO: Dispose() should probably be called at some point on this GCHandle.
GCHandle handle = GCHandle.Alloc (managedWrapper, GCHandleType.Normal);
return GCHandle.ToIntPtr (handle);
}
// WARNING! This method is not safe. DO NOT call
// if we do not KNOW that this instance is managed.
internal static T GetManaged<T> (IntPtr native, int nativeSize) where T : class
{
IntPtr handlePtr = Marshal.ReadIntPtr (native, nativeSize);
GCHandle handle = GCHandle.FromIntPtr (handlePtr);
return handle.Target as T;
}
// TODO: Free GCHandle?
public void Dispose ()
{
if (manage_memory && ptr != IntPtr.Zero)
Marshal.FreeHGlobal (ptr);
ptr = IntPtr.Zero;
manage_memory = false;
}
}
}
| 30.845679 | 109 | 0.723634 | [
"MIT"
] | shana/cppinterop | src/Mono.VisualC.Interop/CppInstancePtr.cs | 4,997 | C# |
using Cake.Core;
using Cake.Core.Annotations;
using System;
using System.Collections.Generic;
namespace Cake.Docker
{
// Contains functionality for working with run command.
partial class DockerAliases
{
/// <summary>
/// Creates a new container using default settings.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="image">The image.</param>
/// <param name="args">The arguments.</param>
/// <param name="command">The command.</param>
[CakeMethodAlias]
public static void DockerRun(this ICakeContext context, string image, string command, params string[] args)
{
DockerRun(context, new DockerContainerRunSettings(), image, command, args);
}
/// <summary>
/// Creates a new container given <paramref name="settings"/>.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="settings">The settings.</param>
/// <param name="image">The image.</param>
/// <param name="args">The arguments.</param>
/// <param name="command">The command.</param>
[CakeMethodAlias]
public static void DockerRun(this ICakeContext context, DockerContainerRunSettings settings, string image, string command, params string[] args)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (string.IsNullOrEmpty(image))
{
throw new ArgumentNullException("image");
}
var runner = new GenericDockerRunner<DockerContainerRunSettings>(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools);
List<string> arguments = new List<string> { image };
if (!string.IsNullOrEmpty(command))
{
arguments.Add(command);
if (args.Length > 0)
{
arguments.AddRange(args);
}
}
runner.Run("run", settings ?? new DockerContainerRunSettings(), arguments.ToArray());
}
}
}
| 37.169492 | 156 | 0.577747 | [
"MIT"
] | KevM/Cake.Docker | src/Cake.Docker/Container/Run/Docker.Aliases.Run.cs | 2,195 | C# |
using System.Collections.Generic;
namespace Yargon.Terms
{
/// <summary>
/// A green term.
/// </summary>
/// <remarks>
/// Green terms are part of the DAG and may only store information about themselves,
/// or information derivable from their descendants.
/// </remarks>
public interface IGreenTerm
{
/// <summary>
/// Gets the descriptor for this term.
/// </summary>
/// <value>The descriptor.</value>
ITermDescriptor Descriptor { get; }
/// <summary>
/// Gets a list of all child terms of this term,
/// both concrete terms and abstract terms.
/// </summary>
/// <value>A list of concrete and abstract child terms.</value>
IReadOnlyList<IGreenTerm> Children { get; }
/// <summary>
/// Gets a list of all abstract child terms of this term.
/// </summary>
/// <value>A list of abstract child terms.</value>
IReadOnlyList<IGreenTerm> AbstractChildren { get; }
/// <summary>
/// Gets the number of input characters that this term describes.
/// </summary>
/// <value>The input width.</value>
int Width { get; }
/// <summary>
/// Constructs a corresponding red term for this term.
/// </summary>
/// <param name="parent">The parent term.</param>
/// <returns>The resulting red term.</returns>
ITerm ConstructTerm(ITerm parent);
}
}
| 31.787234 | 88 | 0.573628 | [
"Apache-2.0"
] | cyberlect/yargon-terms | src/Yargon.Terms/IGreenTerm.cs | 1,496 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using TerraFX.Interop;
using TerraFX.Threading;
using static TerraFX.Interop.Windows;
using static TerraFX.Runtime.Configuration;
using static TerraFX.Threading.VolatileState;
using static TerraFX.Utilities.Win32Utilities;
using static TerraFX.Utilities.AssertionUtilities;
using static TerraFX.Utilities.ExceptionUtilities;
using static TerraFX.Utilities.UnsafeUtilities;
namespace TerraFX.UI
{
/// <summary>Provides access to a Win32 based window subsystem.</summary>
public sealed unsafe class Win32WindowService : WindowService
{
private const string VulkanRequiredExtensionNamesDataName = "TerraFX.Graphics.VulkanGraphicsService.RequiredExtensionNames";
/// <summary>A <c>HINSTANCE</c> to the entry point module.</summary>
public static readonly IntPtr EntryPointModule = GetModuleHandleW(lpModuleName: null);
private readonly ThreadLocal<Dictionary<IntPtr, Win32Window>> _windows;
private ValueLazy<ushort> _classAtom;
private ValueLazy<GCHandle> _nativeHandle;
private VolatileState _state;
/// <summary>Initializes a new instance of the <see cref="Win32WindowService" /> class.</summary>
public Win32WindowService()
{
var vulkanRequiredExtensionNamesDataName = AppContext.GetData(VulkanRequiredExtensionNamesDataName) as string;
vulkanRequiredExtensionNamesDataName += ";VK_KHR_surface;VK_KHR_win32_surface";
AppDomain.CurrentDomain.SetData(VulkanRequiredExtensionNamesDataName, vulkanRequiredExtensionNamesDataName);
_classAtom = new ValueLazy<ushort>(CreateClassAtom);
_nativeHandle = new ValueLazy<GCHandle>(CreateNativeHandle);
_windows = new ThreadLocal<Dictionary<IntPtr, Win32Window>>(trackAllValues: true);
_ = _state.Transition(to: Initialized);
}
/// <summary>Finalizes an instance of the <see cref="Win32WindowService" /> class.</summary>
~Win32WindowService() => Dispose(isDisposing: false);
/// <summary>Gets the <c>ATOM</c> of the <see cref="WNDCLASSEXW" /> registered for the instance.</summary>
public ushort ClassAtom
{
get
{
ThrowIfDisposedOrDisposing(_state, nameof(Win32WindowService));
return _classAtom.Value;
}
}
/// <inheritdoc />
public override DispatchService DispatchService => Win32DispatchService.Instance;
/// <summary>Gets the <see cref="GCHandle" /> containing the native handle for the instance.</summary>
/// <exception cref="ObjectDisposedException">The instance has already been disposed.</exception>
public GCHandle NativeHandle
{
get
{
AssertNotDisposedOrDisposing(_state);
return _nativeHandle.Value;
}
}
/// <inheritdoc />
/// <exception cref="ObjectDisposedException">The instance has already been disposed.</exception>
public override IEnumerable<Window> WindowsForCurrentThread
{
get
{
ThrowIfDisposedOrDisposing(_state, nameof(Win32WindowService));
return _windows.Value?.Values ?? Enumerable.Empty<Win32Window>();
}
}
/// <inheritdoc />
/// <exception cref="ObjectDisposedException">The instance has already been disposed.</exception>
public override Window CreateWindow()
{
ThrowIfDisposedOrDisposing(_state, nameof(Win32WindowService));
return new Win32Window(this);
}
[UnmanagedCallersOnly]
private static nint ForwardWindowMessage(IntPtr hWnd, uint msg, nuint wParam, nint lParam)
{
nint userData;
GCHandle gcHandle;
Win32WindowService windowService;
Dictionary<IntPtr, Win32Window>? windows;
Win32Window? window;
bool forwardMessage;
if (msg == WM_CREATE)
{
// We allow the WM_CREATE message to be forwarded to the Window instance
// for hWnd. This allows some delayed initialization to occur since most
// of the fields in Window are lazy.
var createStruct = (CREATESTRUCTW*)lParam;
userData = (nint)createStruct->lpCreateParams;
// Unlike the WindowService GCHandle, the Window GCHandle is short lived and
// we want to free it after we add the relevant entries to the window map.
gcHandle = GCHandle.FromIntPtr(userData);
{
window = (Win32Window)gcHandle.Target!;
windowService = window.WindowService;
windows = windowService._windows.Value!;
}
gcHandle.Free();
if (windows is null)
{
windows = new Dictionary<IntPtr, Win32Window>(capacity: 4);
windowService._windows.Value = windows;
}
windows.Add(hWnd, window);
// We then want to ensure the window service is registered as a property for fast
// subsequent lookups. This proocess also allows everything to be lazily initialized.
gcHandle = window.WindowService.NativeHandle;
userData = GCHandle.ToIntPtr(gcHandle);
_ = SetWindowLongPtrW(hWnd, GWLP_USERDATA, userData);
forwardMessage = false;
}
else
{
userData = GetWindowLongPtrW(hWnd, GWLP_USERDATA);
if (userData != 0)
{
gcHandle = GCHandle.FromIntPtr(userData);
windowService = (Win32WindowService)gcHandle.Target!;
windows = windowService._windows.Value!;
forwardMessage = windows.TryGetValue(hWnd, out window);
}
else
{
windows = null;
window = null;
forwardMessage = false;
}
}
if (forwardMessage)
{
AssertNotNull(windows);
AssertNotNull(window);
var result = window.ProcessWindowMessage(msg, wParam, lParam);
if (msg == WM_DESTROY)
{
// We forward the WM_DESTROY message to the corresponding Window instance
// so that it can still be properly disposed of in the scenario that the
// hWnd was destroyed externally.
_ = RemoveWindow(windows, hWnd);
}
return result;
}
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
private static Win32Window RemoveWindow(Dictionary<IntPtr, Win32Window> windows, IntPtr hWnd)
{
_ = windows.Remove(hWnd, out var window);
AssertNotNull(window);
if (windows.Count == 0)
{
PostQuitMessage(nExitCode: 0);
}
return window;
}
private static HICON GetDesktopCursor()
{
var desktopWindowHandle = GetDesktopWindow();
var desktopClassName = stackalloc ushort[256]; // 256 is the maximum length of WNDCLASSEX.lpszClassName
ThrowForLastErrorIfZero(GetClassNameW(desktopWindowHandle, desktopClassName, 256), nameof(GetClassNameW));
WNDCLASSEXW desktopWindowClass;
ThrowExternalExceptionIfFalse(GetClassInfoExW(
HINSTANCE.NULL,
lpszClass: desktopClassName,
lpwcx: &desktopWindowClass
), nameof(GetClassInfoExW));
return desktopWindowClass.hCursor;
}
private ushort CreateClassAtom()
{
AssertNotDisposedOrDisposing(_state);
ushort classAtom;
{
// lpszClassName should be less than 256 characters (this includes the null terminator)
// Currently, we are well below this limit and should be hitting 74 characters + the null terminator
var className = $"{GetType().FullName}.{EntryPointModule:X16}.{GetHashCode():X8}";
Assert(AssertionsEnabled && (className.Length < byte.MaxValue));
fixed (char* lpszClassName = className)
{
var wndClassEx = new WNDCLASSEXW {
cbSize = SizeOf<WNDCLASSEXW>(),
style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS,
lpfnWndProc = &ForwardWindowMessage,
cbClsExtra = 0,
cbWndExtra = 0,
hInstance = EntryPointModule,
hIcon = HICON.NULL,
hCursor = GetDesktopCursor(),
hbrBackground = (IntPtr)(COLOR_WINDOW + 1),
lpszMenuName = null,
lpszClassName = (ushort*)lpszClassName,
hIconSm = HICON.NULL
};
classAtom = RegisterClassExW(&wndClassEx);
}
ThrowForLastErrorIfZero(classAtom, nameof(RegisterClassExW));
}
return classAtom;
}
private GCHandle CreateNativeHandle() => GCHandle.Alloc(this, GCHandleType.Normal);
/// <inheritdoc />
protected override void Dispose(bool isDisposing)
{
var priorState = _state.BeginDispose();
if (priorState < Disposing)
{
DisposeWindows(isDisposing);
DisposeClassAtom();
DisposeNativeHandle();
}
_state.EndDispose();
}
private void DisposeClassAtom()
{
AssertDisposing(_state);
if (_classAtom.IsValueCreated)
{
ThrowExternalExceptionIfFalse(UnregisterClassW((ushort*)_classAtom.Value, EntryPointModule), nameof(UnregisterClassW));
}
}
private void DisposeNativeHandle()
{
AssertDisposing(_state);
if (_nativeHandle.IsValueCreated)
{
_nativeHandle.Value.Free();
}
}
private void DisposeWindows(bool isDisposing)
{
AssertDisposing(_state);
if (isDisposing)
{
var threadWindows = _windows.Values;
for (var i = 0; i < threadWindows.Count; i++)
{
var windows = threadWindows[i];
if (windows != null)
{
var hWnds = windows.Keys;
foreach (var hWnd in hWnds)
{
var dispatchService = Win32DispatchService.Instance;
var window = RemoveWindow(windows, hWnd);
window.Dispose();
}
Assert(AssertionsEnabled && (windows.Count == 0));
}
}
_windows.Dispose();
}
}
}
}
| 36.510903 | 145 | 0.5657 | [
"MIT"
] | phizch/terrafx | sources/UI/Win32/UI/Win32WindowService.cs | 11,721 | C# |
using System.Collections.Generic;
using System.Data.SqlClient;
namespace WrappedSqlFileStream
{
public interface IWrappedSqlFileStreamContext
{
SqlConnection Connection { get; }
SqlTransaction Transaction { get; }
string TableName { get; }
string IdentifierName { get; }
string FileStreamProperty { get; }
string FileStreamName { get; }
Dictionary<string,string> Mappings { get; }
void CommitAndDispose();
void RollbackAndDispose();
}
} | 22.916667 | 52 | 0.627273 | [
"MIT"
] | RupertAvery/WrappedSqlFileStream | WrappedSqlFileStream/IWrappedSqlFileStreamContext.cs | 550 | C# |
//
// Auto-generated from generator.cs, do not edit
//
// We keep references to objects, so warning 414 is expected
#pragma warning disable 414
using System;
using System.Drawing;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using UIKit;
using GLKit;
using Metal;
using CoreML;
using MapKit;
using Photos;
using ModelIO;
using SceneKit;
using Contacts;
using Security;
using Messages;
using AudioUnit;
using CoreVideo;
using CoreMedia;
using QuickLook;
using CoreImage;
using SpriteKit;
using Foundation;
using CoreMotion;
using ObjCRuntime;
using AddressBook;
using MediaPlayer;
using GameplayKit;
using CoreGraphics;
using CoreLocation;
using AVFoundation;
using NewsstandKit;
using FileProvider;
using CoreAnimation;
using CoreFoundation;
using NetworkExtension;
namespace CleverTapSDK {
[Protocol (Name = "CleverTapSyncDelegate", WrapperType = typeof (CleverTapSyncDelegateWrapper))]
[ProtocolMember (IsRequired = false, IsProperty = false, IsStatic = false, Name = "ProfileDidInitialize", Selector = "profileDidInitialize:", ParameterType = new Type [] { typeof (string) }, ParameterByRef = new bool [] { false })]
[ProtocolMember (IsRequired = false, IsProperty = false, IsStatic = false, Name = "ProfileDidInitialize", Selector = "profileDidInitialize:forAccountId:", ParameterType = new Type [] { typeof (string), typeof (string) }, ParameterByRef = new bool [] { false, false })]
[ProtocolMember (IsRequired = false, IsProperty = false, IsStatic = false, Name = "ProfileDataUpdated", Selector = "profileDataUpdated:", ParameterType = new Type [] { typeof (NSDictionary) }, ParameterByRef = new bool [] { false })]
public interface ICleverTapSyncDelegate : INativeObject, IDisposable
{
}
public static partial class CleverTapSyncDelegate_Extensions {
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public static void ProfileDidInitialize (this ICleverTapSyncDelegate This, string CleverTapID)
{
if (CleverTapID == null)
throw new ArgumentNullException ("CleverTapID");
var nsCleverTapID = NSString.CreateNative (CleverTapID);
global::ApiDefinition.Messaging.void_objc_msgSend_IntPtr (This.Handle, Selector.GetHandle ("profileDidInitialize:"), nsCleverTapID);
NSString.ReleaseNative (nsCleverTapID);
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public static void ProfileDidInitialize (this ICleverTapSyncDelegate This, string CleverTapID, string accountId)
{
if (CleverTapID == null)
throw new ArgumentNullException ("CleverTapID");
if (accountId == null)
throw new ArgumentNullException ("accountId");
var nsCleverTapID = NSString.CreateNative (CleverTapID);
var nsaccountId = NSString.CreateNative (accountId);
global::ApiDefinition.Messaging.void_objc_msgSend_IntPtr_IntPtr (This.Handle, Selector.GetHandle ("profileDidInitialize:forAccountId:"), nsCleverTapID, nsaccountId);
NSString.ReleaseNative (nsCleverTapID);
NSString.ReleaseNative (nsaccountId);
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public static void ProfileDataUpdated (this ICleverTapSyncDelegate This, NSDictionary updates)
{
if (updates == null)
throw new ArgumentNullException ("updates");
global::ApiDefinition.Messaging.void_objc_msgSend_IntPtr (This.Handle, Selector.GetHandle ("profileDataUpdated:"), updates.Handle);
}
}
internal sealed class CleverTapSyncDelegateWrapper : BaseWrapper, ICleverTapSyncDelegate {
[Preserve (Conditional = true)]
public CleverTapSyncDelegateWrapper (IntPtr handle, bool owns)
: base (handle, owns)
{
}
}
}
namespace CleverTapSDK {
[Protocol()]
[Register("CleverTapSyncDelegate", false)]
[Model]
public unsafe partial class CleverTapSyncDelegate : NSObject, ICleverTapSyncDelegate {
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
[Export ("init")]
public CleverTapSyncDelegate () : base (NSObjectFlag.Empty)
{
IsDirectBinding = false;
InitializeHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected CleverTapSyncDelegate (NSObjectFlag t) : base (t)
{
IsDirectBinding = false;
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected internal CleverTapSyncDelegate (IntPtr handle) : base (handle)
{
IsDirectBinding = false;
}
[Export ("profileDataUpdated:")]
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public virtual void ProfileDataUpdated (NSDictionary updates)
{
throw new You_Should_Not_Call_base_In_This_Method ();
}
[Export ("profileDidInitialize:")]
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public virtual void ProfileDidInitialize (string CleverTapID)
{
throw new You_Should_Not_Call_base_In_This_Method ();
}
[Export ("profileDidInitialize:forAccountId:")]
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public virtual void ProfileDidInitialize (string CleverTapID, string accountId)
{
throw new You_Should_Not_Call_base_In_This_Method ();
}
} /* class CleverTapSyncDelegate */
}
| 36.490323 | 269 | 0.774929 | [
"MIT"
] | ygit/clevertap-xamarin | clevertap-component/src/ios/CleverTap.Bindings.iOS/obj/Debug/ios/CleverTapSyncDelegate.g.cs | 5,656 | C# |
using nce.adosql;
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace BoatRenting {
public partial class boats_pre_mant_aspx_cs : System.Web.UI.Page
{
public string con = "";
public Connection oConn = null;
public const int adEmpty = 0;
public const int adTinyInt = 16;
public const int adSmallInt = 2;
public const int adInteger = 3;
public const int adBigInt = 20;
public const int adUnsignedTinyInt = 17;
public const int adUnsignedSmallInt = 18;
public const int adUnsignedInt = 19;
public const int adUnsignedBigInt = 21;
public const int adSingle = 4;
public const int adDouble = 5;
public const int adCurrency = 6;
public const int adDecimal = 14;
public const int adNumeric = 131;
public const int adBoolean = 11;
public const int adError = 10;
public const int adUserDefined = 132;
public const int adVariant = 12;
public const int adIDispatch = 9;
public const int adIUnknown = 13;
public const int adGUID = 72;
public const int adDate = 7;
public const int adDBDate = 133;
public const int adDBTime = 134;
public const int adDBTimeStamp = 135;
public const int adBSTR = 8;
public const int adChar = 129;
public const int adVarChar = 200;
public const int adLongVarChar = 201;
public const int adWChar = 130;
public const int adVarWChar = 202;
public const int adLongVarWChar = 203;
public const int adBinary = 128;
public const int adVarBinary = 204;
public const int adLongVarBinary = 205;
public const int adChapter = 136;
public const int adFileTime = 64;
public const int adPropVariant = 138;
public const int adVarNumeric = 139;
public const int adArray = 0x2000;
public const int adCmdStoredProc = 0x0004;
public const int adParamInput = 0x0001;
public const int adParamOutput = 0x0002;
public string sMes = "";
public object txt_marinaID = null;
public string txt_BoatID = "";
public Command cmd = null;
public Recordset rs = null;
public Command cmdF = null;
public Recordset rsF = null;
public Command cmdP = null;
public Recordset rsP = null;
public object NVL(object InputValue, object NullReplaceValue)
{
object NVL = null;
if (Convert.IsDBNull(InputValue))
{
NVL = NullReplaceValue;
}
else
{
if ((Convert.ToString(InputValue).Trim()).Length == 0)
{
NVL = NullReplaceValue;
}
else
{
NVL = InputValue;
}
}
return NVL;
}
public string ConvierteFecha(ref string sStartDate)
{
string ConvierteFecha = "";
object sPaola = null;
if (Convert.IsDBNull(sStartDate))
{
ConvierteFecha = "";
}
else
{
if (sStartDate == "")
{
ConvierteFecha = "";
}
else
{
if (sStartDate.Length != 11)
{
ConvierteFecha = "";
}
else
{
sStartDate = sStartDate.ToUpper();
sMes = sStartDate.Substring(4 - 1, 3);
if (sMes == "JAN")
{
sMes = "01";
}
if (sMes == "FEB")
{
sMes = "02";
}
if (sMes == "MAR")
{
sMes = "03";
}
if (sMes == "APR")
{
sMes = "04";
}
if (sMes == "MAY")
{
sMes = "05";
}
if (sMes == "JUN")
{
sMes = "06";
}
if (sMes == "JUL")
{
sMes = "07";
}
if (sMes == "AUG")
{
sMes = "08";
}
if (sMes == "SEP")
{
sMes = "09";
}
if (sMes == "OCT")
{
sMes = "10";
}
if (sMes == "NOV")
{
sMes = "11";
}
if (sMes == "DEC")
{
sMes = "12";
}
ConvierteFecha = sStartDate.Substring(1 - 1, 2) + "/" + sMes + "/" + sStartDate.Substring(8 - 1, 4);
}
}
}
return ConvierteFecha;
}
}
}
| 30.672414 | 121 | 0.44688 | [
"Apache-2.0"
] | richardreamz/rentaboat | admin/boats_pre_mant.aspx.cs | 5,337 | C# |
namespace XenAdmin.Dialogs
{
partial class AdPasswordPrompt
{
/// <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(AdPasswordPrompt));
this.labelBlurb = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.textBoxUsername = new System.Windows.Forms.TextBox();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.textBoxDomain = new System.Windows.Forms.TextBox();
this.labelAdditionalInfo = new System.Windows.Forms.Label();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.SkipButton = new System.Windows.Forms.Button();
this.tableLayoutPanel2.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.tableLayoutPanel2.SetColumnSpan(this.labelBlurb, 2);
this.labelBlurb.Name = "labelBlurb";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// textBoxUsername
//
resources.ApplyResources(this.textBoxUsername, "textBoxUsername");
this.textBoxUsername.Name = "textBoxUsername";
this.textBoxUsername.TextChanged += new System.EventHandler(this.textBoxUsername_TextChanged);
//
// textBoxPassword
//
resources.ApplyResources(this.textBoxPassword, "textBoxPassword");
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.UseSystemPasswordChar = true;
this.textBoxPassword.TextChanged += new System.EventHandler(this.textBoxPassword_TextChanged);
//
// buttonOk
//
resources.ApplyResources(this.buttonOk, "buttonOk");
this.buttonOk.Name = "buttonOk";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.labelBlurb, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.label1, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.textBoxDomain, 1, 1);
this.tableLayoutPanel2.Controls.Add(this.label2, 0, 2);
this.tableLayoutPanel2.Controls.Add(this.textBoxUsername, 1, 2);
this.tableLayoutPanel2.Controls.Add(this.label3, 0, 3);
this.tableLayoutPanel2.Controls.Add(this.textBoxPassword, 1, 3);
this.tableLayoutPanel2.Controls.Add(this.labelAdditionalInfo, 0, 4);
this.tableLayoutPanel2.Controls.Add(this.flowLayoutPanel1, 1, 5);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// textBoxDomain
//
resources.ApplyResources(this.textBoxDomain, "textBoxDomain");
this.textBoxDomain.Name = "textBoxDomain";
this.textBoxDomain.TextChanged += new System.EventHandler(this.textBoxDomain_TextChanged);
//
// labelAdditionalInfo
//
resources.ApplyResources(this.labelAdditionalInfo, "labelAdditionalInfo");
this.tableLayoutPanel2.SetColumnSpan(this.labelAdditionalInfo, 2);
this.labelAdditionalInfo.Name = "labelAdditionalInfo";
//
// flowLayoutPanel1
//
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.flowLayoutPanel1.Controls.Add(this.buttonCancel);
this.flowLayoutPanel1.Controls.Add(this.SkipButton);
this.flowLayoutPanel1.Controls.Add(this.buttonOk);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// SkipButton
//
resources.ApplyResources(this.SkipButton, "SkipButton");
this.SkipButton.Name = "SkipButton";
this.SkipButton.UseVisualStyleBackColor = true;
this.SkipButton.Click += new System.EventHandler(this.SkipButton_Click);
//
// AdPasswordPrompt
//
this.AcceptButton = this.buttonOk;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.tableLayoutPanel2);
this.Name = "AdPasswordPrompt";
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBoxUsername;
private System.Windows.Forms.TextBox textBoxPassword;
private System.Windows.Forms.Button buttonOk;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label labelBlurb;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxDomain;
private System.Windows.Forms.Button SkipButton;
private System.Windows.Forms.Label labelAdditionalInfo;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
}
}
| 46.647399 | 149 | 0.600743 | [
"BSD-2-Clause"
] | AaronRobson/xenadmin | XenAdmin/Dialogs/AdPasswordPrompt.Designer.cs | 8,070 | C# |
using System;
using System.Threading.Tasks;
using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.RPC.Eth.Transactions;
namespace Nethereum.RPC.Tests.Testers
{
/// <summary>
/// use web3 tests for calls and transactions tests
/// </summary>
public class EthCallTester : IRPCRequestTester
{
/*
curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from":"0x65180b8c813457b21dad6cc6363d195231b4d2e9","data":"0x606060405260728060106000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa1146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000600782029050606d565b91905056"}],"id":1}' http://localhost:8545
*/
public async Task<object> ExecuteTestAsync(IClient client)
{
//function multiply , input 69
var contractByteCode = "0xc6888fa10000000000000000000000000000000000000000000000000000000000000045";
var to = "0x32eb97b8ad202b072fd9066c03878892426320ed";
var ethSendTransation = new EthCall(client);
var transactionInput = new CallInput();
transactionInput.Data = contractByteCode;
transactionInput.To = to;
transactionInput.From = "0x12890D2cce102216644c59daE5baed380d84830c";
return await ethSendTransation.SendRequestAsync(transactionInput);
//result
// 0x00000000000000000000000000000000000000000000000000000000000001e3
//483
}
public Type GetRequestType()
{
return typeof (EthCallTester);
}
}
} | 43.666667 | 438 | 0.7064 | [
"MIT"
] | 6ara6aka/Nethereum | tests/Nethereum.RPC.IntegrationTests/Testers/EthCallTester.cs | 1,703 | C# |
using System.Collections;
using System.Collections.Generic;
using ThirdEyeSoftware.GameLogic;
using ThirdEyeSoftware.GameLogic.LogicHandlers;
using UnityEngine;
public class btnPrivacyPolicy : MonoBehaviour, IComponent
{
public ILogicHandler LogicHandler
{
get;
set;
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void OnClick()
{
LogicHandler.OnClick(this.gameObject.name);
}
}
| 16.15625 | 57 | 0.665377 | [
"BSD-3-Clause"
] | jaydpather/UnityGameEngineInterface | btnPrivacyPolicy.cs | 519 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Rasmus Mikkelsen
// Copyright (c) 2015-2018 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// 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 System.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;
using EventFlow.Configuration;
using EventFlow.Core;
using EventFlow.EventStores;
using EventFlow.Exceptions;
using EventFlow.Extensions;
using EventFlow.Subscribers;
using EventFlow.TestHelpers.Aggregates;
using EventFlow.TestHelpers.Aggregates.Commands;
using EventFlow.TestHelpers.Aggregates.Events;
using EventFlow.TestHelpers.Aggregates.ValueObjects;
using EventFlow.TestHelpers.Extensions;
using FluentAssertions;
using Moq;
using NUnit.Framework;
namespace EventFlow.TestHelpers.Suites
{
public abstract class TestSuiteForEventStore : IntegrationTest
{
private readonly List<IDomainEvent> _publishedDomainEvents = new List<IDomainEvent>();
protected IReadOnlyCollection<IDomainEvent> PublishedDomainEvents => _publishedDomainEvents;
[Test]
public async Task NewAggregateCanBeLoaded()
{
// Act
var testAggregate = await LoadAggregateAsync(ThingyId.New).ConfigureAwait(false);
// Assert
testAggregate.Should().NotBeNull();
testAggregate.IsNew.Should().BeTrue();
}
[Test]
public async Task EventsCanBeStored()
{
// Arrange
var id = ThingyId.New;
var testAggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
testAggregate.Ping(PingId.New);
// Act
var domainEvents = await testAggregate.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
// Assert
domainEvents.Count.Should().Be(1);
var pingEvent = domainEvents.Single() as IDomainEvent<ThingyAggregate, ThingyId, ThingyPingEvent>;
pingEvent.Should().NotBeNull();
pingEvent.AggregateIdentity.Should().Be(id);
pingEvent.AggregateSequenceNumber.Should().Be(1);
pingEvent.AggregateType.Should().Be(typeof(ThingyAggregate));
pingEvent.EventType.Should().Be(typeof(ThingyPingEvent));
pingEvent.Timestamp.Should().NotBe(default(DateTimeOffset));
pingEvent.Metadata.Count.Should().BeGreaterThan(0);
pingEvent.Metadata.SourceId.IsNone().Should().BeFalse();
}
[Test]
public async Task AggregatesCanBeLoaded()
{
// Arrange
var id = ThingyId.New;
var testAggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
testAggregate.Ping(PingId.New);
await testAggregate.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
// Act
var loadedTestAggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
// Assert
loadedTestAggregate.Should().NotBeNull();
loadedTestAggregate.IsNew.Should().BeFalse();
loadedTestAggregate.Version.Should().Be(1);
loadedTestAggregate.PingsReceived.Count.Should().Be(1);
}
[Test]
public async Task AggregateEventStreamsAreSeperate()
{
// Arrange
var id1 = ThingyId.New;
var id2 = ThingyId.New;
var aggregate1 = await LoadAggregateAsync(id1).ConfigureAwait(false);
var aggregate2 = await LoadAggregateAsync(id2).ConfigureAwait(false);
aggregate1.Ping(PingId.New);
aggregate2.Ping(PingId.New);
aggregate2.Ping(PingId.New);
// Act
await aggregate1.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
await aggregate2.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
aggregate1 = await LoadAggregateAsync(id1).ConfigureAwait(false);
aggregate2 = await LoadAggregateAsync(id2).ConfigureAwait(false);
// Assert
aggregate1.Version.Should().Be(1);
aggregate2.Version.Should().Be(2);
}
[Test]
public async Task DomainEventCanBeLoaded()
{
// Arrange
var id1 = ThingyId.New;
var id2 = ThingyId.New;
var pingId1 = PingId.New;
var pingId2 = PingId.New;
var aggregate1 = await LoadAggregateAsync(id1).ConfigureAwait(false);
var aggregate2 = await LoadAggregateAsync(id2).ConfigureAwait(false);
aggregate1.Ping(pingId1);
aggregate2.Ping(pingId2);
await aggregate1.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
await aggregate2.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
// Act
var domainEvents = await EventStore.LoadAllEventsAsync(GlobalPosition.Start, 200, CancellationToken.None).ConfigureAwait(false);
// Assert
domainEvents.DomainEvents.Count.Should().BeGreaterOrEqualTo(2);
}
[Test]
public async Task LoadingOfEventsCanStartLater()
{
// Arrange
var id = ThingyId.New;
await PublishPingCommandsAsync(id, 5).ConfigureAwait(false);
// Act
var domainEvents = await EventStore.LoadEventsAsync<ThingyAggregate, ThingyId>(id, 3, CancellationToken.None).ConfigureAwait(false);
// Assert
domainEvents.Should().HaveCount(3);
domainEvents.ElementAt(0).AggregateSequenceNumber.Should().Be(3);
domainEvents.ElementAt(1).AggregateSequenceNumber.Should().Be(4);
domainEvents.ElementAt(2).AggregateSequenceNumber.Should().Be(5);
}
[Test]
public async Task AggregateCanHaveMultipleCommits()
{
// Arrange
var id = ThingyId.New;
// Act
var aggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate.Ping(PingId.New);
await aggregate.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
aggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate.Ping(PingId.New);
await aggregate.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
aggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
// Assert
aggregate.PingsReceived.Count.Should().Be(2);
}
[Test]
public async Task AggregateEventStreamsCanBeDeleted()
{
// Arrange
var id1 = ThingyId.New;
var id2 = ThingyId.New;
var aggregate1 = await LoadAggregateAsync(id1).ConfigureAwait(false);
var aggregate2 = await LoadAggregateAsync(id2).ConfigureAwait(false);
aggregate1.Ping(PingId.New);
aggregate2.Ping(PingId.New);
aggregate2.Ping(PingId.New);
await aggregate1.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
await aggregate2.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
// Act
await EventStore.DeleteAggregateAsync<ThingyAggregate, ThingyId>(id2, CancellationToken.None).ConfigureAwait(false);
// Assert
aggregate1 = await LoadAggregateAsync(id1).ConfigureAwait(false);
aggregate2 = await LoadAggregateAsync(id2).ConfigureAwait(false);
aggregate1.Version.Should().Be(1);
aggregate2.Version.Should().Be(0);
}
[Test]
public async Task NoEventsEmittedIsOk()
{
// Arrange
var id = ThingyId.New;
var aggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
// Act
await aggregate.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
}
[Test]
public async Task NextPositionIsIdOfNextEvent()
{
// Arrange
var id = ThingyId.New;
var aggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate.Ping(PingId.New);
await aggregate.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
// Act
var domainEvents = await EventStore.LoadAllEventsAsync(GlobalPosition.Start, 10, CancellationToken.None).ConfigureAwait(false);
// Assert
domainEvents.NextGlobalPosition.Value.Should().NotBe(string.Empty);
}
[Test]
public async Task LoadingFirstPageShouldLoadCorrectEvents()
{
// Arrange
var id = ThingyId.New;
var pingIds = new[] {PingId.New, PingId.New, PingId.New};
var aggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate.Ping(pingIds[0]);
aggregate.Ping(pingIds[1]);
aggregate.Ping(pingIds[2]);
await aggregate.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
// Act
var domainEvents = await EventStore.LoadAllEventsAsync(GlobalPosition.Start, 200, CancellationToken.None).ConfigureAwait(false);
// Assert
domainEvents.DomainEvents.OfType<IDomainEvent<ThingyAggregate, ThingyId, ThingyPingEvent>>().Should().Contain(e => e.AggregateEvent.PingId == pingIds[0]);
domainEvents.DomainEvents.OfType<IDomainEvent<ThingyAggregate, ThingyId, ThingyPingEvent>>().Should().Contain(e => e.AggregateEvent.PingId == pingIds[1]);
}
[Test]
public async Task OptimisticConcurrency()
{
// Arrange
var id = ThingyId.New;
var aggregate1 = await LoadAggregateAsync(id).ConfigureAwait(false);
var aggregate2 = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate1.DomainErrorAfterFirst();
aggregate2.DomainErrorAfterFirst();
// Act
await aggregate1.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
await ThrowsExceptionAsync<OptimisticConcurrencyException>(() => aggregate2.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None)).ConfigureAwait(false);
}
[Test]
public async Task AggregatesCanUpdatedAfterOptimisticConcurrency()
{
// Arrange
var id = ThingyId.New;
var pingId1 = PingId.New;
var pingId2 = PingId.New;
var aggregate1 = await LoadAggregateAsync(id).ConfigureAwait(false);
var aggregate2 = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate1.Ping(pingId1);
aggregate2.Ping(pingId2);
await aggregate1.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
await ThrowsExceptionAsync<OptimisticConcurrencyException>(() => aggregate2.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None)).ConfigureAwait(false);
// Act
aggregate1 = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate1.PingsReceived.Single().Should().Be(pingId1);
aggregate1.Ping(pingId2);
await aggregate1.CommitAsync(EventStore, SnapshotStore, SourceId.New, CancellationToken.None).ConfigureAwait(false);
// Assert
aggregate1 = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate1.PingsReceived.Should().BeEquivalentTo(new[] {pingId1, pingId2});
}
[Test]
public async Task MultipleScopes()
{
// Arrange
var id = ThingyId.New;
var pingId1 = PingId.New;
var pingId2 = PingId.New;
// Act
using (var scopedResolver = Resolver.BeginScope())
{
var commandBus = scopedResolver.Resolve<ICommandBus>();
await commandBus.PublishAsync(
new ThingyPingCommand(id, pingId1))
.ConfigureAwait(false);
}
using (var scopedResolver = Resolver.BeginScope())
{
var commandBus = scopedResolver.Resolve<ICommandBus>();
await commandBus.PublishAsync(
new ThingyPingCommand(id, pingId2))
.ConfigureAwait(false);
}
// Assert
var aggregate = await LoadAggregateAsync(id).ConfigureAwait(false);
aggregate.PingsReceived.Should().BeEquivalentTo(new []{pingId1, pingId2});
}
[Test]
public async Task PublishedDomainEventsHaveAggregateSequenceNumbers()
{
// Arrange
var id = ThingyId.New;
var pingIds = Many<PingId>(10);
// Act
await CommandBus.PublishAsync(
new ThingyMultiplePingsCommand(id, pingIds))
.ConfigureAwait(false);
// Assert
PublishedDomainEvents.Count.Should().Be(10);
PublishedDomainEvents.Select(d => d.AggregateSequenceNumber).Should().BeEquivalentTo(Enumerable.Range(1, 10));
}
[Test]
public async Task PublishedDomainEventsContinueAggregateSequenceNumbers()
{
// Arrange
var id = ThingyId.New;
var pingIds = Many<PingId>(10);
await CommandBus.PublishAsync(
new ThingyMultiplePingsCommand(id, pingIds))
.ConfigureAwait(false);
_publishedDomainEvents.Clear();
// Act
await CommandBus.PublishAsync(
new ThingyMultiplePingsCommand(id, pingIds))
.ConfigureAwait(false);
// Assert
PublishedDomainEvents.Count.Should().Be(10);
PublishedDomainEvents.Select(d => d.AggregateSequenceNumber).Should().BeEquivalentTo(Enumerable.Range(11, 10));
}
[Test]
public virtual async Task LoadAllEventsAsyncFindsEventsAfterLargeGaps()
{
// Arrange
var ids = Enumerable.Range(0, 10)
.Select(i => ThingyId.New)
.ToArray();
foreach (var id in ids)
{
var command = new ThingyPingCommand(id, PingId.New);
await CommandBus.PublishAsync(command).ConfigureAwait(false);
}
foreach (var id in ids.Skip(1).Take(5))
{
await EventPersistence.DeleteEventsAsync(id, CancellationToken.None)
.ConfigureAwait(false);
}
// Act
var result = await EventStore
.LoadAllEventsAsync(GlobalPosition.Start, 5, CancellationToken.None)
.ConfigureAwait(false);
// Assert
result.DomainEvents.Should().HaveCount(5);
}
[SetUp]
public void TestSuiteForEventStoreSetUp()
{
_publishedDomainEvents.Clear();
}
protected override IEventFlowOptions Options(IEventFlowOptions eventFlowOptions)
{
var subscribeSynchronousToAllMock = new Mock<ISubscribeSynchronousToAll>();
subscribeSynchronousToAllMock
.Setup(s => s.HandleAsync(It.IsAny<IReadOnlyCollection<IDomainEvent>>(), It.IsAny<CancellationToken>()))
.Callback<IReadOnlyCollection<IDomainEvent>, CancellationToken>((d, c) => _publishedDomainEvents.AddRange(d))
.Returns(Task.FromResult(0));
return base.Options(eventFlowOptions)
.RegisterServices(sr => sr.Register(r => subscribeSynchronousToAllMock.Object, Lifetime.Singleton));
}
private static async Task ThrowsExceptionAsync<TException>(Func<Task> action)
where TException : Exception
{
var wasCorrectException = false;
try
{
await action().ConfigureAwait(false);
}
catch (Exception e)
{
wasCorrectException = e.GetType() == typeof(TException);
if (!wasCorrectException)
{
throw;
}
}
wasCorrectException.Should().BeTrue("Action was expected to throw exception {0}", typeof(TException).PrettyPrint());
}
}
} | 41.678161 | 188 | 0.632488 | [
"MIT"
] | OsvaldoJ/EventFlow | Source/EventFlow.TestHelpers/Suites/TestSuiteForEventStore.cs | 18,132 | C# |
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
namespace Microsoft.DevSkim
{
/// <summary>
/// Class holds information about suppressed issue
/// </summary>
public class SuppressedIssue
{
public Boundary Boundary { get; set; }
public string ID { get; set; }
}
}
| 26.8 | 95 | 0.661692 | [
"MIT"
] | PavelBansky/DevSkim | src/Microsoft.DevSkim/Microsoft.DevSkim/SuppressedIssue.cs | 404 | C# |
namespace NAngular.Areas.HelpPage
{
/// <summary>
/// Indicates whether the sample is used for request or response
/// </summary>
public enum SampleDirection
{
Request = 0,
Response
}
} | 21.363636 | 69 | 0.578723 | [
"Unlicense"
] | robert-claypool/nangular | server/NAngular/Areas/HelpPage/SampleGeneration/SampleDirection.cs | 225 | 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("Prism.WinForms.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Prism.WinForms.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("9b8ccd16-ebf3-4bd7-81e2-5d2500cccca4")]
// 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.189189 | 84 | 0.745223 | [
"Apache-2.0"
] | imasm/Prism.WinForms | Source/WinForms/Prism.WinForms.Tests/Properties/AssemblyInfo.cs | 1,416 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Azure.Messaging.EventHubs.Compatibility;
using NUnit.Framework;
namespace Azure.Messaging.EventHubs.Tests
{
/// <summary>
/// The suite of tests for the <see cref="TrackOneEventHubProducer" />
/// class.
/// </summary>
///
[TestFixture]
public class TrackOneComparerTests
{
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventDataEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventDataEquivalentDetectsDifferentBodies()
{
var trackOneEvent = new TrackOne.EventData(new byte[] { 0x22, 0x44 });
var trackTwoEvent = new EventData(new byte[] { 0x11, 0x33 });
Assert.That(TrackOneComparer.IsEventDataEquivalent(trackOneEvent, trackTwoEvent), Is.False);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventDataEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventDataEquivalentDetectsDifferentProperties()
{
var body = new byte[] { 0x22, 0x44, 0x88 };
var trackOneEvent = new TrackOne.EventData((byte[])body.Clone());
var trackTwoEvent = new EventData((byte[])body.Clone());
trackOneEvent.Properties["test"] = "trackOne";
trackTwoEvent.Properties["test"] = "trackTwo";
Assert.That(TrackOneComparer.IsEventDataEquivalent(trackOneEvent, trackTwoEvent), Is.False);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventDataEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventDataEquivalentDetectsWhenOnePropertySetIsNull()
{
var body = new byte[] { 0x22, 0x44, 0x88 };
var trackOneEvent = new TrackOne.EventData((byte[])body.Clone());
var trackTwoEvent = new EventData((byte[])body.Clone());
trackOneEvent.Properties = null;
trackTwoEvent.Properties["test"] = "trackTwo";
Assert.That(TrackOneComparer.IsEventDataEquivalent(trackOneEvent, trackTwoEvent), Is.False);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventDataEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventDataEquivalentDetectsDifferentSystemProperties()
{
var body = new byte[] { 0x22, 0x44, 0x88 };
var trackOneEvent = new TrackOne.EventData((byte[])body.Clone());
var trackTwoEvent = new EventData((byte[])body.Clone());
trackOneEvent.SystemProperties = new TrackOne.EventData.SystemPropertiesCollection();
trackOneEvent.SystemProperties["something"] = "trackOne";
trackTwoEvent.SystemProperties = new EventData.SystemEventProperties();
trackTwoEvent.SystemProperties["something"] = "trackTwo";
Assert.That(TrackOneComparer.IsEventDataEquivalent(trackOneEvent, trackTwoEvent), Is.False);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventDataEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventDataEquivalentDetectsWhenOneSystemPropertySetIsNull()
{
var body = new byte[] { 0x22, 0x44, 0x88 };
var trackOneEvent = new TrackOne.EventData((byte[])body.Clone());
var trackTwoEvent = new EventData((byte[])body.Clone());
trackOneEvent.SystemProperties = new TrackOne.EventData.SystemPropertiesCollection();
trackOneEvent.SystemProperties["something"] = "trackOne";
trackTwoEvent.SystemProperties = null;
Assert.That(TrackOneComparer.IsEventDataEquivalent(trackOneEvent, trackTwoEvent), Is.False);
}
/// <summary>
/// Verifies functionality of the <see cref="IsEventDataEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventDataEquivalentDetectsEqualEvents()
{
var body = new byte[] { 0x22, 0x44, 0x88 };
var trackOneEvent = new TrackOne.EventData((byte[])body.Clone());
var trackTwoEvent = new EventData((byte[])body.Clone());
trackOneEvent.Properties["test"] = "same";
trackTwoEvent.Properties["test"] = "same";
trackOneEvent.SystemProperties = new TrackOne.EventData.SystemPropertiesCollection();
trackOneEvent.SystemProperties["something"] = "otherSame";
trackTwoEvent.SystemProperties = new EventData.SystemEventProperties();
trackTwoEvent.SystemProperties["something"] = "otherSame";
Assert.That(TrackOneComparer.IsEventDataEquivalent(trackOneEvent, trackTwoEvent), Is.True);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentDetectsDifferentOffsets()
{
var trackOnePosition = TrackOne.EventPosition.FromOffset("12", false);
var trackTwoPosition = EventPosition.FromOffset(12);
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.False, "The offset for track two is inclusive; even the same base offset with non-inclusive is not equivilent.");
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentRecognizesSameOffsets()
{
var trackOnePosition = TrackOne.EventPosition.FromOffset("12", true);
var trackTwoPosition = EventPosition.FromOffset(12);
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.True, "The offset for track two is inclusive; the equivilent offset set as inclusive should match.");
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentDetectsDifferentSequence()
{
var trackOnePosition = TrackOne.EventPosition.FromSequenceNumber(54123);
var trackTwoPosition = EventPosition.FromSequenceNumber(2);
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.False);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentRecognizesSameSequence()
{
var trackOnePosition = TrackOne.EventPosition.FromSequenceNumber(54123);
var trackTwoPosition = EventPosition.FromSequenceNumber(54123);
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.True);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentDetectsDifferentEnqueueTime()
{
var enqueueTime = DateTimeOffset.Parse("2015-10-27T12:00:00Z");
var trackOnePosition = TrackOne.EventPosition.FromEnqueuedTime(enqueueTime.UtcDateTime);
var trackTwoPosition = EventPosition.FromEnqueuedTime(enqueueTime.AddDays(1));
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.False);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentRecognizesSameEnqueueTime()
{
var enqueueTime = DateTimeOffset.Parse("2015-10-27T12:00:00Z");
var trackOnePosition = TrackOne.EventPosition.FromEnqueuedTime(enqueueTime.UtcDateTime);
var trackTwoPosition = EventPosition.FromEnqueuedTime(enqueueTime);
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.True);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentRecognizesSameBeginning()
{
var trackOnePosition = TrackOne.EventPosition.FromStart();
var trackTwoPosition = EventPosition.Earliest;
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.True);
}
/// <summary>
/// Verifies functionality of the <see cref="TrackOneComparer.IsEventPositionEquivalent" /> test
/// helper.
/// </summary>
///
[Test]
public void IsEventPositionEquivalentRecognizesSameEnding()
{
var trackOnePosition = TrackOne.EventPosition.FromEnd();
var trackTwoPosition = EventPosition.Latest;
Assert.That(TrackOneComparer.IsEventPositionEquivalent(trackOnePosition, trackTwoPosition), Is.True);
}
}
}
| 40.455645 | 220 | 0.630021 | [
"MIT"
] | gaurangisaxena/azure-sdk-for-net | sdk/eventhub/Azure.Messaging.EventHubs/tests/Compatibility/TrackOneComparerTests.cs | 10,035 | C# |
namespace EmployeesMapping.App.Commands
{
using System;
using System.Globalization;
using System.Linq;
using CustomMapper;
using EmployeesMapping.App.Commands.Contracts;
using EmployeesMapping.App.DTO;
using EmployeesMapping.Data;
public class SetBirthdayCommand : ICommand
{
private readonly EmployeesMappingContext _context;
private readonly Mapper _mapper;
private const string DATE_FORMAT = "dd-MM-yyyy";
public SetBirthdayCommand(Mapper mapper, EmployeesMappingContext context)
{
this._mapper = mapper;
this._context = context;
}
public string Execute(string[] args)
{
int desiredEmployeeId = int.Parse(args[0]);
DateTime birthday = DateTime.ParseExact(args[1], DATE_FORMAT, CultureInfo.InvariantCulture);
var employee = this._context
.Employees
.FirstOrDefault(e => e.Id == desiredEmployeeId);
if (employee is null)
{
throw new ArgumentException("Invalid employee id!");
}
employee.BirthDay = birthday;
this._context.SaveChanges();
var employeeDto = this._mapper.Map<EmployeeDto>(employee);
return $"Successfully updated employee birthday {employee.BirthDay.Value.ToString(DATE_FORMAT)} with id {desiredEmployeeId} -> {employeeDto.FirstName} {employeeDto.LastName}";
}
}
}
| 31.375 | 187 | 0.628818 | [
"MIT"
] | viktornikolov038/-Databases-Advanced-October-2019 | Custom Automapper/Exercise/EmployeesMapping.App/Commands/SetBirthdayCommand.cs | 1,508 | C# |
using System;
using System.Text;
using chapter09.lib.ML;
using chapter09.trainer.Enums;
using chapter09.trainer.Helpers;
using chapter09.trainer.Objects;
namespace chapter09.trainer
{
public class Program
{
public static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.Clear();
var arguments = CommandLineParser.ParseArguments<ProgramArguments>(args);
switch (arguments.Action)
{
case ProgramActions.FEATURE_EXTRACTOR:
new FileClassificationFeatureExtractor().Extract(arguments.TrainingFolderPath,
arguments.TestingFolderPath);
break;
case ProgramActions.PREDICT:
var prediction = new FileClassificationPredictor().Predict(arguments.PredictionFileName);
Console.WriteLine($"File is {(prediction.IsMalicious ? "malicious" : "clean")} with a {prediction.Confidence:P2}% confidence");
break;
case ProgramActions.TRAINING:
new FileClassificationTrainer().Train(arguments.TrainingFileName, arguments.TestingFileName);
break;
default:
Console.WriteLine($"Unhandled action {arguments.Action}");
break;
}
}
}
} | 34.190476 | 147 | 0.600279 | [
"MIT"
] | PacktPublishing/Hands-On-Machine-Learning-With-ML.NET | chapter09/chapter09.trainer/Program.cs | 1,438 | C# |
// Decompiled with JetBrains decompiler
// Type: Gtk.MacWebView
// Assembly: CocoStudio.Gtk.Extend, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: DBDD1FAC-46EB-4E25-BF62-EB35EC7EDA10
// Assembly location: C:\Program Files (x86)\Cocos\Cocos Studio 2\CocoStudio.Gtk.Extend.dll
using CocoStudio.Basic;
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.WebKit;
using System;
using System.Diagnostics;
using Xwt.GtkBackend;
namespace Gtk
{
public class MacWebView
{
public static Widget CreateMacWebView(string url)
{
return GtkMacInterop.NSViewToGtkWidget((object) new WebView() { PolicyDelegate = (WebPolicyDelegate) new MacWebView.DownLoadCallback(), UIDelegate = (WebUIDelegate) new MacWebView.MarkdownWebUIDelegate(), MainFrameUrl = url });
}
private class DownLoadCallback : WebPolicyDelegate
{
private readonly NSString WebActionNavigationTypeKey = new NSString("WebActionNavigationTypeKey");
private readonly NSString WebActionOriginalUrlKey = new NSString("WebActionOriginalUrlKey");
public override void DecidePolicyForNavigation(WebView webView, NSDictionary actionInformation, NSUrlRequest request, WebFrame frame, NSObject decisionToken)
{
switch (((NSNumber) actionInformation[this.WebActionNavigationTypeKey]).Int32Value)
{
case 0:
// ISSUE: reference to a compiler-generated method
NSWorkspace.SharedWorkspace.OpenUrl(actionInformation[this.WebActionOriginalUrlKey] as NSUrl);
WebPolicyDelegate.DecideIgnore(decisionToken);
break;
case 1:
case 2:
case 4:
WebPolicyDelegate.DecideIgnore(decisionToken);
break;
case 3:
case 5:
WebPolicyDelegate.DecideUse(decisionToken);
break;
}
}
public override void DecidePolicyForNewWindow(WebView webView, NSDictionary actionInformation, NSUrlRequest request, string newFrameName, NSObject decisionToken)
{
this.OpenWeb(request.ToString());
}
private void OpenWeb(string url)
{
try
{
using (Process.Start(url))
;
}
catch (Exception ex)
{
LogConfig.Output.Error((object) "Open web address failed.", ex);
}
}
}
private class MarkdownWebUIDelegate : WebUIDelegate
{
public override NSMenuItem[] UIGetContextMenuItems(WebView sender, NSDictionary forElement, NSMenuItem[] defaultMenuItems)
{
return (NSMenuItem[]) null;
}
}
}
}
| 33.551282 | 233 | 0.681697 | [
"MIT"
] | gdbobu/CocoStudio2.0.6 | CocoStudio.Gtk.Extend/Gtk/MacWebView.cs | 2,619 | C# |
using System;
namespace SharpVk.Glfw
{
/// <summary>
/// Bitmask indicating modifer keys.
/// </summary>
[Flags]
public enum Modifier
{
Shift = 0x1,
Control = 0x2,
Alt = 0x4,
Super = 0x8
}
} | 16 | 44 | 0.5 | [
"MIT"
] | xuri02/SharpVk | src/SharpVk.Glfw/Modifier.cs | 258 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.