text
stringlengths
13
6.01M
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BuildStatusViewModel.cs" company="Soloplan GmbH"> // Copyright (c) Soloplan GmbH. All rights reserved. // Licensed under the MIT License. See License-file in the project root for license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Soloplan.WhatsON.GUI.Common.BuildServer { using System; using System.Collections.ObjectModel; using Soloplan.WhatsON.GUI.Common.ConnectorTreeView; using Soloplan.WhatsON.Model; public class BuildStatusViewModel : StatusViewModel { private TimeSpan estimatedDuration; private TimeSpan duration; private bool building; private int? buildNumber; private string displayName; private int progress; private int rawProgress; private bool buildingNoLongerThenExpected; private bool buildingLongerThenExpected; private TimeSpan estimatedRemaining; private TimeSpan buildTimeExcedingEstimation; private ObservableCollection<UserViewModel> culprits; private string url; public BuildStatusViewModel(ConnectorViewModel model) : base(model) { } /// <summary> /// Gets the command for opening the build webPage. /// </summary> public virtual OpenWebPageCommand OpenBuildPage { get; } = new OpenWebPageCommand(); public virtual CopyBuildLabelCommand CopyBuildLabel { get; } = new CopyBuildLabelCommand(); public ObservableCollection<UserViewModel> Culprits => this.culprits ?? (this.culprits = new ObservableCollection<UserViewModel>()); public int? BuildNumber { get { return this.buildNumber; } protected set { if (this.buildNumber != value) { this.buildNumber = value; this.OnPropertyChanged(); } } } public string DisplayName { get { return this.displayName; } protected set { if (this.displayName != value) { this.displayName = value; this.OnPropertyChanged(); } } } public override string Label { get { // if a custom label is set, use it if (!string.IsNullOrWhiteSpace(base.Label)) { return base.Label; } if (!string.IsNullOrEmpty(this.DisplayName)) { // #123 some displayname if (this.BuildNumber.HasValue && this.DisplayName.Contains($"#{this.BuildNumber.Value}")) { return this.DisplayName; } // another displayName without number (#123) return $"{this.DisplayName} (#{this.BuildNumber})"; } if (this.BuildNumber.HasValue) { // #123 return $"#{this.BuildNumber.Value}"; } return string.Empty; } protected set => base.Label = value; } public string Url { get => this.url; set { if (this.url != value) { this.url = value; this.OnPropertyChanged(); } } } public bool Building { get => this.building; protected set { if (this.building != value) { this.building = value; this.OnPropertyChanged(); } } } public DateTime FinishTime { get { return this.Time + this.Duration; } } public override DateTime Time { get => base.Time; protected set { if (base.Time != value) { base.Time = value; this.OnPropertyChanged(nameof(this.FinishTime)); } } } public TimeSpan Duration { get { return this.duration; } protected set { if (this.duration != value) { this.duration = value; this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.FinishTime)); } } } public TimeSpan EstimatedDuration { get { return this.estimatedDuration; } protected set { if (this.estimatedDuration != value) { this.estimatedDuration = value; this.OnPropertyChanged(); } } } public TimeSpan EstimatedRemaining { get => this.estimatedRemaining; set { if (this.estimatedRemaining != value) { this.estimatedRemaining = value; this.OnPropertyChanged(); } } } public TimeSpan BuildTimeExcedingEstimation { get => this.buildTimeExcedingEstimation; set { if (this.buildTimeExcedingEstimation != value) { this.buildTimeExcedingEstimation = value; this.OnPropertyChanged(); } } } /// <summary> /// Gets or sets progress shown in progress bar and displayed in GUI. /// The value is processed: /// <list type=""> /// <item>0 is changed to 1 to prevent progress bar showing unknown value.</item> /// <item>Changed to 0 if build is taking longer then expected to show unknown value.</item> /// <item>Otherwise the value from build server is shown.</item> /// </list> /// </summary> public int Progress { get { return this.progress; } protected set { if (this.progress != value) { this.progress = value; this.OnPropertyChanged(); } } } /// <summary> /// Gets or sets the true value of progress. Can get above 100% if the build takes longer then expected. /// </summary> public int RawProgress { get => this.rawProgress; protected set { this.rawProgress = value; this.OnPropertyChanged(); } } public bool BuildingNoLongerThenExpected { get => this.buildingNoLongerThenExpected; set { if (this.buildingNoLongerThenExpected != value) { this.buildingNoLongerThenExpected = value; this.OnPropertyChanged(); } } } public bool BuildingLongerThenExpected { get => this.buildingLongerThenExpected; set { if (this.buildingLongerThenExpected != value) { this.buildingLongerThenExpected = value; this.OnPropertyChanged(); } } } public override void Update(Status newStatus) { base.Update(newStatus); if (newStatus == null) { return; } this.BuildNumber = newStatus.BuildNumber; this.Building = newStatus.Building; this.Duration = newStatus.Duration; this.EstimatedDuration = newStatus.EstimatedDuration; this.Label = newStatus.Label; this.Url = newStatus.Url; this.ErrorMessage = newStatus.ErrorMessage; this.UpdateCalculatedFields(); } protected void UpdateCalculatedFields() { this.UpdateStateFlags(); this.UpdateEstimatedRemaining(); this.UpdateProgress(); } /// <summary> /// Updates flags used to control visibility of controls based on <see cref="State"/>. /// </summary> protected override void UpdateStateFlags() { this.Succees = false; this.Failure = false; this.Unknown = false; this.Unstable = false; if (!this.Building) { base.UpdateStateFlags(); } } /// <summary> /// Updates flags controlling visibility of progress bar and the progress bar buttons. /// </summary> private void UpdateEstimatedRemaining() { if (!this.Building) { this.BuildingNoLongerThenExpected = false; this.BuildingLongerThenExpected = false; this.EstimatedDuration = TimeSpan.Zero; } else { this.BuildingNoLongerThenExpected = this.EstimatedDuration > this.Duration; this.BuildingLongerThenExpected = !this.BuildingNoLongerThenExpected; if (this.BuildingNoLongerThenExpected) { this.EstimatedRemaining = this.EstimatedDuration - this.Duration; this.BuildTimeExcedingEstimation = TimeSpan.Zero; } else { this.EstimatedRemaining = TimeSpan.Zero; this.BuildTimeExcedingEstimation = this.Duration - this.EstimatedDuration; } } } /// <summary> /// Updates <see cref="Progress"/> based on other parameters. /// </summary> /// <remarks> /// Must be called when <see cref="BuildingNoLongerThenExpected"/>, <see cref="BuildingLongerThenExpected"/> and <see cref="RawProgress"/> are calculated /// and won't change. It is important not to change values when <see cref="BuildingLongerThenExpected"/> because it resets the indeterminate progress bar /// and the animation looks bad. /// </remarks> private void UpdateProgress() { if (this.BuildingNoLongerThenExpected && this.RawProgress == 0) { this.Progress = 1; } else if (this.BuildingLongerThenExpected) { this.Progress = 0; } else { this.Progress = this.RawProgress; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Task 2 namespace Divide_By_5_7 { class Program { static void Main(string[] args) { Console.Write("Enter n: "); int n = int.Parse(Console.ReadLine()); bool b = (n % 5 == 0 && n % 7 == 0); Console.WriteLine(b); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Ws2008.BLL; using Ws2008.MODEL; namespace Ws2008.WEB.Admin.soft { public partial class list : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //public SoftMODEL[] GetAll() //{ // SoftMODEL[] model = new SoftBLL().GetAll(); // return model; // //StringBuilder sb = new StringBuilder(); // //SoftMODEL[] model = new SoftBLL().GetAll(); // //sb.Append("<ul>"); // //for (int i = 0; i < model.Length; i++) // //{ // // sb.Append("<li><a href=\""); // // sb.Append("/Admin/Soft.aspx?type=edit&sid="); // // sb.Append(model[i].SoftID); // // sb.Append("&cid="); // // sb.Append(model[i].CategoryID+"\">"); // // sb.Append(model[i].Title); // // sb.Append("</a></li>\n"); // //} // //sb.Append("</ul>"); // //list = sb.ToString(); // //return list; //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// Email Model - Class to create Email Objects. /// </summary> namespace NapierBank.Models { public class Email { // Setup variables - getters and setters. public string MessageID { get; set; } public string Sender { get; set; } public string Subject { get; set; } public string Text { get; set; } public string SortCode { get; set; } public string NatureOfIncident { get; set; } // Setup Email Constructor. public Email() { // Set all email variables to empty. MessageID = string.Empty; Sender = string.Empty; Subject = string.Empty; Text = string.Empty; } // Setup second Email Constructor. public Email(string sortcode, string noi) { // Set all email variables to empty. Sender = string.Empty; Subject = string.Empty; Text = string.Empty; this.SortCode = sortcode; this.NatureOfIncident = noi; } } }
using System; using System.Data; using System.Data.Common; namespace System.Data.Linq.SqlClient { internal interface IConnectionManager { DbConnection UseConnection(IConnectionUser user); void ReleaseConnection(IConnectionUser user); } internal interface IConnectionUser { void CompleteUse(); } }
using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Markup; using System.Windows.Media; using WMagic; namespace WMaper.Misc.View.Plug { /// <summary> /// About.xaml 的交互逻辑 /// </summary> public sealed partial class About : UserControl { #region 常量 private const string TEXTBLOCK_TEMPLATE = @"<TextBlock xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>{0}</TextBlock>"; #endregion #region 变量 private bool ready; // 控件对象 private WMaper.Plug.About about; #endregion #region 构造函数 /// <summary> /// 构造函数 /// </summary> public About() { InitializeComponent(); } /// <summary> /// 构造函数 /// </summary> public About(int sort) : this() { Panel.SetZIndex(this, sort); } /// <summary> /// 构造函数 /// </summary> /// <param name="about"></param> public About(WMaper.Plug.About about, int sort) : this(sort) { this.ready = false; { (this.about = about).Facade = this.AboutDecor; { // 语言资源 this.AboutResource.MergedDictionaries.Add( this.about.Target.Assets.Language ); } } } #endregion #region 函数方法 /// <summary> /// 构建控件 /// </summary> public void Build() { if (!this.ready && (this.ready = true)) { // 适配位置 if ("left".Equals(this.about.Anchor)) { Canvas.SetLeft(this, 18); { this.AboutGrid.SizeChanged += new SizeChangedEventHandler((obj, evt) => { Canvas.SetBottom(this, this.AboutGrid.ActualHeight); }); } } else { Canvas.SetRight(this, 18); { this.AboutGrid.SizeChanged += new SizeChangedEventHandler((obj, evt) => { Canvas.SetBottom(this, this.AboutGrid.ActualHeight); { Canvas.SetRight(this, this.AboutGrid.ActualWidth + 18); } }); } } // 显示版权文本 if (!MatchUtils.IsEmpty(this.about.Author)) { TextBlock author = null; try { author = (TextBlock)XamlReader.Parse( String.Format(TEXTBLOCK_TEMPLATE, this.about.Author) ); } catch { author = null; } finally { if (!MatchUtils.IsEmpty(author)) { author.FontSize = 12; author.FontStyle = FontStyles.Normal; author.FontWeight = FontWeights.Normal; author.Background = Brushes.Transparent; author.FontFamily = new FontFamily("SimSun"); author.Foreground = new SolidColorBrush( Color.FromRgb((byte)103, (byte)104, (byte)125) ); author.TextWrapping = TextWrapping.NoWrap; // 绑定事件 foreach (Inline link in author.Inlines) { if (link is Hyperlink) { (link as Hyperlink).Click += (obj, evt) => { // 浏览链接 Process.Start((obj as Hyperlink).NavigateUri + ""); }; } } // 加载控件 this.AboutGrid.Children.Add(author); } } } } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using PowerString.Data; namespace PowerString { public partial class ResultForm : Form { private TypingTestForm _typingTestForm; private Tester _tester; private decimal _time;//테스트에서 받아온 시간 private bool _perfect;//테스트에서 받아온 완전 정답 여부 private decimal _score;//테스트에서 받아온 점수 private string _line;//결과 텍스트를 위한 string private ResultForm() { InitializeComponent(); } public ResultForm(TypingTestForm typingTestform, Tester tester, decimal time, bool perfect, decimal score) : this() { _typingTestForm = typingTestform; _tester = tester; _time = time; _perfect = perfect; _score = score; } // 메인메뉴로 돌아가기 버튼 private void MoveToMainMenu_Click(object sender, EventArgs e) { MoveEvent.MoveToForm(new MainMenuForm(_tester)); this.Close(); _typingTestForm.CloseForm(); } private void Close_Click(object sender, EventArgs e) { this.Close(); } private void ResultForm_Load(object sender, EventArgs e) { ResultImg.Image.Dispose(); if (!_perfect) { ChangeLineAndImage(1); } else { if (_score < 100) { ChangeLineAndImage(0); } else { ChangeLineAndImage(2); } } String tName = _tester.TesterName; TextGroup.Text = $"{tName}님은"; ResultLine.Text = $"{_time}초 동안 코드를 작성하셨습니다.{Environment.NewLine}" + $"{Environment.NewLine}" + $"{_score}점을 획득하셨습니다.{Environment.NewLine}" + $"{Environment.NewLine}" + $"{_line}"; //엔딩 문장 } private void ChangeLineAndImage(int i) { switch (i) { case 0: { ResultImg.Image = ClearImgList.Images[0]; //거북이 사진으로 교체 _line = "성의있는 코딩도 좋지만 조금 더 빠르게 치시면 좋겠어요."; //다 정답이지만 시간이 부족한 경우, 좀 더 노력합시다, break; } case 1: { ResultImg.Image = ClearImgList.Images[1]; //나무늘보 사진으로 교체 _line = "부지런하게 연습해봅시다."; //퍼펙트가 아니면 부지런히 코디합시다. break; } case 2: { ResultImg.Image = ClearImgList.Images[2]; //참 잘했어요! _line = "빠르면서도 완벽한 코딩이었습니다!"; //다 정답이고 빨리 쳤습니다! break; } default: break; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcApplication2 { public class MyRoles { public static string Administrators = "Administrators"; public static string UserAdmin = "User Admin"; public static string CoAdmin = "Co-Admin"; public static string GeneralUser = "General User"; public static string NotMember = "Not Member"; public static string Editor = "Editor"; public static string Internal = "Internal"; // mainly for showing the "ManageSite" & "ManageiGuardExpress" tabs in Dealer page (comment (150224) public static string RealTimeMonitor = "RealTimeMonitor"; public static string CoViewer = "Co-Viewer"; public static string Dealer = "Dealer"; } }
using System; using System.Collections.Generic; using System.Linq; namespace ClaseAbstracta { class Program { static void Main(string[] args) { Acutangulo acutangulo = new Acutangulo(); Escaleno escaleno = new Escaleno(); acutangulo.Area(); escaleno.Area(); acutangulo.CalcularAreaEnBaseAngulos(2, 3, 4); escaleno.CalcularAreaTrianguloconHipotenusa(2, 5); acutangulo.CalcularAreaTrianguloconHipotenusa(2, 5); Console.WriteLine("Hello World!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shop { class Sales { public static List<Sales> sList = new List<Sales>(); public int id { set; get; } public string date { set; get; } public int idProduct { set; get; } public string nameProduct { set; get; } public int ammount { set; get; } public double sumSales { set; get; } public Sales() { } public Sales(int i, string d, int iP,string nP, int a, double sumS) { id = i; date = d; idProduct = iP; nameProduct = nP; ammount = a; sumSales = sumS; } } }
using System; using System.Collections.Generic; using UnityEngine; public sealed class MathHandler { //max > 1 public static MathProblem CreateAdditionProblem(int max) { int a, b, c; System.Random r = new System.Random(); a = r.Next(1, max); b = r.Next(0, max - a + 1); c = a+b; return new MathProblem(a,b,c,true); } //max > 1 public static string GenerateAdditionProblemString(int size, int max) { int a, b, c; string s = ""; System.Random r = new System.Random(Environment.TickCount); for(int i = 0; i<size; i++) { a = r.Next(1, max); b = r.Next(0, max - a + 1); c = a+b; s += ""+a+b+c+"p"; } Debug.Log(s); return s; } //max > 1 public static MathProblem CreateSubtractionProblem(int max) { int a, b, c, big, small; System.Random r = new System.Random(); a = r.Next(1, max+1); b = r.Next(0, max+1); big = Math.Max(a,b); small = Math.Min(a,b); a = big; b = small; c = big-small; return new MathProblem(a,b,c,false); } public static string GenerateSubtractionProblemString(int size, int max) { int a, b, c, big, small; string s = ""; System.Random r = new System.Random(Environment.TickCount); for(int i = 0; i<size; i++) { a = r.Next(1, max+1); b = r.Next(0, max+1); big = Math.Max(a,b); small = Math.Min(a,b); a = big; b = small; c = big-small; s += ""+a+b+c+"m"; } Debug.Log(s); return s; } public static int[] NotThisNumber(int num) { return NotThisNumber(num, 9, 8); } public static int[] NotThisNumber(int num, int max, int sizeOfReturnArray) { Debug.Log("params: num,max,sizeofreturn" + num + "," + max +"," + sizeOfReturnArray); if(sizeOfReturnArray<1) return null; //error, throw exception here if(num>max) return null; //error, throw new exception here List<int> allNumbersFromZeroToMax = new List<int>(); for(int i = 0; i<=max; i++) { allNumbersFromZeroToMax.Add(i); Debug.Log(i + " added to list, list size: " + allNumbersFromZeroToMax.Count); } allNumbersFromZeroToMax.Remove(num); Debug.Log(num + " removed from list, list size: " + allNumbersFromZeroToMax.Count); int[] returnArray = new int[sizeOfReturnArray+1]; Debug.Log("returnArray created, size: " + returnArray.Length); System.Random r = new System.Random(Environment.TickCount); for(int i = 0; i<=sizeOfReturnArray; i++) { int index = r.Next(0,max-i); Debug.Log("index of number to be removed: " + index + ", value at index: " + allNumbersFromZeroToMax[index]); returnArray[i] = allNumbersFromZeroToMax[index]; Debug.Log(returnArray[i] + " added to return array at index " + i); allNumbersFromZeroToMax.RemoveAt(index); Debug.Log("number at index " + index + " removed from allnumberslist, current size: " + allNumbersFromZeroToMax.Count); } Debug.Log("return array ready!"); string s = ""; for(int i = 0; i<returnArray.Length; i++) { s += returnArray[i] + " " ; } Debug.Log(s); return returnArray; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Game_Manager : MonoBehaviour { public Game_Manager instance; //UI 패널 지우기 public GameObject panel; private float destroyTime = 2.0f; //Enemy 자동 생성 public GameObject[] enemyObjs; public Transform[] spawnPoints; public float maxSpawnDelay; public float curSpawnDelay; public GameObject Textmesh; public GameObject player; public int enemyDeadnum; public bool isBoss; public AudioSource audioSource; public AudioClip BGMSound; // Start is called before the first frame update void Start() { //패널 삭제 Destroy(panel.gameObject, destroyTime); enemyDeadnum = 0; isBoss = false; audioSource = gameObject.AddComponent<AudioSource>(); audioSource.loop = false; audioSource.volume = 0.3f; Textmesh.SetActive(false); } // Update is called once per frame void Update() { curSpawnDelay += Time.deltaTime; if (curSpawnDelay > maxSpawnDelay && !isBoss) { SpawnEnemy(); maxSpawnDelay = Random.Range(0.5f, 3.0f); curSpawnDelay = 0; } if(audioSource.isPlaying==false) { audioSource.clip = BGMSound; audioSource.Play(); } if(enemyDeadnum>8&&isBoss==false) { Textmesh.SetActive(true); } if(isBoss==true) { Textmesh.SetActive(false); } } void SpawnEnemy() { if(enemyDeadnum < 10) { int ranEnemy = Random.Range(0, 3); int ranPoint = Random.Range(0, 5); GameObject enemy = Instantiate(enemyObjs[ranEnemy], spawnPoints[ranPoint].position, spawnPoints[ranPoint].rotation); Enemy enemyLogic = enemy.GetComponent<Enemy>(); enemyLogic.player = player; } else { isBoss = true; GameObject enemy = Instantiate(enemyObjs[3], spawnPoints[2].position, spawnPoints[2].rotation); Enemy enemyLogic = enemy.GetComponent<Enemy>(); enemyLogic.player = player; } } }
namespace Exam_Konspiration { using System; using System.Collections.Generic; public class Konspiration { public static void Main() { int numLinesInput = int.Parse(Console.ReadLine()); var declaredMethods = new List<string>(); var invokedMethods = new List<List<string>>(); for (int i = 0; i < numLinesInput; i++) { string currentLine = Console.ReadLine(); declaredMethods = Extractor.GetDeclaredMethod(currentLine); if (Extractor.GetCurrentInvokedMethodsCount() >= 0) { invokedMethods = Extractor.GetInvokedMethods(currentLine); } } PrintResult(declaredMethods, invokedMethods); } private static void PrintResult(List<string> declaredMethods, List<List<string>> invokedMethods) { for (int i = 0; i < declaredMethods.Count; i++) { Console.WriteLine("{0} -> {1}", declaredMethods[i], invokedMethods[i].Count == 0 ? "None" : invokedMethods[i].Count + " -> " + string.Join(", ", invokedMethods[i])); } } } }
using System; using TestAccount; namespace BankSystem { enum MenuOption { Withdraw = 1, Deposit, Print , Quit } class BankSystem { static MenuOption ReadUserInput() { int input; do { Console.WriteLine("\nWelcome user!\n"); Console.WriteLine("To:\n1 Withdraw enter'1'\n2)Deposit enter'2'\n3)Print enter'3'\n4)Quit enter'4' "); Console.WriteLine("Enter choice: "); input = Convert.ToInt32(Console.ReadLine()); } while (input < 1 || input > 4); MenuOption option = (MenuOption)input; return option; } static void DoWithdraw(Account account) { Console.WriteLine("Enter the amount you want to withdraw:"); decimal amount = Convert.ToInt32(Console.ReadLine()); if (account.Withdraw(amount)) { Console.WriteLine("Withdrawal successful!"); } else { Console.WriteLine("Balance Not sufficient"); } } static void DoDeposit(Account account) { Console.WriteLine("enter the amount you want to deposit:"); decimal amount = Convert.ToInt32(Console.ReadLine()); if (account.Deposit(amount)) { Console.WriteLine("Deposit successful!"); } else { Console.WriteLine("Error! depossit unsuccessful! amount entered is invalid!"); } } static void Print(Account account) { account.Print(); } public static void Main(string[] args) { Console.WriteLine("Name of account for which you want Transaction: "); string n = Console.ReadLine(); Console.WriteLine("Enter balance in your account: "); decimal b = Convert.ToDecimal(Console.ReadLine()); Account acc = new Account(b, n); MenuOption option = ReadUserInput(); Console.WriteLine("YOU SELECTED TO " + option + "\n" + " To Change enter '1' else enter '0' :"); int confirm = Convert.ToInt32(Console.ReadLine()); if (confirm == 1) { option = ReadUserInput(); Console.WriteLine("YOU SELECTED TO" + option + "\n"); } switch (option) { case MenuOption.Withdraw: { DoWithdraw(acc); break; } case MenuOption.Deposit: { DoDeposit(acc); break; } case MenuOption.Print: { Print(acc); break; } case MenuOption.Quit: { break; } } } } }
using Microsoft.Extensions.Options; using System; using System.Threading.Tasks; using Xunit; namespace MailerQ.MessageStore.Test { public class MessageStorageTest { private const string SimpleValidMongoUri = "mongodb://server/database"; public static IOptions<MailerQConfiguration> CreateOptions(string uri) { var messageStorageSettings = new MailerQConfiguration { MessageStorageUrl = uri }; return Options.Create(messageStorageSettings); } [InlineData("")] [InlineData("not uri")] [Theory] public void Constructor_should_throw_exception_with_invalid_uri(string uri) { // Arrange var options = CreateOptions(uri); // Act var ex = Assert.Throws<ArgumentException>(() => new MessageStorage(options)); // Assert Assert.Contains("has invalid value", ex.Message); } [InlineData("http://server/path/to/directory")] [InlineData("https://server/path/to/directory")] [InlineData("ftp://path/to/directory")] [InlineData("file:///path/to/directory")] [Theory] public void Constructor_should_throw_exception_with_unsupported_engine_uri(string uri) { // Arrange var options = CreateOptions(uri); var expected = $"{nameof(MailerQConfiguration.MessageStorageUrl)} value does not correspond to a supported storage engine"; // Act var exception = Assert.Throws<ArgumentException>(() => new MessageStorage(options)); // Assert Assert.Equal(expected, exception.Message); } [InlineData("couchbase://password@hostname/bucketname")] [InlineData("mysql://user:password@hostname/databasename")] [InlineData("postgresql://user:password@hostname/databasename")] [InlineData("sqlite:///path/to/database/file")] [InlineData("directory:///path/to/directory")] [Theory] public void Constructor_should_throw_exception_with_not_implemented_supported_engine_uri(string uri) { // Arrange var options = CreateOptions(uri); var expected = "message storage engine is not implement yet."; // Act var ex = Assert.Throws<NotImplementedException>(() => new MessageStorage(options)); // Assert Assert.Contains(expected, ex.Message); } [InlineData(SimpleValidMongoUri)] [InlineData("mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary")] [InlineData("mongodb://mongos1.example.com,mongos2.example.com/database?readPreference=secondary")] [Theory] public void Constructor_should_create_instance_with_valid_supported_engine_uri(string uri) { // Arrange var options = CreateOptions(uri); // Act var sut = new MessageStorage(options); // Assert Assert.NotNull(sut); } [Fact] public async Task InsertAsync_should_throw_an_exception_using_mongodb_with_messages_larger_than_fifteen_megabytes() { // Arrange var size = 15728640; // 15 MB var message = new string('*', size); var options = CreateOptions(SimpleValidMongoUri); var sut = new MessageStorage(options); var expected = $"Message is to big, split is not suppported yet. Size should be less than {size} bytes."; // Act var exception = await Assert.ThrowsAsync<NotSupportedException>(() => sut.InsertAsync(message)); // Assert Assert.Equal(expected, exception.Message); } } }
using Sandbox; using System.Reflection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ZeroFormatter; using System.IO; using ZeroFormatter.Segments; using ZeroFormatter.Formatters; using ZeroFormatter.Internal; using Sandbox.Shared; using Sandbox.Shared.Bar; namespace Sandbox { [ZeroFormattable] public class Simple { [Index(0)] public virtual int I { get; set; } } public enum MogeMoge { Apple, Orange } public enum MyEnum { Furit, Alle } [ZeroFormattable] public class MyGuid { [Index(0)] public virtual Guid MyProperty { get; set; } [Index(1)] public virtual Uri MyProperty2 { get; set; } [Index(2)] public virtual KeyValuePair<string, int> MyProperty3 { get; set; } } [ZeroFormattable] public class Version1 { [Index(0)] public virtual int Prop1 { get; set; } [Index(1)] public virtual int Prop2 { get; set; } } [ZeroFormattable] public class Version2 { [Index(0)] public virtual int Prop1 { get; set; } [Index(1)] public virtual int Prop2 { get; set; } // You can add new property. If deserialize from old data, value is assigned default(T). [Index(2)] public virtual int NewType { get; set; } } [Serializable] [ZeroFormattable] public struct LargeStruct { private static void A(bool b) { if (!b) throw new Exception(); } [Index(0)] private ulong m_val1; [Index(1)] private ulong m_val2; [Index(2)] private ulong m_val3; [Index(3)] private ulong m_val4; private static ulong counter; public LargeStruct(ulong m_val1, ulong m_val2, ulong m_val3, ulong m_val4) { this.m_val1 = m_val1; this.m_val2 = m_val2; this.m_val3 = m_val3; this.m_val4 = m_val4; } public static LargeStruct Create() { return new LargeStruct { m_val1 = counter++, m_val2 = ulong.MaxValue - counter++, m_val3 = counter++, m_val4 = ulong.MaxValue - counter++ }; } public static void Compare(LargeStruct a, LargeStruct b) { A(a.m_val1 == b.m_val1); A(a.m_val2 == b.m_val2); A(a.m_val3 == b.m_val3); A(a.m_val4 == b.m_val4); } } [ZeroFormattable] public class Abc { [Index(0)] public virtual int A { get; set; } [Index(1)] public virtual int BA { get; set; } } [DynamicUnion] public abstract class MyClass { } [DynamicUnion] // root of DynamicUnion public class MessageBase { } public class UnknownMessage : MessageBase { } [ZeroFormattable] public class MessageA : MessageBase { } [ZeroFormattable] public class MessageB : MessageBase { [Index(0)] public virtual IList<IEvent> Events { get; set; } } // If new type received, return new UnknownEvent() [Union(subTypes: new[] { typeof(MailEvent), typeof(NotifyEvent) }, fallbackType: typeof(UnknownEvent))] public interface IEvent { [UnionKey] byte Key { get; } } [ZeroFormattable] public class MailEvent : IEvent { [IgnoreFormat] public byte Key => 1; [Index(0)] public string Message { get; set; } } [ZeroFormattable] public class NotifyEvent : IEvent { [IgnoreFormat] public byte Key => 1; [Index(0)] public bool IsCritical { get; set; } } [ZeroFormattable] public class UnknownEvent : IEvent { [IgnoreFormat] public byte Key => 0; } public class CustomSerializationContext : ITypeResolver { public bool IsUseBuiltinSerializer { get { return true; } } public object ResolveFormatter(Type type) { // same as Formatter.AppendFormatResolver. return null; } public void RegisterDynamicUnion(Type unionType, DynamicUnionResolver resolver) { // same as Formatter.AppendDynamicUnionResolver } } [ZeroFormattable] public class ArrayDirty { public static ArrayDirty Instance { get; private set; } [Index(0)] public virtual Nest MyProperty { get; set; } public ArrayDirty() { Instance = this; } } [ZeroFormattable] public class Nest { [Index(0)] public virtual int[] MyProperty { get; set; } } [ZeroFormattable] public struct ZeroA { } [ZeroFormattable] public class StringZ { [Index(0)] public virtual string MyProp { get; set; } } class Program { static void Main(string[] args) { var c = ZeroFormatterSerializer.Convert(new StringZ { MyProp = "a" }); c.MyProp = "b"; var re = ZeroFormatterSerializer.Convert(c); Console.WriteLine(re.MyProp); } } public interface Imessage { } [Union(new[] { typeof(Human), typeof(Monster) }, typeof(Unknown))] public abstract class Character { [UnionKey] public abstract CharacterType Type { get; } } public class Unknown : Character { public override CharacterType Type { get { return CharacterType.Unknown; } } } [ZeroFormattable] public class Human : Character { // UnionKey value must return constant value(Type is free, you can use int, string, enum, etc...) public override CharacterType Type { get { return CharacterType.Human; } } [Index(0)] public virtual string Name { get; set; } [Index(1)] public virtual DateTime Birth { get; set; } [Index(2)] public virtual int Age { get; set; } [Index(3)] public virtual int Faith { get; set; } } [ZeroFormattable] public class Monster : Character { public override CharacterType Type { get { return CharacterType.Monster; } } [Index(0)] public virtual string Race { get; set; } [Index(1)] public virtual int Power { get; set; } [Index(2)] public virtual int Magic { get; set; } } [ZeroFormattable] public struct MyStruct { [Index(0)] public int MyProperty1 { get; set; } [Index(1)] public int MyProperty2 { get; set; } public MyStruct(int x, int y) { MyProperty1 = x; MyProperty2 = y; } } [ZeroFormattable] public class ErrorClass { [Index(0)] public int MyProperty1; } public class UriFormatter<TTypeResolver> : Formatter<TTypeResolver, Uri> where TTypeResolver : ITypeResolver, new() { public override int? GetLength() { // If size is variable, return null. return null; } public override int Serialize(ref byte[] bytes, int offset, Uri value) { // Formatter<T> can get child serializer return Formatter<TTypeResolver, string>.Default.Serialize(ref bytes, offset, value.ToString()); } public override Uri Deserialize(ref byte[] bytes, int offset, DirtyTracker tracker, out int byteSize) { var uriString = Formatter<TTypeResolver, string>.Default.Deserialize(ref bytes, offset, tracker, out byteSize); return (uriString == null) ? null : new Uri(uriString); } } }
/** 版本信息模板在安装目录下,可自行修改。 * PaperExercise.cs * * 功 能: N/A * 类 名: PaperExercise * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2014/11/28 16:20:52 N/A 初版 * * Copyright (c) 2012 Maticsoft Corporation. All rights reserved. *┌──────────────────────────────────┐ *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │ *│ 版权所有:动软卓越(北京)科技有限公司              │ *└──────────────────────────────────┘ */ using System; using System.Collections.Generic; namespace IES.Resource.Model { /// <summary> /// 试卷下的习题 /// </summary> [Serializable] public partial class PaperExercise { #region 补充信息 // t2.Conten, t2.Kens, t2.Keys , t2.Diffcult,t2.IsRand , t2.ExerciseTypeName , t2.ExerciseType /// <summary> /// 习题内容 /// </summary> public string Conten { get; set; } /// <summary> /// 知识点 /// </summary> public string Kens { get; set; } /// <summary> /// 关键字 /// </summary> public string Keys { get; set; } /// <summary> /// 难度系统 /// </summary> public int Diffcult { get; set; } /// <summary> /// 是否随机 /// </summary> public bool IsRand { get; set; } /// <summary> /// 题型名称 /// </summary> public string ExerciseTypeName { get; set; } /// <summary> /// 题型 /// </summary> public int ExerciseType { get; set; } public List<ExerciseChoice> ExerciseChoices { get; set; } #endregion public PaperExercise() { this.ExerciseChoices = new List<ExerciseChoice>(); } #region Model private int _paperexerciseid; private int _paperid; private int _papergroupid; private int _exerciseid=0; private int _parentexerciseid=0; private int? _papertacticid=0; private decimal _score; private int _orde; /// <summary> /// 主键 /// </summary> public int PaperExerciseID { set{ _paperexerciseid=value;} get{return _paperexerciseid;} } /// <summary> /// 试卷编号 /// </summary> public int PaperID { set{ _paperid=value;} get{return _paperid;} } /// <summary> /// 试卷分组 /// </summary> public int PaperGroupID { set{ _papergroupid=value;} get{return _papergroupid;} } /// <summary> /// 习题编号,如果为0,则PaperTacticID /// </summary> public int ExerciseID { set{ _exerciseid=value;} get{return _exerciseid;} } /// <summary> /// 组合题父题的编号 /// </summary> public int ParentExerciseID { set{ _parentexerciseid=value;} get{return _parentexerciseid;} } /// <summary> /// 组卷策略的编号,如果ExerciseID为0,则PaperTacticID>0 /// </summary> public int? PaperTacticID { set{ _papertacticid=value;} get{return _papertacticid;} } /// <summary> /// 习题分值 /// </summary> public decimal Score { set{ _score=value;} get{return _score;} } /// <summary> /// 习题顺序 /// </summary> public int Orde { set{ _orde=value;} get{return _orde;} } #endregion Model } }
using Microsoft.Extensions.DependencyInjection; namespace DryIoc; /// <summary> /// This DryIoc is supposed to be used with generic `IHostBuilder` like this: /// /// <code><![CDATA[ /// public class Program /// { /// public static async Task Main(string[] args) => /// await CreateHostBuilder(args).Build().RunAsync(); /// /// Rules WithMyRules(Rules currentRules) => currentRules; /// /// public static IHostBuilder CreateHostBuilder(string[] args) => /// Host.CreateDefaultBuilder(args) /// .UseServiceProviderFactory(new DryIocServiceProviderFactory(new Container(rules => WithMyRules(rules)))) /// .ConfigureWebHostDefaults(webBuilder => /// { /// webBuilder.UseStartup<Startup>(); /// }); /// } /// ]]></code> /// /// Then register your services in `Startup.ConfigureContainer`. /// /// DON'T try to change the container rules there - they will be lost, /// instead pass the pre-configured container to `DryIocServiceProviderFactory` as in example above. /// By default container will use <see href="DryIoc.Rules.MicrosoftDependencyInjectionRules" /> /// /// DON'T forget to add `services.AddControllers().AddControllersAsServices()` in `Startup.ConfigureServices` /// in order to access DryIoc diagnostics for controllers, property-injection, etc. /// /// </summary> internal class DryIocServiceProviderFactory : IServiceProviderFactory<IContainer> { private readonly IContainer _container; private readonly Func<IRegistrator, ServiceDescriptor, bool> _registerDescriptor; private readonly RegistrySharing _registrySharing; /// <summary> /// We won't initialize the container here because it is logically expected to be done in `CreateBuilder`, /// so the factory constructor is just saving some options to use later. /// </summary> public DryIocServiceProviderFactory( IContainer container = null, Func<IRegistrator, ServiceDescriptor, bool> registerDescriptor = null ) : this(container, RegistrySharing.CloneAndDropCache, registerDescriptor) { } /// <summary> /// `container` is the existing container which will be cloned with the MS.DI rules and its cache will be dropped, /// unless the `registrySharing` is set to the `RegistrySharing.Share` or to `RegistrySharing.CloneButKeepCache`. /// `registerDescriptor` is the custom service descriptor handler. /// </summary> public DryIocServiceProviderFactory( IContainer container, RegistrySharing registrySharing, Func<IRegistrator, ServiceDescriptor, bool> registerDescriptor = null ) { _container = container; _registrySharing = registrySharing; _registerDescriptor = registerDescriptor; } /// <inheritdoc /> public IContainer CreateBuilder(IServiceCollection services) => ( _container ?? new Container(Rules.MicrosoftDependencyInjectionRules) ) .WithDependencyInjectionAdapter(services, _registerDescriptor, _registrySharing); /// <inheritdoc /> public IServiceProvider CreateServiceProvider(IContainer container) => container.BuildServiceProvider(); }
using System; using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Driver; using W3ChampionsStatisticService.Ports; using W3ChampionsStatisticService.ReadModelBase; namespace W3ChampionsStatisticService.Clans { public class ClanRepository : MongoDbRepositoryBase, IClanRepository { public async Task<bool> TryInsertClan(Clan clan) { var clanFound = await LoadFirst<Clan>(c => c.ClanId == clan.ClanId); if (clanFound != null) return false; await Insert(clan); return true; } public Task UpsertClan(Clan clan) { return Upsert(clan, c => c.ClanId == clan.ClanId); } public Task<Clan> LoadClan(string clanId) { return LoadFirst<Clan>(l => l.ClanId == clanId); } public Task<ClanMembership> LoadMemberShip(string battleTag) { return LoadFirst<ClanMembership>(m => m.BattleTag == battleTag); } public Task UpsertMemberShip(ClanMembership clanMemberShip) { return UpsertTimed(clanMemberShip, c => c.BattleTag == clanMemberShip.BattleTag); } public Task DeleteClan(string clanId) { return Delete<Clan>(c => c.ClanId == clanId); } public Task<List<ClanMembership>> LoadMemberShips(List<string> clanMembers) { return LoadAll<ClanMembership>(m => clanMembers.Contains(m.BattleTag)); } public Task<List<ClanMembership>> LoadMemberShipsSince(DateTimeOffset from) { return LoadSince<ClanMembership>(from); } public Task SaveMemberShips(List<ClanMembership> clanMembers) { return UpsertMany(clanMembers); } public ClanRepository(MongoClient mongoClient) : base(mongoClient) { } } }
namespace Turbomix { public interface ICocinaService { void Calentar(Alimento mAlimento1, Alimento mAlimento2); } }
using ExperianOfficeArrangement.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace ExperianOfficeArrangement.ViewModels { public class MainViewModel : BindableBase, IStateContext { private IStateViewModel currentState; public IStateViewModel CurrentState { get { return this.currentState; } private set { this.SetProperty(ref this.currentState, value); } } public ICommand SetStateCommand { get; private set; } public MainViewModel() { this.CurrentState = new LoadMapViewModel(new Factories.FileLoadInteriorLayoutFactory()) { Parent = this }; this.SetStateCommand = new DelegateCommand(this.SetState); } private void SetState(object state) { this.CurrentState = state as IStateViewModel; this.CurrentState.Parent = this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; namespace MZcms.Core.Helper { /// <summary> /// Api签名帮助类 /// </summary> public class ApiSignHelper { /// <summary> /// DateTime时间格式转换为Unix时间戳格式 /// </summary> /// <param name="time"> DateTime时间格式</param> /// <returns>Unix时间戳格式</returns> public static long ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); DateTime dtResult = time; long t = (dtResult.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 return t; } /// <summary> /// 时间戳转为C#格式时间 /// </summary> /// <param name="timeStamp">Unix时间戳格式</param> /// <returns>C#格式时间</returns> public static DateTime GetTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + (timeStamp.Length == 13 ? "0000" : "0000000")); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } /// <summary> /// 时间戳验证 /// </summary> /// <param name="timestamp"></param> /// <returns></returns> public static bool CheckTimeStamp(string timestamp) { DateTime time = DateTime.Parse(timestamp); TimeSpan span = (TimeSpan)(DateTime.Now - time); return (Math.Abs(span.TotalMinutes) <= 5.0); } /// <summary> /// 数据排序 /// </summary> /// <param name="dic"></param> /// <returns></returns> public static SortedDictionary<string, string> SortedData(IDictionary<string, string> dic) { SortedDictionary<string, string> result = new SortedDictionary<string, string>(dic); return result; } /// <summary> /// 参数过滤 sign sign_type /// </summary> /// <param name="dic"></param> /// <returns></returns> public static SortedDictionary<string, string> Parameterfilter(IDictionary<string, string> dic) { SortedDictionary<string, string> dictionary = new SortedDictionary<string, string>(); foreach (KeyValuePair<string, string> pair in dic) { if (((pair.Key.ToLower() != "sign") && (pair.Key.ToLower() != "sign_type")) && ((pair.Value != "") && (pair.Value != null))) { string key = pair.Key.ToLower(); dictionary.Add(key, pair.Value); } } return dictionary; } /// <summary> /// 生成待签名数据字符 /// </summary> /// <param name="dic"></param> /// <returns></returns> public static string Data2Linkstring(IDictionary<string, string> dic) { SortedDictionary<string, string> dictionary = new SortedDictionary<string, string>(dic); StringBuilder builder = new StringBuilder(); foreach (KeyValuePair<string, string> pair in dictionary) { if (!string.IsNullOrEmpty(pair.Key) && !string.IsNullOrEmpty(pair.Value)) { builder.Append(pair.Key + pair.Value); } } return builder.ToString(); } /// <summary> /// 获取签名 /// </summary> /// <param name="dic"></param> /// <param name="appSecret"></param> /// <param name="sign_type"></param> /// <param name="_input_charset"></param> /// <returns></returns> public static string GetSign(IDictionary<string, string> dic, string appSecret, string sign_type="MD5", string _input_charset="utf-8") { string signstr = Data2Linkstring(dic) + appSecret; return BuildSign(signstr, sign_type, _input_charset); } /// <summary> /// 生成签名 /// </summary> /// <param name="prestr"></param> /// <param name="sign_type"></param> /// <param name="_input_charset"></param> /// <returns></returns> public static string BuildSign(string prestr, string sign_type = "MD5", string _input_charset = "utf-8") { StringBuilder builder = new StringBuilder(0x50); if (sign_type.ToUpper() == "MD5") { byte[] buffer = new MD5CryptoServiceProvider().ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(prestr)); for (int i = 0; i < buffer.Length; i++) { builder.Append(buffer[i].ToString("x").PadLeft(2, '0')); } } return builder.ToString().ToUpper(); } /// <summary> /// 生成带签名的链接 /// </summary> /// <param name="dic"></param> /// <param name="appSecret"></param> /// <param name="sign_type"></param> /// <param name="_input_charset"></param> /// <returns></returns> public static string Data2URIAndSign(IDictionary<string, string> dic, string appSecret, string sign_type = "MD5", string _input_charset = "utf-8") { StringBuilder builder = new StringBuilder(0x50); builder.Append("?"); foreach (KeyValuePair<string, string> pair in dic) { if (!string.IsNullOrEmpty(pair.Key) && !string.IsNullOrEmpty(pair.Value)) { builder.Append(pair.Key +"="+ pair.Value+"&"); } } string sign = GetSign(Parameterfilter(dic), appSecret, sign_type, _input_charset); builder.Append("sign_type=MD5&"); builder.Append("sign=" + sign); return builder.ToString(); } /// <summary> /// 签名验证 /// </summary> /// <param name="dic"></param> /// <param name="appSecret"></param> /// <param name="sign_type"></param> /// <param name="_input_charset"></param> /// <returns></returns> public static bool CheckSign(IDictionary<string, string> dic, string appSecret, string sign_type = "MD5", string _input_charset = "utf-8") { var sign = GetSign(Parameterfilter(dic), appSecret, sign_type, _input_charset); bool flag = sign == dic["sign"]; return flag; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TE18B_String_manipulation { class Program { static void Main(string[] args) { string h = Console.ReadLine(); h = h.Trim().ToLower(); int pos = h.IndexOf(" "); Console.WriteLine(pos); string j = h.Substring(pos+1); Console.WriteLine("Hej " + j + " hur mår du idag?"); Console.ReadLine(); } } }
using System.Web.Mvc; using MvcContrib.PortableAreas; namespace JqD.Web.Common { public class CommonAreaRegistration : PortableAreaRegistration { public override string AreaName => "Common"; public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( AreaName, AreaName + "/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, new[] { "JqD.Web.Common.Controllers" } ); base.RegisterArea(context); } } }
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_GameObjectInfo : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { GameObjectInfo o = new GameObjectInfo(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Add_Transform(IntPtr l) { int result; try { GameObjectInfo gameObjectInfo = (GameObjectInfo)LuaObject.checkSelf(l); int type; LuaObject.checkType(l, 2, out type); long key; LuaObject.checkType(l, 3, out key); Transform t; LuaObject.checkType<Transform>(l, 4, out t); float radius; LuaObject.checkType(l, 5, out radius); gameObjectInfo.Add_Transform(type, key, t, radius); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Remove(IntPtr l) { int result; try { GameObjectInfo gameObjectInfo = (GameObjectInfo)LuaObject.checkSelf(l); long key; LuaObject.checkType(l, 2, out key); bool b = gameObjectInfo.Remove(key); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Clear(IntPtr l) { int result; try { GameObjectInfo gameObjectInfo = (GameObjectInfo)LuaObject.checkSelf(l); gameObjectInfo.Clear(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Get(IntPtr l) { int result; try { GameObjectInfo gameObjectInfo = (GameObjectInfo)LuaObject.checkSelf(l); long key; LuaObject.checkType(l, 2, out key); GameObjectInfo.Info o = gameObjectInfo.Get(key); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_map(IntPtr l) { int result; try { GameObjectInfo gameObjectInfo = (GameObjectInfo)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, gameObjectInfo.map); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.GameObjectInfo"); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjectInfo.Add_Transform)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjectInfo.Remove)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjectInfo.Clear)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjectInfo.Get)); LuaObject.addMember(l, "map", new LuaCSFunction(Lua_RO_GameObjectInfo.get_map), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_GameObjectInfo.constructor), typeof(GameObjectInfo)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; class Eratosthenes { static List<long> primes = new List<long>();// stores prime numbers static bool IsPrime(long checkValue) { bool isPrime = true; foreach (long prime in primes) { if ((checkValue % prime) == 0 && prime <= Math.Sqrt(checkValue)) { isPrime = false; break; } } return isPrime; } static void Main(string[] args) { /*Write a program that finds all prime numbers in the range [1...10 000 000]. Use the sieve of Eratosthenes algorithm (find it in Wikipedia).*/ DateTime start = DateTime.Now; int number = 1000000; primes.Add(2);//add manually number 2 Console.Write(2); for (long checkValue = 3; checkValue <= number; checkValue += 2) { if (IsPrime(checkValue)) { primes.Add(checkValue); Console.Write("\t{0}", checkValue); } } Console.WriteLine(); TimeSpan timeElapsed = DateTime.Now - start; Console.WriteLine("time elapsed: " + timeElapsed); } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace VACE_Controlling.Outlookbar { internal class BandPanel : Panel { public BandPanel(string caption, ContentPanel content, BandTagInfo bti) { BandButton bandButton = new BandButton(caption, bti); Controls.Add(bandButton); Controls.Add(content); this.BorderStyle = BorderStyle.None; } } }
using System.Collections.Generic; using Vaccination.Data; namespace Vaccination.ViewModels { public class VaccineIndexViewModel { public List<VaccineViewModel> Vaccines { get; set; } = new List<VaccineViewModel>(); } public class VaccineViewModel { public int Id { get; set; } public string Name { get; set; } public Supplier Supplier { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using XUnit.Moq.Produtos; namespace Models { public class Produto { public int Id { get; set; } public string Nome { get; set; } public string Descricao { get; set; } public decimal Preco { get; set; } } public class VerificadorPrecoProduto : IVerificadorPrecoProduto { public string VerificaPrecoProduto(Produto p) { if (p.Preco > 100) return "Produto caro!"; else if (p.Preco <= 100 && p.Preco > 40) return "Produto na média de preço!"; else return "Produto barato!"; } } }
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class DragAndDrop : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public static GameObject DraggedInstance; Vector3 _startPosition; Vector3 _offsetToMouse; float _zDistanceToCamera; float maxZHeight = 3; private BaseColumn columnSelected; Vector3 endPosition; // it has to be total nmber of the cards * their z distances public GameObject cardManager; CardManager cdmScript; CardTextScript textFetchScript; public GameObject cardObj; RuleEngine ruleScript; Vector3 cardOriginalPosition; bool addedCard = false; //bool dragComplete = false; int moves = 0; int score = 0; public Text moveText; void Start () { cardManager = GameObject.Find ("CardManagerObj"); cdmScript = cardManager.GetComponent<CardManager> (); textFetchScript = cardManager.GetComponent<CardTextScript> (); ruleScript = cardObj.GetComponent<RuleEngine> (); textFetchScript.winPanel.gameObject.SetActive(false) ; } void Update () { Debug.Log ("mvscol" + addedCard); //Debug.Log ("mvsph" + addedCard); if (addedCard == true) { moves+= 10; } textFetchScript.moveText.text = "Moves: " + moves; } public void OnBeginDrag (PointerEventData eventData) { Card selectedCard = gameObject.GetComponent<Card> (); cardOriginalPosition = selectedCard.GetPosition (); columnSelected = cdmScript.PopIfTopCardOfColumn (selectedCard); if (columnSelected == null ) { columnSelected = cdmScript.PopIfTopCardOfWasteColumn (selectedCard); if (columnSelected == null) { return; } } DraggedInstance = gameObject; _startPosition = transform.position; _zDistanceToCamera = Mathf.Abs (_startPosition.z - Camera.main.transform.position.z); _offsetToMouse = _startPosition - Camera.main.ScreenToWorldPoint ( new Vector3 (Input.mousePosition.x, Input.mousePosition.y, _zDistanceToCamera) ); } public void OnDrag (PointerEventData eventData) { if (columnSelected == null) { return; } if(Input.touchCount > 1) return; Card selectedCard = gameObject.GetComponent<Card> (); selectedCard.SetPosition( Camera.main.ScreenToWorldPoint ( new Vector3 ( Input.mousePosition.x, Input.mousePosition.y, _zDistanceToCamera - maxZHeight)) + _offsetToMouse); } public void OnEndDrag (PointerEventData eventData) { if (columnSelected == null) { return; } Card selectedCard = gameObject.GetComponent<Card> (); Column targetColumn = cdmScript.FindOverlappingColumn (selectedCard); PlaceholderColumn targetPhColum = cdmScript.FindOverlappingPlaceHolderColumn (selectedCard); bool flipTopCard = false; if (targetColumn != null && ruleScript.isMatching (selectedCard, targetColumn.GetTopCard ())) { targetColumn.AddCard (selectedCard); //moves++; addedCard = true; //textFetchScript.moveText.text = "Moves: " + moves; flipTopCard = true; } else if (targetPhColum != null && ruleScript.isPlaceHolderCardMatching(selectedCard, targetPhColum.GetTopCard ())) { targetPhColum.AddCard (selectedCard); addedCard = true; //moves++; //textFetchScript.moveText.text = "Moves: " + moves; score += 10; if (ruleScript.allStacksAreFull (cdmScript.placeholderColumnArray)) { Debug.Log ("Won"); //won dialogbox textFetchScript.winPanel.gameObject.SetActive(true) ; } flipTopCard = true; } else { columnSelected.AddCard (selectedCard); addedCard = false; } if (flipTopCard) { if (columnSelected is Column) { FlipTopCard (columnSelected); } } columnSelected = null; DraggedInstance = null; _offsetToMouse = Vector3.zero; transform.position = _startPosition; } void FlipTopCard(BaseColumn column) { if (!column.IsEmpty()) { column.GetTopCard ().Flip (); } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.Json.Serialization; namespace Checkout.Payment.Processor.Domain.Models.Enums { [JsonConverter(typeof(JsonStringEnumConverter))] public enum CurrencyType { USD, EUR, GBP } }
using Contoso.Data.Entities; using Microsoft.EntityFrameworkCore; namespace Contoso.Contexts.Configuations { internal class InstructorConfiguration : ITableConfiguration { public void Configure(ModelBuilder modelBuilder) { var entity = modelBuilder.Entity<Instructor>(); entity.ToTable(nameof(Instructor)); entity.HasKey(i => i.ID); entity.HasMany(i => i.Courses).WithOne(ca => ca.Instructor).HasForeignKey(ca => ca.InstructorID); entity.HasOne(i => i.OfficeAssignment).WithOne(oa => oa.Instructor).HasForeignKey<OfficeAssignment>(oa => oa.InstructorID); entity.Property(d => d.LastName).HasMaxLength(50); entity.Property(d => d.LastName).IsRequired(); entity.Property(d => d.FirstName).HasMaxLength(50); entity.Property(d => d.FirstName).IsRequired(); } } }
using IdentityServer4.EntityFramework.Entities; using Promact.Oauth.Server.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace Promact.Oauth.Server.Repository.ConsumerAppRepository { public interface IConsumerAppRepository { /// <summary> /// This method used for added consumer app and return primary key. -An /// </summary> /// <param name="consumerApp">App details as object</param> Task AddConsumerAppsAsync(ConsumerApps aaps); /// <summary> /// This method used for get list of apps. -An /// </summary> /// <returns>list of App</returns> Task<List<ConsumerApps>> GetListOfConsumerAppsAsync(); /// <summary> /// This method used for get apps detail by client id. /// </summary> /// <param name="clientId">App's clientId</param> /// <returns>App details</returns> Task<ConsumerApps> GetAppDetailsByClientIdAsync(string clientId); /// <summary> /// This method used for update consumer app and return primary key. -An /// </summary> /// <param name="consumerApps">App details as object</param> Task UpdateConsumerAppsAsync(ConsumerApps consumerApp); /// <summary> /// This method used for get random number For AuthId and Auth Secreate. -An /// </summary> /// <param name="isAuthId">isAuthId = true (get random number for auth id.) and /// isAuthId = false (get random number for auth secreate)</param> /// <returns>Random generated code</returns> string GetRandomNumber(bool isAuthId); } }
using Prueba.Vistas; 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 Prueba { /// <summary> /// Lógica de interacción para MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Persona_Click(object sender, RoutedEventArgs e) { Persona per = new Persona(); per.Show(); } private void Recaudo_Click(object sender, RoutedEventArgs e) { Recaudo recaudo = new Recaudo(); recaudo.Show(); } private void Beneficiario_Click(object sender, RoutedEventArgs e) { Beneficiario bene = new Beneficiario(); bene.Show(); } private void Contrato_Click(object sender, RoutedEventArgs e) { Contrato contrato = new Contrato(); contrato.Show(); } private void Ciudad_Click(object sender, RoutedEventArgs e) { Ciudad ciudad = new Ciudad(); ciudad.Show(); } private void Departamento_Click(object sender, RoutedEventArgs e) { Departamento departamento = new Departamento(); departamento.Show(); } private void Parentesco_Click(object sender, RoutedEventArgs e) { Parentesco parentesco = new Parentesco(); parentesco.Show(); } private void Salir_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace ISISFighters { class Menu { public Texture2D menutexture; public Rectangle menurectangle; public Texture2D switchtx; public Rectangle switchrc; public Texture2D option1tx; public Rectangle option1rc; public Texture2D option2tx; public Rectangle option2rc; public Texture2D option3tx; public Rectangle option3rc; public Texture2D option4tx; public Rectangle option4rc; public Texture2D option5tx; public Rectangle option5rc; public Texture2D sfxtexture; public Rectangle sfxrectangle; public Texture2D mustexture; public Rectangle musrectangle; public Rectangle[] menus; public Vector2 originalposition; public Vector2 position; public Vector2 switchposition; public int framewidth; public int frameheight; public int currentframe; public int index; public int menuindex; public float timer; public float interval = 80; public int value = 0; public Color colour; public bool next = false; public bool fade = false; public bool exit = false; public bool quit = false; public float sfx; public float musicvolume; public string[] parameters; public SoundEffect sample; public KeyboardState newstate; public KeyboardState oldstate; } class MainMenu: Menu { public MainMenu(Texture2D texture, Texture2D cursor, Texture2D opt1tx, Texture2D opt2tx, Texture2D opt3tx, Texture2D opt4tx, Texture2D opt5tx, Vector2 newposition, Vector2 switchpos, int newframewidth, int newframeheight, int index) { menutexture = texture; framewidth = newframewidth; frameheight = newframeheight; menurectangle = new Rectangle(0, 0, framewidth, frameheight); colour = new Color(255, 255, 255); menuindex = 6; switchtx = cursor; switchrc = new Rectangle(0, 0, 94, 48); switchposition = switchpos; option1tx = opt1tx; option2tx = opt2tx; option3tx = opt3tx; option4tx = opt4tx; option5tx = opt5tx; } public void Update(GameTime gameTime) { KeyboardState newstate = Keyboard.GetState(); if (newstate.IsKeyDown(Keys.Down) && oldstate.IsKeyUp(Keys.Down)) { menuindex++; switchposition.Y += 75; if (menuindex < 0) { menuindex = 4; switchposition.Y = 475; } else if (menuindex > 4) { menuindex = 0; switchposition.Y = 175; } } if (menuindex == 0) option1rc = new Rectangle(0, 75, 360, 75); else { option1rc = new Rectangle(0, 0, 360, 75); } if (menuindex == 1) option2rc = new Rectangle(0, 75, 360, 75); else { option2rc = new Rectangle(0, 0, 360, 75); } if (menuindex == 2) option3rc = new Rectangle(0, 75, 360, 75); else { option3rc = new Rectangle(0, 0, 360, 75); } if (menuindex == 3) option4rc = new Rectangle(0, 75, 360, 75); else { option4rc = new Rectangle(0, 0, 360, 75); } if (menuindex == 4) option5rc = new Rectangle(0, 75, 360, 75); else { option5rc = new Rectangle(0, 0, 360, 75); } if (newstate.IsKeyDown(Keys.Up) && oldstate.IsKeyUp(Keys.Up)) { menuindex--; switchposition.Y -= 75; if (menuindex < 0) { menuindex = 4; switchposition.Y = 475; } else if (menuindex > 4) { menuindex = 0; switchposition.Y = 175; } } if (newstate.IsKeyUp(Keys.Enter) && oldstate.IsKeyDown(Keys.Enter)) { switch (menuindex) { case 0: fade = true; break; case 1: index = 2; break; case 2: index = 3; break; case 3: index = 4; break; case 4: fade = true; quit = true; break; } } oldstate = newstate; if(fade) { timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds; if (timer >= 1 && colour.R > 2 && colour.G > 2 && colour.B > 2) { timer = 0; colour.R -=2; colour.G -=2; colour.B -=2; if (colour.R <= 2 && colour.G <= 2 && colour.B <= 2) { if (menuindex == 0) index = 1; else if(quit) { exit = true; } } } if (next) { } } } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(menutexture, position, menurectangle, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); if(menuindex < 5 && menuindex > -1) spriteBatch.Draw(switchtx, switchposition, switchrc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option1tx, new Vector2(95, 150), option1rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option2tx, new Vector2(95, 225), option2rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option3tx, new Vector2(85, 300), option3rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option4tx, new Vector2(75, 375), option4rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option5tx, new Vector2(45, 450), option5rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); } } class Options: Menu { public float volume; public int music; public bool fullscreen; public int screenwidth; public int screenheight; public string sfx2; public Options(Texture2D texture, Texture2D cursor, Texture2D opt1tx, Texture2D opt2tx, Texture2D opt3tx, Texture2D opt4tx, Texture2D newsfxtexture, SoundEffect newsample, Vector2 newposition, Vector2 switchpos, int newframewidth, int newframeheight, int index) { menutexture = texture; framewidth = newframewidth; frameheight = newframeheight; menurectangle = new Rectangle(0, 0, framewidth, frameheight); colour = new Color(255, 255, 255); menuindex = 6; switchtx = cursor; switchrc = new Rectangle(0, 0, 94, 48); switchposition = switchpos; // menu points option1tx = opt1tx; option2tx = opt2tx; option3tx = opt3tx; option4tx = opt4tx; // volume check // remove weird number like 2,980232E-08 StreamReader exceptioncheck = new StreamReader(@"params.ini"); string[] exceptions = exceptioncheck.ReadToEnd().Split('\n'); foreach (string s in exceptions) { if (s.Contains("2,980232E-08")) s.Replace("2,980232E-08", "0"); } exceptioncheck.Close(); StreamWriter exceptionremove = new StreamWriter(@"params.ini"); for (int i = 0; i < exceptions.Length - 1; i++) exceptionremove.WriteLine(exceptions[i]); exceptionremove.Close(); StreamReader sfxinit = new StreamReader(@"params.ini"); parameters = sfxinit.ReadToEnd().Split('\n'); foreach (string s in parameters) { // prevent digit format exception if (s.Contains("sfx")) { if (s.Contains("0,")) // if sound is between 0 & 1 sfx = Convert.ToSingle(s.Substring(5, 3)); // if sound is 0 or 1 else { sfx = Convert.ToSingle(s.Substring(5, 1)); } } else if (s.Contains("music")) { if (s.Contains("0,")) // if music is between 0 & 1 musicvolume = Convert.ToSingle(s.Substring(7, 3)); // if music is 0 or 1 else { musicvolume = Convert.ToSingle(s.Substring(7, 1)); } } } sfxinit.Close(); // volume switch graphics sfxtexture = newsfxtexture; mustexture = newsfxtexture; // volume sample sample = newsample; } public void Update(GameTime gameTime) { KeyboardState newstate = Keyboard.GetState(); // sound effects sfxrectangle = new Rectangle(0, Convert.ToInt32(SoundEffect.MasterVolume * 300), 120, 60); musrectangle = new Rectangle(0, Convert.ToInt32(MediaPlayer.Volume * 300), 120, 60); // switch between menu points if (newstate.IsKeyDown(Keys.Down) && oldstate.IsKeyUp(Keys.Down)) { menuindex++; switchposition.Y += 75; if (menuindex < 0) { menuindex = 2; switchposition.Y = 475; } else if (menuindex > 2) { menuindex = 0; switchposition.Y = 175; } } if (menuindex == 0) option1rc = new Rectangle(0, 60, 300, 60); else { option1rc = new Rectangle(0, 0, 300, 60); } if (menuindex == 1) option2rc = new Rectangle(0, 60, 360, 60); else { option2rc = new Rectangle(0, 0, 360, 60); } // if (menuindex == 2) // option3rc = new Rectangle(0, 60, 360, 60); // else { option3rc = new Rectangle(0, 0, 360, 60); } if (menuindex == 2) option4rc = new Rectangle(0, 60, 480, 60); else { option4rc = new Rectangle(0, 0, 480, 60); } if (newstate.IsKeyDown(Keys.Up) && oldstate.IsKeyUp(Keys.Up)) { menuindex--; switchposition.Y -= 75; if (menuindex < 0) { menuindex = 2; switchposition.Y = 475; } else if (menuindex > 2) { menuindex = 0; switchposition.Y = 175; } } // switch sound and music volume if (SoundEffect.MasterVolume < 0.2f) SoundEffect.MasterVolume = 0; if (MediaPlayer.Volume < 0.2f) MediaPlayer.Volume = 0; if (newstate.IsKeyUp(Keys.Right) && oldstate.IsKeyDown(Keys.Right)) { switch (menuindex) { case 0: if(SoundEffect.MasterVolume <= 0.8f) { SoundEffect.MasterVolume += 0.2f; sample.Play(); for(int i = 0; i< parameters.Length - 1; i++) { if (parameters[i].Contains("sfx")) parameters[i] = "sfx: " + Convert.ToString(SoundEffect.MasterVolume) + ";"; } StreamWriter sfxwriter = new StreamWriter(@"params.ini"); for (int i = 0; i < parameters.Length - 1; i++) sfxwriter.WriteLine(parameters[i]); sfxwriter.Close(); } break; case 1: if(MediaPlayer.Volume <= 0.8f) { MediaPlayer.Volume += 0.2f; for (int i = 0; i < parameters.Length - 1; i++) { if (parameters[i].Contains("music")) parameters[i] = "music: " + Convert.ToString(MediaPlayer.Volume) + ";"; } StreamWriter musicwriter = new StreamWriter(@"params.ini"); for (int i = 0; i < parameters.Length - 1; i++) musicwriter.WriteLine(parameters[i]); musicwriter.Close(); } break; case 2: break; case 3: break; } } if (newstate.IsKeyUp(Keys.Left) && oldstate.IsKeyDown(Keys.Left)) { switch (menuindex) { case 0: { // prevent digit format exception if (SoundEffect.MasterVolume > 0.2f) SoundEffect.MasterVolume -= 0.2f; else { SoundEffect.MasterVolume = 0.0f; } sample.Play(); for (int i = 0; i < parameters.Length - 1; i++) { if (SoundEffect.MasterVolume > 0.2f) { if (parameters[i].Contains("sfx")) parameters[i] = "sfx: " + Convert.ToString(SoundEffect.MasterVolume) + ";"; } else { if (parameters[i].Contains("sfx")) parameters[i] = "sfx: 0;"; } } StreamWriter sfxwriter = new StreamWriter(@"params.ini"); for (int i = 0; i < parameters.Length - 1; i++) sfxwriter.WriteLine(parameters[i]); sfxwriter.Close(); } break; case 1: { if (MediaPlayer.Volume > 0.2f) MediaPlayer.Volume -= 0.2f; // write 0 float as 0 to params file else { MediaPlayer.Volume = 0.0f; } for (int i = 0; i < parameters.Length - 1; i++) { if (MediaPlayer.Volume > 0.2f) { if (parameters[i].Contains("music")) parameters[i] = "music: " + Convert.ToString(MediaPlayer.Volume) + ";"; } else { if (parameters[i].Contains("music")) parameters[i] = "music: 0;"; } } StreamWriter musicwriter = new StreamWriter(@"params.ini"); for (int i = 0; i < parameters.Length - 1; i++) musicwriter.WriteLine(parameters[i]); musicwriter.Close(); } break; case 2: break; case 3: break; } } if (newstate.IsKeyUp(Keys.Enter) && oldstate.IsKeyDown(Keys.Enter)) { switch (menuindex) { case 0: { } break; case 1: break; case 3: break; case 2: index = 1; break; } } oldstate = newstate; if (volume > 8) volume = 8; if (volume < 1) volume = 0; if (fade) { timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds; if (timer >= 1 && colour.R > 2 && colour.G > 2 && colour.B > 2) { timer = 0; colour.R -= 2; colour.G -= 2; colour.B -= 2; if (colour.R <= 2 && colour.G <= 2 && colour.B <= 2) { if (menuindex == 0) index = 1; else if (quit) { exit = true; } } } if (next) { } } } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(menutexture, position, menurectangle, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option1tx, new Vector2(95, 150), option1rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option2tx, new Vector2(95, 225), option2rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); // spriteBatch.Draw(option3tx, new Vector2(85, 300), option3rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option4tx, new Vector2(775, 725), option4rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(sfxtexture, new Vector2(505, 150), sfxrectangle, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(mustexture, new Vector2(505, 225), musrectangle, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); } } class LoadGame : Menu { public LoadGame(Texture2D texture, Texture2D cursor, Texture2D opt1tx, Vector2 newposition, Vector2 switchpos, int newframewidth, int newframeheight, int index) { menutexture = texture; framewidth = newframewidth; frameheight = newframeheight; menurectangle = new Rectangle(0, 0, framewidth, frameheight); colour = new Color(255, 255, 255); menuindex = 0; switchtx = cursor; switchrc = new Rectangle(0, 0, 94, 48); switchposition = switchpos; // menu points option1tx = opt1tx; } public void Update(GameTime gameTime) { KeyboardState newstate = Keyboard.GetState(); // switch between menu points if (newstate.IsKeyDown(Keys.Up) && oldstate.IsKeyUp(Keys.Up)) { menuindex--; switchposition.Y -= 75; if (menuindex < 0) { menuindex = 1; switchposition.Y = 475; } else if (menuindex > 1) { menuindex = 0; switchposition.Y = 175; } } if (newstate.IsKeyDown(Keys.Down) && oldstate.IsKeyUp(Keys.Down)) { menuindex++; switchposition.Y += 75; if (menuindex < 0) { menuindex = 1; switchposition.Y = 475; } else if (menuindex > 1) { menuindex = 0; switchposition.Y = 175; } } if (menuindex == 1) option1rc = new Rectangle(0, 60, 480, 60); else { option1rc = new Rectangle(0, 0, 480, 60); } /* if (menuindex == 1) option2rc = new Rectangle(0, 60, 360, 60); else { option2rc = new Rectangle(0, 0, 360, 60); } if (menuindex == 2) option3rc = new Rectangle(0, 60, 360, 60); else { option3rc = new Rectangle(0, 0, 360, 60); } if (menuindex == 3) option4rc = new Rectangle(0, 60, 480, 60); else { option4rc = new Rectangle(0, 0, 480, 60); } */ if (newstate.IsKeyUp(Keys.Enter) && oldstate.IsKeyDown(Keys.Enter)) { switch (menuindex) { case 0: break; case 1: index = 1; break; } } oldstate = newstate; } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(menutexture, position, menurectangle, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option1tx, new Vector2(775, 725), option1rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); } } class AuthorsMenu : Menu { public AuthorsMenu(Texture2D texture, Texture2D cursor, Texture2D opt1tx, Vector2 newposition, Vector2 switchpos, int newframewidth, int newframeheight, int index) { menutexture = texture; framewidth = newframewidth; frameheight = newframeheight; menurectangle = new Rectangle(0, 0, framewidth, frameheight); colour = new Color(255, 255, 255); menuindex = 0; switchtx = cursor; switchrc = new Rectangle(0, 0, 94, 48); switchposition = switchpos; // menu points option1tx = opt1tx; } public void Update(GameTime gameTime) { KeyboardState newstate = Keyboard.GetState(); // switch between menu points if (newstate.IsKeyDown(Keys.Up) && oldstate.IsKeyUp(Keys.Up)) { menuindex--; switchposition.Y -= 75; if (menuindex < 0) { menuindex = 1; switchposition.Y = 475; } else if (menuindex > 1) { menuindex = 0; switchposition.Y = 175; } } if (newstate.IsKeyDown(Keys.Down) && oldstate.IsKeyUp(Keys.Down)) { menuindex++; switchposition.Y += 75; if (menuindex < 0) { menuindex = 1; switchposition.Y = 475; } else if (menuindex > 1) { menuindex = 0; switchposition.Y = 175; } } if (menuindex == 1) option1rc = new Rectangle(0, 60, 480, 60); else { option1rc = new Rectangle(0, 0, 480, 60); } /* if (menuindex == 1) option2rc = new Rectangle(0, 60, 360, 60); else { option2rc = new Rectangle(0, 0, 360, 60); } if (menuindex == 2) option3rc = new Rectangle(0, 60, 360, 60); else { option3rc = new Rectangle(0, 0, 360, 60); } if (menuindex == 3) option4rc = new Rectangle(0, 60, 480, 60); else { option4rc = new Rectangle(0, 0, 480, 60); } */ if (newstate.IsKeyUp(Keys.Enter) && oldstate.IsKeyDown(Keys.Enter)) { switch (menuindex) { case 0: break; case 1: index = 1; break; } } oldstate = newstate; } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(menutexture, position, menurectangle, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); spriteBatch.Draw(option1tx, new Vector2(775, 725), option1rc, colour, 0f, originalposition, 1.0f, SpriteEffects.None, 0); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ProyectoMIPS; namespace ProyectoMIPS.Forms { public partial class Resultados : Form { Queue<hilillo> hilillos; int[] memoriaDatos; public Resultados(Queue<hilillo> h, int[] md) { hilillos = h; memoriaDatos = md; InitializeComponent(); } public void Resultados_Load(object sender, EventArgs e) { this.CenterToScreen(); tregistros1.ReadOnly = true; tregistros2.ReadOnly = true; tregistros3.ReadOnly = true; tmemoria.ReadOnly = true; chilillo1.Items.Add("Seleccione"); chilillo2.Items.Add("Seleccione"); chilillo3.Items.Add("Seleccione"); chilillo1.SelectedIndex = 0; chilillo2.SelectedIndex = 0; chilillo3.SelectedIndex = 0; for (int i = 0; i < hilillos.Count; i++) { int numero_hilo = hilillos.ElementAt(i).obtener_numero_nucleo(); int numero_hilillo = hilillos.ElementAt(i).obtener_numero_hil(); if (numero_hilo == 0) chilillo1.Items.Add(numero_hilillo); else if(numero_hilo == 1) chilillo2.Items.Add(numero_hilillo); else if(numero_hilo == 2) chilillo3.Items.Add(numero_hilillo); } string mem = ""; for (int i = 0; i < 96; i++) mem = mem + " " + memoriaDatos[i]; tmemoria.Text = mem; } public void chilillo1_SelectedIndexChanged(object sender, EventArgs e) { hilillo auxiilar; string reg = ""; if (chilillo1.SelectedIndex != 0) { for (int i = 0; i < hilillos.Count; i++) { if (hilillos.ElementAt(i).obtener_numero_hil().ToString() == chilillo1.SelectedItem.ToString()) { auxiilar = hilillos.ElementAt(i); int[] registros = auxiilar.obtener_registros(); for (int j = 0; j < registros.Length; j++) reg = reg + "R" + j + ": " + registros[j] + " \n"; i = hilillos.Count; } } } tregistros1.Text = reg; } public void chilillo2_SelectedIndexChanged(object sender, EventArgs e) { if (chilillo2.SelectedIndex != 0) { hilillo auxiilar; for (int i = 0; i < hilillos.Count; i++) { if (hilillos.ElementAt(i).obtener_numero_hil().ToString() == chilillo2.SelectedItem.ToString()) { auxiilar = hilillos.ElementAt(i); string reg = ""; int[] registros = auxiilar.obtener_registros(); for (int j = 0; j < registros.Length; j++) { reg = reg + "R" + j + ": " + registros[j] + "\n"; } tregistros2.Text = reg; i = hilillos.Count; } } } } public void chilillo3_SelectedIndexChanged(object sender, EventArgs e) { if (chilillo3.SelectedIndex != 0) { hilillo auxiilar; for (int i = 0; i < hilillos.Count; i++) { if (hilillos.ElementAt(i).obtener_numero_hil().ToString() == chilillo3.SelectedItem.ToString()) { auxiilar = hilillos.ElementAt(i); string reg = ""; int[] registros = auxiilar.obtener_registros(); for (int j = 0; j < registros.Length; j++) { reg = reg + "R" + j + ": " + registros[j] + "\n"; } tregistros3.Text = reg; i = hilillos.Count; } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ECommerceApp.Core.Models; namespace ECommerceApp.Core.Interfaces { public interface ICatalogRepository { void AddCatalog(string name , string description); void UpdateCatalog(Guid Id, Catalog ca); Catalog FindById(Guid Id); void RemoveCatalog(Guid Id); IEnumerable GetCatalogs(); } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Discovery.Core.UI.Converters { /// <summary> /// string 类型和 BitmapImage 类型的值转换器 /// </summary> [ValueConversion(typeof(string), typeof(BitmapImage))] public class NullImageConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) => value ?? DependencyProperty.UnsetValue; public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) => Binding.DoNothing; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.EntityFrameworkCore; using AspNetCoreTodo.Data; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using AspNetCoreTodo.Services; namespace ASP_to_do { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. /// <summary> /// Declaring (or "wiring up") which concrete class to use for each interface. /// </summary> /// <param name="services">adding things to the service container, /// or the collection of services that ASP.NET Core knows about</param> public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddControllersWithViews(); services.AddRazorPages(); /// <summary> /// Telling ASP.NET Core to use FakeTodoItemService whenever ITodoItemService interface is requested. /// AddSingleton means that only one copy of the FakeTodoItemService is created, /// and it's reused whenever the service is requested. /// </summary> /// <typeparam name="ITodoItemService">what the controller asks for</typeparam> /// <typeparam name="FakeTodoItemService">what ASP.NET Core automatically supply</typeparam> /// <returns></returns> services.AddSingleton<ITodoItemService, FakeTodoItemService>(); /// <summary> /// Establishing a connection to database. /// </summary> /// <typeparam name="ApplicationDbContext">which context, connection string, database to use</typeparam> /// <returns></returns> services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); /// <summary> /// Updating service container: the new instance of TodoItemService will be created during each web request /// </summary> /// <typeparam name="ITodoItemService">the service class that interact with database</typeparam> /// <typeparam name="TodoItemService">replace FakeTodoItemService</typeparam> /// <returns></returns> services.AddScoped<ITodoItemService, TodoItemService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; class WebSocketsGuedes { public static void Run() { TcpListener server = new TcpListener(IPAddress.Loopback, 8181); server.Start(); using (TcpClient client = server.AcceptTcpClient()) using (NetworkStream clientStream = client.GetStream()) using (StreamReader sr = new StreamReader(clientStream)) using (StreamWriter sw = new StreamWriter(clientStream)) { Console.WriteLine(sr.ReadLine()); Console.WriteLine(sr.ReadLine()); Console.WriteLine(sr.ReadLine()); Console.WriteLine(sr.ReadLine()); Console.WriteLine(sr.ReadLine()); Console.WriteLine(sr.ReadLine()); sw.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake"); sw.WriteLine("Upgrade: WebSocket"); sw.WriteLine("Connection: Upgrade"); sw.WriteLine("WebSocket-Origin: http://localhost:8080"); sw.WriteLine("WebSocket-Location: ws://localhost:8181/websession"); sw.WriteLine(""); sw.Flush(); // Accept send while (true) { // read type byte byte type = (byte)clientStream.ReadByte(); if (type != 0x00) { Console.Error.WriteLine("Erro no protocolo: The type byte was not 0x00"); break; } byte[] sendData = new byte[1024]; byte sendDataByte; int sendDataIdx = 0; while ((sendDataByte = (byte)clientStream.ReadByte()) != 0xFF) { sendData[sendDataIdx++] = sendDataByte; } String text = System.Text.ASCIIEncoding.Default.GetString(sendData, 0, sendDataIdx); Console.WriteLine("LINE: " + text); // Write down message ECHO clientStream.WriteByte(0x00); sw.Write(text.ToUpper()); sw.Flush(); clientStream.WriteByte(0xFF); } } server.Stop(); } }
using PatientInformationSystem.Server.Application.Models.Authentication; namespace PatientInformationSystem.Server.Application.IServices { public interface IAuthenticationService { public AuthenticationResponse? Authenticate(AuthenticationRequest authenticationRequest); } }
using ComputerBuilderSystem.Contracts; namespace ComputerBuilderSystem.SystemTypes { public class PersonalComputer : BaseSystem, IPcSystem { public PersonalComputer(IMotherboard motherboard, ICentralProcessingUnit cpu, IDiskDrive diskDrive) :base (motherboard, cpu, diskDrive) { } public void Play(int guessNumber) { int number = this.Cpu.Rand(1, 10); if (number + 1 != guessNumber + 1) { this.Motherboard.DrawOnVideoCard(string.Format("You didn't guess the number {0}.", number)); } else { this.Motherboard.DrawOnVideoCard("You win!"); } } } }
using System; using System.Collections.Generic; using System.Text; namespace StringSubString.Classes { public class MatchSubString { public bool MatchSubStringBool(string s1, string s2) { int s1Len = s1.Length; int s2Len = s2.Length; int i; for (i = 0; i <= s2Len - s1Len; i++) { int j; for (j = 0; j < s1Len; j++) { if (s2[i + j] != s1[j]) break; } if (j == s1Len) return true; } return false; } } }
using ModernCSApp.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.ApplicationSettings; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace ModernCSApp.MVVM.Views.Settings { public sealed partial class HelpSupport : UserControl { public SettingsViewModel _vm { get; set; } public HelpSupport() { this.InitializeComponent(); _vm = new SettingsViewModel(); this.DataContext = _vm; } private void grdBack_PointerPressed(object sender, PointerRoutedEventArgs e) { if (this.Parent.GetType() == typeof(Popup)) { ((Popup)this.Parent).IsOpen = false; } SettingsPane.Show(); } } }
using System; using System.Runtime.InteropServices; using gdalconst_csharp_core; namespace OSGeo.GDAL { public class Dataset : MajorObject { private HandleRef swigCPtr; public int RasterCount { get { int num = GdalPINVOKE.Dataset_RasterCount_get(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return num; } } public int RasterXSize { get { int num = GdalPINVOKE.Dataset_RasterXSize_get(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return num; } } public int RasterYSize { get { int num = GdalPINVOKE.Dataset_RasterYSize_get(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return num; } } public Dataset(IntPtr cPtr, bool cMemoryOwn, object parent) : base(GdalPINVOKE.DatasetUpcast(cPtr), cMemoryOwn, parent) { this.swigCPtr = new HandleRef(this, cPtr); } private IntPtr __AllocCArray_GDAL_GCP(int size) { IntPtr intPtr = GdalPINVOKE.Dataset___AllocCArray_GDAL_GCP(this.swigCPtr, size); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return intPtr; } private void __FreeCArray_GDAL_GCP(IntPtr carray) { GdalPINVOKE.Dataset___FreeCArray_GDAL_GCP(this.swigCPtr, carray); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } } private IntPtr __GetGCPs() { IntPtr intPtr = GdalPINVOKE.Dataset___GetGCPs(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return intPtr; } private GCP __ReadCArrayItem_GDAL_GCP(IntPtr carray, int index) { GCP gCP; IntPtr intPtr = GdalPINVOKE.Dataset___ReadCArrayItem_GDAL_GCP(this.swigCPtr, carray, index); if (intPtr == IntPtr.Zero) { gCP = null; } else { gCP = new GCP(intPtr, false, base.ThisOwn_false()); } GCP gCP1 = gCP; if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return gCP1; } private CPLErr __SetGCPs(int nGCPs, IntPtr pGCPs, string pszGCPProjection) { CPLErr cPLErr = (CPLErr)GdalPINVOKE.Dataset___SetGCPs(this.swigCPtr, nGCPs, pGCPs, pszGCPProjection); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return cPLErr; } private void __WriteCArrayItem_GDAL_GCP(IntPtr carray, int index, GCP value) { GdalPINVOKE.Dataset___WriteCArrayItem_GDAL_GCP(this.swigCPtr, carray, index, GCP.getCPtr(value)); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } } public CPLErr AddBand(DataType datatype, string[] options) { IntPtr[] stringListMarshal; HandleRef handleRef = this.swigCPtr; DataType dataType = datatype; if (options != null) { stringListMarshal = (new GdalPINVOKE.StringListMarshal(options))._ar; } else { stringListMarshal = null; } CPLErr cPLErr = (CPLErr)GdalPINVOKE.Dataset_AddBand(handleRef, (int)dataType, stringListMarshal); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return cPLErr; } public int BuildOverviews(string resampling, int[] overviewlist, Gdal.GDALProgressFuncDelegate callback, string callback_data) { int num; if ((int)overviewlist.Length <= 0) { throw new ArgumentException("overviewlist size is small (BuildOverviews)"); } IntPtr intPtr = Marshal.AllocHGlobal((int)overviewlist.Length * Marshal.SizeOf(overviewlist[0])); try { Marshal.Copy(overviewlist, 0, intPtr, (int)overviewlist.Length); num = this.BuildOverviews(resampling, (int)overviewlist.Length, intPtr, callback, callback_data); } finally { Marshal.FreeHGlobal(intPtr); } GC.KeepAlive(this); return num; } public int BuildOverviews(string resampling, int[] overviewlist) { return this.BuildOverviews(resampling, overviewlist, null, null); } public int BuildOverviews(string resampling, int overviewlist, IntPtr pOverviews, Gdal.GDALProgressFuncDelegate callback, string callback_data) { int num = GdalPINVOKE.Dataset_BuildOverviews(this.swigCPtr, resampling, overviewlist, pOverviews, callback, callback_data); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return num; } public CPLErr CreateMaskBand(int nFlags) { CPLErr cPLErr = (CPLErr)GdalPINVOKE.Dataset_CreateMaskBand(this.swigCPtr, nFlags); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return cPLErr; } public override void Dispose() { lock (this) { if ((this.swigCPtr.Handle == IntPtr.Zero ? false : this.swigCMemOwn)) { this.swigCMemOwn = false; GdalPINVOKE.delete_Dataset(this.swigCPtr); } this.swigCPtr = new HandleRef(null, IntPtr.Zero); GC.SuppressFinalize(this); base.Dispose(); } } ~Dataset() { this.Dispose(); } public void FlushCache() { GdalPINVOKE.Dataset_FlushCache(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } } public static HandleRef getCPtr(Dataset obj) { return (obj == null ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr); } public static HandleRef getCPtrAndDisown(Dataset obj, object parent) { HandleRef handleRef; if (obj == null) { handleRef = new HandleRef(null, IntPtr.Zero); } else { obj.swigCMemOwn = false; obj.swigParentRef = parent; handleRef = obj.swigCPtr; } return handleRef; } public static HandleRef getCPtrAndSetReference(Dataset obj, object parent) { HandleRef handleRef; if (obj == null) { handleRef = new HandleRef(null, IntPtr.Zero); } else { obj.swigParentRef = parent; handleRef = obj.swigCPtr; } return handleRef; } public Driver GetDriver() { Driver driver; IntPtr intPtr = GdalPINVOKE.Dataset_GetDriver(this.swigCPtr); if (intPtr == IntPtr.Zero) { driver = null; } else { driver = new Driver(intPtr, false, base.ThisOwn_false()); } Driver driver1 = driver; if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return driver1; } public string[] GetFileList() { string stringAnsi; IntPtr intPtr = GdalPINVOKE.Dataset_GetFileList(this.swigCPtr); int num = 0; if (intPtr != IntPtr.Zero) { while (Marshal.ReadIntPtr(intPtr, num * IntPtr.Size) != IntPtr.Zero) { num++; } } string[] strArrays = new string[num]; if (num > 0) { for (int i = 0; i < num; i++) { IntPtr intPtr1 = Marshal.ReadIntPtr(intPtr, i * Marshal.SizeOf(typeof(IntPtr))); string[] strArrays1 = strArrays; int num1 = i; if (intPtr1 == IntPtr.Zero) { stringAnsi = null; } else { stringAnsi = Marshal.PtrToStringAnsi(intPtr1); } strArrays1[num1] = stringAnsi; } } if (intPtr != IntPtr.Zero) { GdalPINVOKE.StringListDestroy(intPtr); } if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return strArrays; } public int GetGCPCount() { int num = GdalPINVOKE.Dataset_GetGCPCount(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return num; } public string GetGCPProjection() { string str = GdalPINVOKE.Dataset_GetGCPProjection(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return str; } public GCP[] GetGCPs() { IntPtr intPtr = this.__GetGCPs(); int gCPCount = this.GetGCPCount(); GCP[] gCPArray = null; if ((intPtr == IntPtr.Zero ? false : gCPCount > 0)) { gCPArray = new GCP[gCPCount]; for (int i = 0; i < gCPCount; i++) { gCPArray[i] = this.__ReadCArrayItem_GDAL_GCP(intPtr, i); } } GC.KeepAlive(this); return gCPArray; } public void GetGeoTransform(double[] argout) { GdalPINVOKE.Dataset_GetGeoTransform(this.swigCPtr, argout); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } } public string GetProjection() { string str = GdalPINVOKE.Dataset_GetProjection(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return str; } public string GetProjectionRef() { string str = GdalPINVOKE.Dataset_GetProjectionRef(this.swigCPtr); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return str; } public Band GetRasterBand(int nBand) { Band band; IntPtr intPtr = GdalPINVOKE.Dataset_GetRasterBand(this.swigCPtr, nBand); if (intPtr == IntPtr.Zero) { band = null; } else { band = new Band(intPtr, false, base.ThisOwn_false()); } Band band1 = band; if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return band1; } public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, byte[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.ReadRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Byte, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, short[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.ReadRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Int16, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, int[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.ReadRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Int32, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, float[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.ReadRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Float32, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, double[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.ReadRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Float64, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, IntPtr buffer, int buf_xSize, int buf_ySize, DataType buf_type, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr = (CPLErr)GdalPINVOKE.Dataset_ReadRaster(this.swigCPtr, xOff, yOff, xSize, ySize, buffer, buf_xSize, buf_ySize, (int)buf_type, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return cPLErr; } public CPLErr SetGCPs(GCP[] pGCPs, string pszGCPProjection) { CPLErr cPLErr = CPLErr.CE_None; if ((pGCPs == null ? false : (int)pGCPs.Length > 0)) { IntPtr intPtr = this.__AllocCArray_GDAL_GCP((int)pGCPs.Length); if (intPtr == IntPtr.Zero) { throw new Exception("Error allocating CArray with __AllocCArray_GDAL_GCP"); } try { for (int i = 0; i < (int)pGCPs.Length; i++) { this.__WriteCArrayItem_GDAL_GCP(intPtr, i, pGCPs[i]); } cPLErr = this.__SetGCPs((int)pGCPs.Length, intPtr, pszGCPProjection); } finally { this.__FreeCArray_GDAL_GCP(intPtr); } } GC.KeepAlive(this); return cPLErr; } public CPLErr SetGeoTransform(double[] argin) { CPLErr cPLErr = (CPLErr)GdalPINVOKE.Dataset_SetGeoTransform(this.swigCPtr, argin); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return cPLErr; } public CPLErr SetProjection(string prj) { CPLErr cPLErr = (CPLErr)GdalPINVOKE.Dataset_SetProjection(this.swigCPtr, prj); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return cPLErr; } public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, byte[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.WriteRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Byte, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, short[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.WriteRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Int16, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, int[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.WriteRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Int32, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, float[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.WriteRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Float32, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, double[] buffer, int buf_xSize, int buf_ySize, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr; GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { cPLErr = this.WriteRaster(xOff, yOff, xSize, ySize, gCHandle.AddrOfPinnedObject(), buf_xSize, buf_ySize, DataType.GDT_Float64, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); } finally { gCHandle.Free(); } GC.KeepAlive(this); return cPLErr; } public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, IntPtr buffer, int buf_xSize, int buf_ySize, DataType buf_type, int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { CPLErr cPLErr = (CPLErr)GdalPINVOKE.Dataset_WriteRaster(this.swigCPtr, xOff, yOff, xSize, ySize, buffer, buf_xSize, buf_ySize, (int)buf_type, bandCount, bandMap, pixelSpace, lineSpace, bandSpace); if (GdalPINVOKE.SWIGPendingException.Pending) { throw GdalPINVOKE.SWIGPendingException.Retrieve(); } return cPLErr; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LibraryManagementSystem { public partial class MemberPage : Form { //Object of TAB public MemberHome memberHome = new MemberHome(); public Search search = new Search(); public MemberPage() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { Application.Exit(); } private void panel12_Click(object sender, EventArgs e) { if (panel2.Width == 50) { panel2.Width = 264; panel12.Visible = false; panel13.Visible = true; panel14.Visible = false; panel22.Visible = true; panel3.Width = 264; panel4.Width = 264; panel5.Width = 264; panel6.Width = 264; panel7.Width = 264; panel8.Width = 264; panel9.Width = 264; } } private void panel13_Click(object sender, EventArgs e) { if (panel2.Width == 264) { panel2.Width = 50; panel12.Visible = true; panel13.Visible = false; panel14.Visible = true; panel22.Visible = false; } } private void panel9_Paint(object sender, PaintEventArgs e) { if (panel2.Width == 50) { panel9.Width = 50; } else { panel9.Width = 264; } } private void panel8_Paint(object sender, PaintEventArgs e) { if (panel2.Width == 50) { panel8.Width = 50; } else { panel9.Width = 264; } } private void panel7_Paint(object sender, PaintEventArgs e) { if (panel2.Width == 50) { panel7.Width = 50; } else { panel9.Width = 264; } } private void panel6_Paint(object sender, PaintEventArgs e) { if (panel2.Width == 50) { panel6.Width = 50; } else { panel9.Width = 264; } } private void panel5_Paint(object sender, PaintEventArgs e) { if (panel2.Width == 50) { panel5.Width = 50; } else { panel9.Width = 264; } } private void panel4_Paint(object sender, PaintEventArgs e) { if (panel2.Width == 50) { panel4.Width = 50; } else { panel9.Width = 264; } } private void panel3_Paint(object sender, PaintEventArgs e) { if (panel2.Width == 50) { panel3.Width = 50; } else { panel9.Width = 264; } } Point lastclick; private void panel1_MouseDown(object sender, MouseEventArgs e) { lastclick = e.Location; } private void panel1_MouseMove(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Left) { this.Left += e.X - lastclick.X; this.Top += e.Y - lastclick.Y; } } private void panel3_MouseHover(object sender, EventArgs e) { panel3.BackColor = Color.DarkCyan; } private void panel4_MouseHover(object sender, EventArgs e) { panel4.BackColor = Color.DarkCyan; } private void panel5_MouseHover(object sender, EventArgs e) { panel5.BackColor = Color.DarkCyan; } private void panel6_MouseHover(object sender, EventArgs e) { panel6.BackColor = Color.DarkCyan; } private void panel7_MouseHover(object sender, EventArgs e) { panel7.BackColor = Color.DarkCyan; } private void panel8_MouseHover(object sender, EventArgs e) { panel8.BackColor = Color.DarkCyan; } private void panel9_MouseHover(object sender, EventArgs e) { panel9.BackColor = Color.DarkCyan; } private void panel3_MouseLeave(object sender, EventArgs e) { panel3.BackColor = Color.Teal; } private void panel4_MouseLeave(object sender, EventArgs e) { panel4.BackColor = Color.Teal; } private void panel5_MouseLeave(object sender, EventArgs e) { panel5.BackColor = Color.Teal; } private void panel6_MouseLeave(object sender, EventArgs e) { panel6.BackColor = Color.Teal; } private void panel7_MouseLeave(object sender, EventArgs e) { panel7.BackColor = Color.Teal; } private void panel8_MouseLeave(object sender, EventArgs e) { panel8.BackColor = Color.Teal; } private void panel9_MouseLeave(object sender, EventArgs e) { panel9.BackColor = Color.Teal; } private void label9_MouseDown(object sender, MouseEventArgs e) { lastclick = e.Location; } private void label9_MouseMove(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Left) { this.Left += e.X - lastclick.X; this.Top += e.Y - lastclick.Y; } } private void panel23_MouseDown(object sender, MouseEventArgs e) { lastclick = e.Location; } private void panel23_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Left += e.X - lastclick.X; this.Top += e.Y - lastclick.Y; } } private void panel15_Click(object sender, EventArgs e) { Search search = new Search(); search.TopLevel = false; search.AutoScroll = true; Body.Controls.Add(search); search.Dock = DockStyle.Fill; search.Show(); } private void label10_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Maximized; } private void Body_Click(object sender, EventArgs e) { } private void panel15_Click_1(object sender, EventArgs e) { memberHome.Hide(); search.TopLevel = false; search.AutoScroll = true; Body.Controls.Add(search); search.Dock = DockStyle.Fill; search.Show(); } private void Body_Paint(object sender, PaintEventArgs e) { memberHome.TopLevel = false; memberHome.AutoScroll = true; Body.Controls.Add(memberHome); memberHome.Dock = DockStyle.Fill; memberHome.Show(); } private void label10_Click_1(object sender, EventArgs e) { this.WindowState = FormWindowState.Maximized; } private void label11_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } } }
using System; namespace SharpPcap { /// <summary> /// A PcapDevice or dumpfile is not ready for capture operations. /// </summary> public class PcapDeviceNotReadyException : PcapException { internal PcapDeviceNotReadyException() : base() { } internal PcapDeviceNotReadyException(string msg) : base(msg) { } } }
using System.Linq; using Cogent.IoC.Generators.Extensions; using Microsoft.CodeAnalysis; namespace Cogent.IoC.Generators.Models { internal class ContainerClassDescription { public ContainerClassDescription(ITypeSymbol[] containerTypeInstances) { FullyQualifiedName = containerTypeInstances.First()?.FullyQualifiedTypeName(); FullyQualifiedNamespace = containerTypeInstances.First()?.ContainingNamespace.FullyQualifiedNamespace(); ShortName = containerTypeInstances.First()?.Name; AllInterfaces = containerTypeInstances.SelectMany(c => c.AllInterfaces).ToArray(); AllAttributes = containerTypeInstances.SelectMany(c => c.GetAttributes()).ToArray(); } public INamedTypeSymbol[] AllInterfaces { get; } public AttributeData[] AllAttributes { get; } public string FullyQualifiedName { get; } public string FullyQualifiedNamespace { get; } public string ShortName { get; } } }
using UnityEngine; using System.Collections; public class ExerciseNotes : MonoBehaviour { [TextArea(3, 20)] public string exerciseNoteText; }
using ClassLibrary1; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; namespace WebApplication5.welcome { public partial class Instorage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Databind(); } } public static List<ClassLibrary1.Instorage> getXmlData() { String xmlPath = Util.filePath + "Instorage.xml"; var xdoc = XDocument.Load(xmlPath); var query = (from item in xdoc.Descendants("Instorage") select new ClassLibrary1.Instorage() { serial = item.Element("serial").Value, isbn = item.Element("isbn").Value, purchase = item.Element("purchase").Value, num = item.Element("num").Value, price = item.Element("price").Value, totPrice = item.Element("totPrice").Value, }).ToList(); return query; } public void Databind() { var query = getXmlData(); GridView1.DataSource = query; GridView1.DataBind(); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { } protected void addInstorage_Click(object sender, EventArgs e) { Response.Redirect("addInstorage.aspx"); } } }
using PlatformRacing3.Server.API.Game.Commands; using PlatformRacing3.Server.Game.Client; namespace PlatformRacing3.Server.Game.Commands.Selector; internal sealed class OnlineCommandTargetSelector : ICommandTargetSelector { private readonly ClientManager clientManager; internal OnlineCommandTargetSelector(ClientManager clientManager) { this.clientManager = clientManager; } public IEnumerable<ClientSession> FindTargets(ICommandExecutor executor, string parameter) => this.clientManager.LoggedInUsers; }
/* 3. Write a program that reads from the console a sequence of N integer numbers and returns the minimal and maximal of them. */ using System; class MinimalAndMaximal { static void Main() { Console.Write("Please input how many integers you want to enter: "); int numbers; int.TryParse(Console.ReadLine(), out numbers); int minimal = 0, maximal = 0; for (int i = 0; i < numbers; i++) { int currentNumber; int.TryParse(Console.ReadLine(), out currentNumber); if (i == 0) { minimal = currentNumber; maximal = currentNumber; } else { if (currentNumber > maximal) { maximal = currentNumber; } else if (minimal > currentNumber) { minimal = currentNumber; } } } Console.WriteLine("The minimal number is: {0}", minimal); Console.WriteLine("The maximal number is: {0}", maximal); } }
namespace Hearthbuddy.Controls { using System; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Controls; using System.Windows.Input; [TemplatePart(Name="SplitElement", Type=typeof(UIElement))] public class SplitButton : Button { [CompilerGenerated] private bool bool_0; private ContextMenu contextMenu_0; private DependencyObject dependencyObject_0; private ObservableCollection<object> observableCollection_0 = new ObservableCollection<object>(); private Point point_0; private const string string_0 = "SplitElement"; private UIElement uielement_0; public SplitButton() { base.DefaultStyleKey = typeof(SplitButton); } private void contextMenu_0_Closed(object sender, RoutedEventArgs e) { base.LayoutUpdated -= new EventHandler(this.SplitButton_LayoutUpdated); base.Focus(); } private void contextMenu_0_Opened(object sender, RoutedEventArgs e) { this.point_0 = base.TranslatePoint(new Point(0.0, base.ActualHeight), this.contextMenu_0); this.method_0(); base.LayoutUpdated += new EventHandler(this.SplitButton_LayoutUpdated); } private void method_0() { Point point = new Point(); Point point2 = this.point_0; this.contextMenu_0.HorizontalOffset = point2.X - point.X; this.contextMenu_0.VerticalOffset = point2.Y - point.Y; if (FlowDirection.RightToLeft == base.FlowDirection) { this.contextMenu_0.HorizontalOffset *= -1.0; } } public override void OnApplyTemplate() { if (this.uielement_0 != null) { this.uielement_0.MouseEnter -= new MouseEventHandler(this.uielement_0_MouseEnter); this.uielement_0.MouseLeave -= new MouseEventHandler(this.uielement_0_MouseLeave); this.uielement_0 = null; } if (this.contextMenu_0 != null) { this.contextMenu_0.Opened -= new RoutedEventHandler(this.contextMenu_0_Opened); this.contextMenu_0.Closed -= new RoutedEventHandler(this.contextMenu_0_Closed); this.contextMenu_0 = null; } if (this.dependencyObject_0 != null) { base.RemoveLogicalChild(this.dependencyObject_0); this.dependencyObject_0 = null; } base.OnApplyTemplate(); this.uielement_0 = base.GetTemplateChild("SplitElement") as UIElement; if (this.uielement_0 != null) { this.uielement_0.MouseEnter += new MouseEventHandler(this.uielement_0_MouseEnter); this.uielement_0.MouseLeave += new MouseEventHandler(this.uielement_0_MouseLeave); this.contextMenu_0 = ContextMenuService.GetContextMenu(this.uielement_0); if (this.contextMenu_0 != null) { this.contextMenu_0.IsOpen = true; DependencyObject current = this.contextMenu_0; do { this.dependencyObject_0 = current; current = LogicalTreeHelper.GetParent(current); } while (current != null); this.contextMenu_0.IsOpen = false; base.AddLogicalChild(this.dependencyObject_0); this.contextMenu_0.Opened += new RoutedEventHandler(this.contextMenu_0_Opened); this.contextMenu_0.Closed += new RoutedEventHandler(this.contextMenu_0_Closed); } } } protected override void OnClick() { if (this.IsMouseOverSplitElement) { this.OpenButtonMenu(); } else { base.OnClick(); } } protected override void OnKeyDown(KeyEventArgs e) { if (e == null) { throw new ArgumentNullException("e"); } if ((Key.Down != e.Key) && (Key.Up != e.Key)) { base.OnKeyDown(e); } else { base.Dispatcher.BeginInvoke(new Action(this.OpenButtonMenu), Array.Empty<object>()); } } protected void OpenButtonMenu() { if ((0 < this.observableCollection_0.Count) && (this.contextMenu_0 != null)) { this.contextMenu_0.HorizontalOffset = 0.0; this.contextMenu_0.VerticalOffset = 0.0; this.contextMenu_0.IsOpen = true; } } private void SplitButton_LayoutUpdated(object sender, EventArgs e) { this.method_0(); } private void uielement_0_MouseEnter(object sender, MouseEventArgs e) { this.IsMouseOverSplitElement = true; } private void uielement_0_MouseLeave(object sender, MouseEventArgs e) { this.IsMouseOverSplitElement = false; } public Collection<object> ButtonMenuItemsSource { get { return this.observableCollection_0; } } protected bool IsMouseOverSplitElement { [CompilerGenerated] get { return this.bool_0; } [CompilerGenerated] private set { this.bool_0 = value; } } } }
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace NetFabric.Hyperlinq { public interface IValueEnumerable<out T, out TEnumerator> : IEnumerable<T> where TEnumerator : struct , IEnumerator<T> { [return: NotNull] new TEnumerator GetEnumerator(); } public interface IValueReadOnlyCollection<out T, out TEnumerator> : IReadOnlyCollection<T> , IValueEnumerable<T, TEnumerator> where TEnumerator : struct , IEnumerator<T> { } public interface IValueReadOnlyList<out T, out TEnumerator> : IReadOnlyList<T> , IValueReadOnlyCollection<T, TEnumerator> where TEnumerator : struct , IEnumerator<T> { } public interface IValueEnumerableRef<out T, out TEnumerator> where TEnumerator : struct , IEnumeratorRef<T> { [return: NotNull] TEnumerator GetEnumerator(); } }
using UnityEngine; using System.Collections; public class CollisionHandler : MonoBehaviour { public GameObject collides_with; public GameObject spawns; public Collision collision; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter (Collider other) { //Debug.Log("touch"); /* if (other.gameObject.tag == collides_with.tag) { Instantiate(spawns, other.transform.position, Quaternion.identity); Destroy (other.gameObject); Destroy(this.gameObject); } */ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Protogame; namespace Protogame.MultiLevel { public interface IMultiLevelEntity : IEntity { Level Level { set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Methods { class Program { static void Main(string[] args) { Console.WriteLine( Bark() +" "+ Meow()+" " + One() +" " + MakeSound("Moo")+" "+ MakeTwoSounds("Whee", "Chirp")); } public static string Meow() { return "Meow!"; } public static string Bark() { string b = "Bark!"; return b; } public static int One() { return 1; } public static string MakeSound(string noise) { string punctuation = "!"; return noise + punctuation; } //Anything can be a parameter and anything can be a return type public static string MakeTwoSounds(string noise1, string noise2) { //Return passes out the data when it's called return noise1 + " " + noise2; } public static void greet() { Console.WriteLine("Hello There!"); Console.WriteLine("We're here to make animal noises!"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.ServiceModel; using System.ServiceModel.Description; using System.Threading; namespace GPSSim { public partial class Form1 : Form { System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); HtmlDocument doc; double oldLon = 0.0; double oldLat = 0.0; double oldMeters = 0.0; const int THRESHOLD = 20; //adjust how many meters before the 'beyond threshold' call is triggered const int timerInterval = 30; //adjust to how often you want to check for updates (milliseconds) public Form1() { InitializeComponent(); //setup the timer timer.Interval = timerInterval; timer.Tick += new EventHandler(timer_Tick); } void timer_Tick(object sender, EventArgs e) { string lat = "0.0"; string lon = "0.0"; try { lon = doc.GetElementById("tbLongitude").GetAttribute("Value"); //get the longitude lat = doc.GetElementById("tbLatitude").GetAttribute("Value"); //get the latitude } catch { } //if the tick event is too fast, the javascript controls haven't initialised so this exception may be caught for the first few ticks if (String.IsNullOrEmpty(lon)) lon = "0.0"; //ensure there's a correctly formatted string when app initially launches if (String.IsNullOrEmpty(lat)) lat = "0.0"; tbLatitude.Text = lat.ToString(); tbLongitude.Text = lon.ToString(); //display whether the threshold has been reached (if tick count is low, it will flash momentarily) tbThreshold.Text = CheckThreshold(oldLon, oldLat, double.Parse(lon), double.Parse(lat)).ToString(); } private void Form1_Load(object sender, EventArgs e) { //Navigate to the HTML file (add your URI) webBrowser1.Navigate(new Uri(@"file:///C:\Users\KP\Documents\Visual Studio 2010\Projects\VEMap\VEMap\map.html", UriKind.RelativeOrAbsolute)); //get the document in order to be able to access the coordinate information doc = this.webBrowser1.Document; //add event handler to let us know when the webbrowser control has loaded webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated); } void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { timer.Start(); } public bool CheckThreshold(double clon, double clat, double nLon, double nLat) { //thanks to code found here (http://forums.silverlight.net/forums/p/191064/441241.aspx#441241) clon *= Math.PI / 180; clat *= Math.PI / 180; var dstLongR = nLon * Math.PI / 180; var dstLatR = nLat * Math.PI / 180; var earthRadius = 3958.75587; var distance = Math.Acos(Math.Sin(clat) * Math.Sin(dstLatR) + Math.Cos(clat) * Math.Cos(dstLatR) * Math.Cos((dstLongR - clat))) * earthRadius; distance = Math.Floor(distance * 10) / 10; //convert miles to meters since WP7 emulator has meters threshold double meters = distance * 1609.344f; //assign the old values as the current value, so in the next loop it represents the previous value oldLat = nLat; oldLon = nLon; if (Math.Abs(meters - oldMeters) > THRESHOLD) { oldMeters = meters; return true; } else { oldMeters = meters; return false; } } public double[] GetData() { double[] data = new double[2]; data[0] = double.Parse(tbLatitude.Text); data[1] = double.Parse(tbLongitude.Text); return data; } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using CodeDiscoPlayer; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace CodeDisco { /// <summary> /// This class causes a classifier to be added to the set of classifiers. Since /// the content type is set to "text", this classifier applies to all text files /// </summary> [Export(typeof(IClassifierProvider))] [ContentType("text")] internal class CodeDiscoProvider : IClassifierProvider { /// <summary> /// Import the classification registry to be used for getting a reference /// to the custom classification type later. /// </summary> [Import] internal IClassificationTypeRegistryService ClassificationRegistry = null; // Set via MEF public IClassifier GetClassifier(ITextBuffer buffer) { return buffer.Properties.GetOrCreateSingletonProperty<CodeDisco>(delegate { return new CodeDisco(ClassificationRegistry); }); } } /// <summary> /// Classifier that classifies all text as an instance of the OrinaryClassifierType /// </summary> class CodeDisco : IClassifier { readonly IClassificationType _classificationType; readonly Router _router = new Router(new Player(), new Config()); internal CodeDisco(IClassificationTypeRegistryService registry) { _classificationType = registry.GetClassificationType("CodeDisco"); } /// <summary> /// This method scans the given SnapshotSpan for potential matches for this classification. /// In this instance, it classifies everything and returns each span as a new ClassificationSpan. /// </summary> /// <param name="span">The span currently being classified</param> /// <returns>A list of ClassificationSpans that represent spans identified to be of this classification</returns> public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) { var lastLine = GetLastLine(span); if (lastLine.Length > 0) { _router.RouteKey(lastLine.GetText()[lastLine.Length - 1]); } return new List<ClassificationSpan>(); } /// <summary> /// Get the last line included in the SnapshotSpan /// </summary> private static ITextSnapshotLine GetLastLine(SnapshotSpan span) { return span.Length > 0 ? span.End.Subtract(1).GetContainingLine() : GetStartLine(span); } private static ITextSnapshotLine GetStartLine(SnapshotSpan span) { return span.Start.GetContainingLine(); } #pragma warning disable 67 // This event gets raised if a non-text change would affect the classification in some way, // for example typing /* would cause the classification to change in C# without directly // affecting the span. public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged; #pragma warning restore 67 } }
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class SystemManager : MonoBehaviour { GameObject _pauseScreen; void Start () { _pauseScreen = GameObject.Find("PauseScreen"); if (_pauseScreen != null) { _pauseScreen.SetActive(false); } } void Update () { if (_pauseScreen != null) { if (Input.GetKeyDown(KeyCode.Escape)) { _pauseScreen.SetActive(!_pauseScreen.activeInHierarchy); } if (_pauseScreen.activeInHierarchy) { Time.timeScale = 0; } else { Time.timeScale = 1; } } else { Time.timeScale = 1; } } public void LoadScene (string sceneName) { SceneManager.LoadScene(sceneName); } public void QuitGame () { Application.Quit(); } }
using System.Threading.Tasks; namespace LoadBalancer.Providers { public interface IProvider { Task<string> Get(); bool Check(); // should be async too } }
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace NtApiDotNet.Win32.DirectoryService { /// <summary> /// Structure to represent an attribute for a class. /// </summary> public struct DirectoryServiceSchemaClassAttribute { /// <summary> /// The name of the attribute. /// </summary> public string Name { get; } /// <summary> /// True if the attribute is required. /// </summary> public bool Required { get; } /// <summary> /// True if the attribute can only be modified by system. /// </summary> public bool System { get; } internal DirectoryServiceSchemaClassAttribute(string name, bool required, bool system) { Name = name; Required = required; System = system; } /// <summary> /// Get the hash code for the attribute. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return Tuple.Create(Name, Required, System).GetHashCode(); } /// <summary> /// Check attributes for equality. /// </summary> /// <param name="obj">The other attribute to check.</param> /// <returns>True if equal.</returns> public override bool Equals(object obj) { return Tuple.Create(Name, Required, System).Equals(obj); } /// <summary> /// Overridden ToString method. /// </summary> /// <returns>The name of the attribute.</returns> public override string ToString() { return Name; } } }
using RBACv3; using RBACv3.Models; using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading; using System.Web; using GetLabourManager; public static class RBAC_ExtendedMethods_4_Principal { public static int GetUserId(this IIdentity _identity) { int _retVal = 0; try { if (_identity != null && _identity.IsAuthenticated) { var ci = _identity as ClaimsIdentity; string _userId = ci != null ? ci.FindFirstValue(ClaimTypes.NameIdentifier) : null; if (!string.IsNullOrEmpty(_userId)) { _retVal = int.Parse(_userId); } } } catch (Exception) { throw; } return _retVal; } public static bool HasPermission(this IPrincipal _principal, string _requiredPermission) { bool _retVal = false; try { if (_principal != null && _principal.Identity != null && _principal.Identity.IsAuthenticated) { var ci = _principal.Identity as ClaimsIdentity; string _userId = ci != null ? ci.FindFirstValue(ClaimTypes.NameIdentifier) : null; if (!string.IsNullOrEmpty(_userId)) { ApplicationUser _authenticatedUser = ApplicationUserManager.GetUser(int.Parse(_userId)); _retVal = _authenticatedUser.IsPermissionInUserRoles(_requiredPermission); } } } catch (Exception) { throw; } return _retVal; } //public static string LicenseCheckSum(this IPrincipal _principal) //{ // try // { // RBACDbContext db = new RBACDbContext(); // var records = db.LicenseStore.Where(c => c.Id == db.LicenseStore.Max(x => x.Id)).FirstOrDefault(); // int subscribed_days = records.ExpiredOn.Subtract(DateTime.Now.Date).Days; // if (records.ExpiredOn.Subtract(DateTime.Now.Date).Days <= 0) // { // records.LicenseStatus = "EXPIRED"; // db.Entry<LicenseStore>(records).State = System.Data.Entity.EntityState.Modified; // db.SaveChanges(); // return "EXPIRED"; // } // if (subscribed_days >= 14 & subscribed_days <= 180) // { // return "YOU HAVE " + subscribed_days + " DAYS TO RENEW YOU YOUR LICENSE"; // } // else // { // string describe = subscribed_days > 1 ? "DAYS" : "DAY"; // return "YOU HAVE " + subscribed_days + " " + describe + " TO RENEW YOUR LICENSE"; // } // } // catch (Exception err) // { // return ""; // } //} //public static string LicenseCheckSumDays(this IPrincipal _principal) //{ // try // { // RBACDbContext db = new RBACDbContext(); // var records = db.LicenseStore.Where(c => c.Id == db.LicenseStore.Max(x => x.Id)).FirstOrDefault(); // int subscribed_days = records.ExpiredOn.Subtract(DateTime.Now.Date).Days; // return subscribed_days.ToString(); // } // catch (Exception err) // { // return "0"; // } //} public static string HasPermissionAdmin(this IPrincipal _principal, string Module) { if (_principal.IsSysAdmin()) return "normal"; string _retVal = "hidden"; string[] _Customer = new string[] { "Customer-Index", "Customer-Create" }; string[] _Account = new string[] { "CustomerAccount-Index", "CustomerAccount-AccountTransaction" , "CustomerAccount-AccountManager"}; string[] _Loans = new string[] { "Loan-Index", "Loan-Create", "Loan-ManageLoans", "Loan-LoanPayment" }; string[] _MasterSetup = new string[] { "Sequence-Index", "SmsApi-Index" , "ClientDetails-Index","MasterSetup-AccountSetupIndex","MasterSetup-AccountTypeIndex", "MasterSetup-NominalCodeIndex","MasterSetup-LoanChartIndex", "MasterSetup-GroupIndex","CashbookManager-Index" }; string[] _Finance = new string[] { "CashbookManager-CashbookTransferIndex", "Finance-PaymentReversal" }; string[] _BackOffice = new string[] { "ChequeManager-Index" }; string[] _UserManager = new string[] { "Admin-Index", "Admin-RoleIndex", "Admin-PermissionIndex" }; string[] _Report = new string[] { "" }; //string[] Master = new string[] { "DataMigration-Index", // "Sequence-Index","ClientSetup-Index"}; if (_principal != null && _principal.Identity != null && _principal.Identity.IsAuthenticated) { var ci = _principal.Identity as ClaimsIdentity; string _userId = ci != null ? ci.FindFirstValue(ClaimTypes.NameIdentifier) : null; if (!string.IsNullOrEmpty(_userId)) { ApplicationUser _authenticatedUser = ApplicationUserManager.GetUser(int.Parse(_userId)); switch (Module) { case "CUSTOMER": for (int i = 0; i < _Customer.Length; i++) { _retVal = _authenticatedUser.IsPermissionInUserRoles(_Customer[i]) == true ? "normal" : "none"; if (_retVal == "normal") break; } break; case "ACCOUNT": for (int i = 0; i < _Account.Length; i++) { _retVal = _authenticatedUser.IsPermissionInUserRoles(_Account[i]) == true ? "normal" : "none"; if (_retVal == "normal") break; } break; case "LOANS": for (int i = 0; i < _Loans.Length; i++) { _retVal = _authenticatedUser.IsPermissionInUserRoles(_Loans[i]) == true ? "normal" : "none"; if (_retVal == "normal") break; } break; case "USER MANAGEMENT": for (int i = 0; i < _UserManager.Length; i++) { _retVal = _authenticatedUser.IsPermissionInUserRoles(_UserManager[i]) == true ? "normal" : "none"; if (_retVal == "normal") break; } break; case "FINANCE": for (int i = 0; i < _Finance.Length; i++) { _retVal = _authenticatedUser.IsPermissionInUserRoles(_Finance[i]) == true ? "normal" : "none"; if (_retVal == "normal") break; } break; case "MASTER SETUP": for (int i = 0; i < _MasterSetup.Length; i++) { _retVal = _authenticatedUser.IsPermissionInUserRoles(_MasterSetup[i]) == true ? "normal" : "none"; if (_retVal == "normal") break; } break; case "BACK OFFICE": for (int i = 0; i < _BackOffice.Length; i++) { _retVal = _authenticatedUser.IsPermissionInUserRoles(_BackOffice[i]) == true ? "normal" : "none"; if (_retVal == "normal") break; } break; //case "ParentReport": // for (int i = 0; i < ParentReport.Length; i++) // { // _retVal = _authenticatedUser.IsPermissionInUserRoles(ParentReport[i]) == true ? "normal" : "none"; // if (_retVal == "normal") break; // } // break; //case "MASTER SETUP": // for (int i = 0; i < Master.Length; i++) // { // _retVal = _authenticatedUser.IsPermissionInUserRoles(Master[i]) == true ? "normal" : "none"; // if (_retVal == "normal") break; // } // break; // //case "Event": // for (int i = 0; i < Event.Length; i++) // { // _retVal = _authenticatedUser.IsPermissionInUserRoles(Event[i]) == true ? "normal" : "none"; // if (_retVal == "normal") break; // } // break; //// //case "Messaging": // for (int i = 0; i < Messaging.Length; i++) // { // _retVal = _authenticatedUser.IsPermissionInUserRoles(Messaging[i]) == true ? "normal" : "none"; // if (_retVal == "normal") break; // } // break; //case "User": // for (int i = 0; i < UserManagement.Length; i++) // { // _retVal = _authenticatedUser.IsPermissionInUserRoles(UserManagement[i]) == true ? "normal" : "none"; // if (_retVal == "normal") break; // } // break; } } } return _retVal; } public static string HasPermissionView(this IPrincipal _principal, string _requiredPermission) { string _retVal = "hidden"; try { if (_principal != null && _principal.Identity != null && _principal.Identity.IsAuthenticated) { if (_principal.IsSysAdmin()) { _retVal = "normal"; return _retVal; } var ci = _principal.Identity as ClaimsIdentity; string _userId = ci != null ? ci.FindFirstValue(ClaimTypes.NameIdentifier) : null; if (!string.IsNullOrEmpty(_userId)) { ApplicationUser _authenticatedUser = ApplicationUserManager.GetUser(int.Parse(_userId)); _retVal = _authenticatedUser.IsPermissionInUserRoles(_requiredPermission) == true ? "normal" : "none"; } } } catch (Exception) { throw; } return _retVal; } public static bool IsSysAdmin(this IPrincipal _principal) { bool _retVal = false; try { if (_principal != null && _principal.Identity != null && _principal.Identity.IsAuthenticated) { var ci = _principal.Identity as ClaimsIdentity; string _userId = ci != null ? ci.FindFirstValue(ClaimTypes.NameIdentifier) : null; if (!string.IsNullOrEmpty(_userId)) { ApplicationUser _authenticatedUser = ApplicationUserManager.GetUser(int.Parse(_userId)); _retVal = _authenticatedUser.IsSysAdmin(); } } } catch (Exception) { throw; } return _retVal; } public static string FindFirstValue(this ClaimsIdentity identity, string claimType) { string _retVal = string.Empty; try { if (identity != null) { var claim = identity.FindFirst(claimType); _retVal = claim != null ? claim.Value : null; } } catch (Exception) { throw; } return _retVal; } }
/* ------------------------------------------------ Generated by Cradle 2.0.1.0 https://github.com/daterre/Cradle Original file: dancer.html Story format: Harlowe ------------------------------------------------ */ using System.Collections; using System.Collections.Generic; using UnityEngine; using Cradle; using IStoryThread = System.Collections.Generic.IEnumerable<Cradle.StoryOutput>; using Cradle.StoryFormats.Harlowe; public partial class @dancer: Cradle.StoryFormats.Harlowe.HarloweStory { #region Variables // --------------- public class VarDefs: RuntimeVars { public VarDefs() { } } public new VarDefs Vars { get { return (VarDefs) base.Vars; } } // --------------- #endregion #region Initialization // --------------- public readonly Cradle.StoryFormats.Harlowe.HarloweRuntimeMacros macros1; @dancer() { this.StartPassage = "dancer1"; base.Vars = new VarDefs() { Story = this, StrictMode = true }; macros1 = new Cradle.StoryFormats.Harlowe.HarloweRuntimeMacros() { Story = this }; base.Init(); passage1_Init(); passage2_Init(); passage3_Init(); passage4_Init(); passage5_Init(); passage6_Init(); } // --------------- #endregion // ............. // #1: dancer1 void passage1_Init() { this.Passages[@"dancer1"] = new StoryPassage(@"dancer1", new string[]{ }, passage1_Main); } IStoryThread passage1_Main() { yield return text("Weeeeeeeeeeeee!"); yield return lineBreak(); yield return lineBreak(); yield return link("space", "player1", null); yield break; } // ............. // #2: dancer2 void passage2_Init() { this.Passages[@"dancer2"] = new StoryPassage(@"dancer2", new string[]{ }, passage2_Main); } IStoryThread passage2_Main() { yield return text("~Backpack~?? I DOWN KNOT about no ~Backpack~, but I HARE there's a BOX CHILI TOE at the EMU SUM. You should TICKET OUCH!"); yield return lineBreak(); yield return lineBreak(); yield return link("space", "player2", null); yield break; } // ............. // #3: player1 void passage3_Init() { this.Passages[@"player1"] = new StoryPassage(@"player1", new string[]{ }, passage3_Main); } IStoryThread passage3_Main() { yield return text("Hey! Have you seen my backpack around here?"); yield return lineBreak(); yield return lineBreak(); yield return link("space", "dancer2", null); yield break; } // ............. // #4: player2 void passage4_Init() { this.Passages[@"player2"] = new StoryPassage(@"player2", new string[]{ "player", }, passage4_Main); } IStoryThread passage4_Main() { yield return text("Wait... you can understand me???"); yield return lineBreak(); yield return lineBreak(); yield return link("space", "dancer3", null); yield break; } // ............. // #5: dancer3 void passage5_Init() { this.Passages[@"dancer3"] = new StoryPassage(@"dancer3", new string[]{ }, passage5_Main); } IStoryThread passage5_Main() { yield return text("..."); yield return lineBreak(); yield return lineBreak(); yield return link("space", "dancer4", null); yield break; } // ............. // #6: dancer4 void passage6_Init() { this.Passages[@"dancer4"] = new StoryPassage(@"dancer4", new string[]{ "end", }, passage6_Main); } IStoryThread passage6_Main() { yield return text("Weeeeeeeeeeeeeeeee!! "); using (Group("em", true)) { yield return text("NICE SNOUT CAN DING ICE FLOUR SOY"); } yield return lineBreak(); yield return lineBreak(); yield return link("space", "dancer1", null); yield break; } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2009 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System.Configuration; using System.Xml; namespace Framework.Remote { /// <summary> /// Class reader for databaseConnections section of the Web.Config file. /// </summary> public class CxDbConnectionsSectionHandler : IConfigurationSectionHandler { //------------------------------------------------------------------------- public CxDbConnectionsSectionHandler() { } //------------------------------------------------------------------------- /// <summary> /// Creates CxDbConnections object from the section XML node. /// </summary> /// <param name="parent"></param> /// <param name="configContext"></param> /// <param name="section"></param> /// <returns></returns> public object Create( object parent, object configContext, XmlNode section) { return new CxDbConnections(section); } //------------------------------------------------------------------------- } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Prototype { class Camera { Vector3 cameraPosition; Vector3 cameraTarget; Vector3 upVector; public Camera(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 upVector) { this.cameraPosition = cameraPosition; this.cameraTarget = cameraTarget; this.upVector = upVector; } public Vector3 getCameraPosition() { return cameraPosition; } public void setCameraPosition(Vector3 position) { cameraPosition = position; } public void changeCameraPosition(Vector3 position) { cameraPosition += position; } public Vector3 getCameraTarget() { return cameraTarget; } public void setCameaTarget(Vector3 target) { cameraTarget = target; } public void changeCameaTarget(Vector3 target) { cameraTarget += target; } public Vector3 getUpVector() { return upVector; } public void setUpVector(Vector3 vector) { upVector = vector; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { string hex; char let; char[] hexa = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; double cot = 0, sum = 0; Console.Write("Enter a hexadecimal number you wish to convert : "); hex = Console.ReadLine(); Console.WriteLine("--------------------------------------------------------"); for (int i = 0; i < hex.Length; i++) { let = hex[hex.Length - 1 - i]; for (int y = 0; y < 16; y++) { if (let == hexa[y]) { sum += Convert.ToInt64(y) * (Math.Pow(16, cot)); cot++; } } } Console.Write("The number in decimal is : " + sum); Console.ReadKey(); } } }
using System.Data.Entity.ModelConfiguration; using RMAT3.Models; namespace RMAT3.Data.Mapping { public class ConditionTypeMap : EntityTypeConfiguration<ConditionType> { public ConditionTypeMap() { // Primary Key HasKey(t => t.ConditionTypeId); // Properties Property(t => t.AddedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedCommentTxt) .HasMaxLength(500); Property(t => t.ConditionTypeCd) .IsRequired() .HasMaxLength(50); Property(t => t.ConditionTypeTxt) .HasMaxLength(200); // Table & Column Mappings ToTable("ConditionType", "OLTP"); Property(t => t.ConditionTypeId).HasColumnName("ConditionTypeId"); Property(t => t.AddedByUserId).HasColumnName("AddedByUserId"); Property(t => t.AddTs).HasColumnName("AddTs"); Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId"); Property(t => t.UpdatedCommentTxt).HasColumnName("UpdatedCommentTxt"); Property(t => t.UpdatedTs).HasColumnName("UpdatedTs"); Property(t => t.IsActiveInd).HasColumnName("IsActiveInd"); Property(t => t.EffectiveFromDt).HasColumnName("EffectiveFromDt"); Property(t => t.EffectiveToDt).HasColumnName("EffectiveToDt"); Property(t => t.ConditionTypeCd).HasColumnName("ConditionTypeCd"); Property(t => t.ConditionTypeTxt).HasColumnName("ConditionTypeTxt"); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace WMagic.Thread { /// <remarks> /// ----------------------------------------------------------------------- /// 部件名:WMagicThread /// 工程名:WMagic /// 版权:CopyRight (c) 2013 /// 创建人:WY /// 描述:线程类 /// 创建日期:2013.05.17 /// 修改人:ZFL /// 修改日期:2013.05.20 /// ----------------------------------------------------------------------- /// </remarks> /// <summary> /// 线程类 /// </summary> public class MagicThread { #region 变量 // 线程标识 private string key; // 线程执行函数 private Action fun; // 线程创建选项 private TaskCreationOptions policy; // 线程取消管理 private CancellationTokenSource reactor; #endregion #region 属性 public bool IsCancel { get { return this.reactor != null ? this.reactor.IsCancellationRequested : true; } } public string Key { get { return this.key; } set { this.key = value; } } public Action Fun { get { return this.fun; } set { this.fun = value; } } public TaskCreationOptions Policy { get { return this.policy; } set { this.policy = value; } } public CancellationTokenSource Reactor { get { return this.reactor; } internal set { this.reactor = value; } } #endregion #region 构造函数 /// <summary> /// 构造函数 /// </summary> /// <param name="key">线程标识</param> /// <param name="fun">线程执行函数</param> public MagicThread(string key, Action fun) : this(key, fun, TaskCreationOptions.PreferFairness) { } /// <summary> /// /// </summary> /// <param name="key">线程标识</param> /// <param name="fun">线程执行函数</param> /// <param name="policy">线程创建可选行为</param> public MagicThread(string key, Action fun, TaskCreationOptions policy) { this.key = key; this.fun = fun; this.policy = policy; } #endregion #region 函数方法 /// <summary> /// 取消线程 /// </summary> public void Cancel() { if (this.reactor != null) this.reactor.Cancel(); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Users.DB; namespace Users.Core { public interface IUsersServices { List<User> GetUsers(); //User GetUser(int id); User GetUser(string username); User CreateUser(User user); string AddItem(User user); } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters { internal class LocationOrLocationLinksConverter : JsonConverter<LocationOrLocationLinks> { public override void WriteJson(JsonWriter writer, LocationOrLocationLinks value, JsonSerializer serializer) { var v = value.ToArray(); if (v.Length == 1 && v[0].IsLocation) { serializer.Serialize(writer, v[0]); return; } serializer.Serialize(writer, v); } public override LocationOrLocationLinks ReadJson( JsonReader reader, Type objectType, LocationOrLocationLinks existingValue, bool hasExistingValue, JsonSerializer serializer ) { if (reader.TokenType == JsonToken.StartArray) { return new LocationOrLocationLinks(JArray.Load(reader).ToObject<IEnumerable<LocationOrLocationLink>>(serializer)); } if (reader.TokenType == JsonToken.StartObject) { return new LocationOrLocationLinks(JObject.Load(reader).ToObject<Location>(serializer)); } return new LocationOrLocationLinks(); } public override bool CanRead => true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using XPowerAPI.Repository.Collections; namespace XPowerAPI.Models.Results { public class StatisticResult { public float TotalWattage { get; set; } public int Switches { get; set; } public IPagedList<IStatistic> Statistics { get; set; } } }
using UnityEngine; using System.Collections; [System.Serializable] [CreateAssetMenu] public class ObstructionTileData : BaseTileData { public const int NEVER_EXPIRES = -1234; public int TurnsTilExpired = NEVER_EXPIRES; }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace BankingWindowsApplication { public partial class AccountDetails : Form { public AccountDetails() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string MyConString = "Data Source=./LAPTOP-FAO2P8J8/SQLEXPRESS;Initial Catalog=BankingSystem.mdf;Integrated Security=true"; SqlConnection connection = new SqlConnection(MyConString); connection.Open(); string str = "select * from account where accid = '" + textBox1.Text + "'"; SqlCommand cmd = new SqlCommand(str, connection); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; //dataGridView1.DataBind(); } } }
using System; namespace jankenapp { public class MyClass { public MyClass() { } } }
namespace BusinessLogic { public class ReturnMsg { public string Name { get; set; } public string Msg { get; set; } public string Session { get; set; } public ReturnMsg(string name, string msg, string session) { this.Name = name; this.Msg = msg; this.Session = session; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using WindowsFormsApp4; namespace FireApp { public partial class form1 : Form { public form1() { InitializeComponent(); panelLeft.Height = btnHome.Height; panelLeft.Top = btnHome.Top; } private void BtnCreate_Click(object sender, EventArgs e) { panelLeft.Height = btnCreate.Height; panelLeft.Top = btnCreate.Top; Form2 myForm = new Form2(); myForm.Owner = this; myForm.Show(); } private void Sign1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\84931\Documents\List_User.mdf;Integrated Security=True;Connect Timeout=30"); SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From CreateAccount where username='" + textBox1.Text + "' and password='" + textBox2.Text + "'", con); DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows[0][0].ToString() == "1") { this.Hide(); MainScreen ss = new MainScreen(); ss.Show(); } else { MessageBox.Show("Please Check Your Username and Password"); } } private void btnHome_Click(object sender, EventArgs e) { panelLeft.Height = btnHome.Height; panelLeft.Top = btnHome.Top; System.Diagnostics.Process.Start("https://smartfirebbq.com/"); } private bool dragging = false; private Point startPoint = new Point(0, 0); private void panel3_MouseDown(object sender, MouseEventArgs e) { dragging = true; startPoint = new Point(e.X, e.Y); } private void panel3_MouseMove(object sender, MouseEventArgs e) { if (dragging) { Point p = PointToScreen(e.Location); Location = new Point(p.X - this.startPoint.X, p.Y - this.startPoint.Y); } } private void panel3_MouseUp(object sender, MouseEventArgs e) { dragging = false; } private void btnExit_Click(object sender, EventArgs e) { panelLeft.Height = btnExit.Height; panelLeft.Top = btnExit.Top; this.Close(); } private void form1_FormClosing(object sender, FormClosingEventArgs e) { if(MessageBox.Show("Are you sure want to quit?", "Close?", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) { e.Cancel = true; } } private void panel3_Paint(object sender, PaintEventArgs e) { } } }
 using System; using UrTLibrary.Server.Queries.Game; namespace UrTLibrary.Server.Logging.Events.ChatCommands { [ChatCommandKey("exec")] public class ExecCommand : ChatCommand { [ChatCommandParameter(ChatCommandParameterType.Word)] public string CfgPath { get; set; } public override void Execute(GameServer server) { log.DebugFormat("--> Executing ExecCommand"); try { server.QueryManager.RCon("exec \"" + CfgPath + "\""); } catch (CommandException ex) { server.QueryManager.TellError(Slot, ex.Message); } } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using proj.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; namespace proj.Controllers { public class HomeController : Controller { private readonly ApplicationContext _db; private readonly SignInManager<User> _signInManager; private readonly UserManager<User> _userManager; IWebHostEnvironment _appEnvironment; public HomeController(ApplicationContext db, UserManager<User> userManager, SignInManager<User> signInManager, IWebHostEnvironment appEnvironment) { _db = db; _signInManager = signInManager; _userManager = userManager; _appEnvironment = appEnvironment; } public IActionResult Index(string title = "", string description = "", int year1 = 2001, int year2 = 2022, int dwnl1 = 0, int dwnl2 = 1000, string author = "", bool descending = true) { try { if (descending) { ViewBag.Book = _db.Books.Where(x => x.Title.Contains(title) && x.Description.Contains(description) && x.Author.Contains(author) && x.Year >= year1 && x.Year <= year2 && x.Downloads >= dwnl1 && x.Downloads <= dwnl2).OrderByDescending(x => x.Id).ToList(); } else { ViewBag.Book = _db.Books.Where(x => x.Title.Contains(title) && x.Description.Contains(description) && x.Author.Contains(author) && x.Year >= year1 && x.Year <= year2 && x.Downloads >= dwnl1 && x.Downloads <= dwnl2).OrderBy(x => x.Id).ToList(); } return View(); } catch (Exception) { return RedirectToAction("Error"); } } //public IActionResult Privacy() //{ // return View(); //} [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [HttpGet] [Authorize(Roles = "admin")] public IActionResult CreateBook() { return View(); } [HttpPost] [Authorize(Roles = "admin")] [RequestFormLimits(MultipartBodyLengthLimit = 209715200)] [RequestSizeLimit(209715200)] public IActionResult CreateBook(string title, string description, string author, int year , IFormFile formFile, IFormFile uploadedFile) { try { var dateStr = DateTime.Now.ToString().Replace(".", "").Replace(" ", "").Replace(":", ""); if (formFile != null) { string formfile = "/img/" + dateStr + formFile.FileName; using (var filestream = new FileStream(_appEnvironment.WebRootPath + formfile, FileMode.Create)) { formFile.CopyTo(filestream); } } if (uploadedFile != null) { string path = "/Files/" + dateStr + dateStr + uploadedFile.FileName; using (var filestream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { formFile.CopyTo(filestream); } } Book book = new Book(); book.Title = title; book.Description = description; book.Author = author; book.Year = year; book.Img = "/img/" + dateStr + formFile.FileName; book.File = "/Files/" + dateStr + dateStr + uploadedFile.FileName; _db.Books.Add(book); _db.SaveChanges(); return View(); } catch (Exception) { return RedirectToAction("Error"); } } } }
using System; using System.Collections; namespace Aut.Lab.lab06 { public class Lab06Application { Queue myque = new Queue(); private string name = ""; public Lab06Application(string fileName) { name = fileName; } public void Run() { string cmd = ""; while(!cmd.Equals("quit")) { Console.Write("Please enter command : "); string cm = Console.ReadLine(); string[] command = cm.Split(' '); cmd = command[0]; if(cmd.Equals("clear")) { myque.Clear(); } else if(cmd.Equals("quit")) { return; } else if(cmd.Equals("enque")) { if(command.Length == 1) { Console.WriteLine("Please put command !!"); } else { string word = command[1]; myque.Enqueue(word); } } else if(cmd.Equals("display")) { myque.DisplayQue(); } else if(cmd.Equals("count")) { Console.WriteLine("Size of Queue = {0}",myque.Count); } else if(cmd.Equals("deque")) { string data = myque.Dequeue(); Console.WriteLine("Deque item : {0}",data); } } } } }
using System; using System.Data; using System.Runtime.InteropServices; using System.Windows.Forms; using TutteeFrame2.Controller; using TutteeFrame2.Model; using TutteeFrame2.Reports; namespace TutteeFrame2.View { public partial class frmStudentInfoReport : Form { #region Win32 Form public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImportAttribute("user32.dll")] public static extern bool ReleaseCapture(); protected override CreateParams CreateParams { get { const int CS_DROPSHADOW = 0x20000; CreateParams cp = base.CreateParams; cp.ClassStyle |= CS_DROPSHADOW; return cp; } } #endregion HomeView homeView; public enum GradeFilter { All = 0, Grade10 = 1, Grade11 = 2, Grade12 = 3, } public GradeFilter gradeFilter = GradeFilter.All; public string classFilter = "Tất cả"; public ReportStudentController controller; public void SetHome(HomeView homeView) { this.homeView = homeView; } public frmStudentInfoReport() { controller = new ReportStudentController(this); controller.FetchData(); InitializeComponent(); cbbFilterByGrade.SelectedIndex = 0; } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } private void cbbFilterByGrade_SelectedIndexChanged(object sender, EventArgs e) { if (cbbFilterByGrade.SelectedIndex < 0) return; gradeFilter = (GradeFilter)cbbFilterByGrade.SelectedIndex; controller.FilterStudentByGrade(); controller.FetchCbbClassItems(); } public void ShowStudentsOnListView() { listViewStudents.Items.Clear(); foreach (Student student in controller.students) { ListViewItem lvi = new ListViewItem(new string[] {student.ID,student.SurName,student.FirstName, student.DateBorn.ToString("dd/MM/yyyy"),student.GetSex,student.Address, student.Phone,student.ClassID,student.Status?"Đang học":"Đã nghĩ học" }); lvi.Tag = student; listViewStudents.Items.Add(lvi); } } public void FetchCbbClassItems() { cbbFilterByClass.Items.Clear(); cbbFilterByClass.Items.Add("Tất cả"); foreach (var item in controller.cbbClassItems) { cbbFilterByClass.Items.Add(item); } cbbFilterByClass.SelectedIndex = 0; } private void cbbFilterByClass_SelectedIndexChanged(object sender, EventArgs e) { if (cbbFilterByClass.SelectedIndex < 0) return; classFilter = (String)cbbFilterByClass.SelectedItem; controller.cbbSlectedItem = (String)cbbFilterByClass.SelectedItem; controller.FilterStudentByClass(); } private void btnPrintStudents_Click(object sender, EventArgs e) { StudentInfoReporter studentInfoReporter = new StudentInfoReporter(TypePrint.List, controller, null); studentInfoReporter.ShowDialog(); DataTable table = controller.convertListStudentToDataTable(controller.students); Console.WriteLine(table); } private void frmStudentReport_FormClosed(object sender, FormClosedEventArgs e) { this.homeView.Visible = true; this.homeView.Select(); } private void frmStudentInfoReport_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); } } private void frmStudentInfoReport_Shown(object sender, EventArgs e) { this.homeView.Visible = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace ProyectoIntegrado { class Pago { public Pago() { } public virtual void EfectuarPago(Pedidos pedido) { } public double getPrecioTotal(Pedidos pedido) { String consulta = "SELECT precio FROM ArticulosPedido where id=$id"; ConexionBBDD conexion = new ConexionBBDD(); MySqlCommand comando = new MySqlCommand(consulta, conexion.Conexion); comando.Parameters.AddWithValue("id", pedido.PrecioPedido); MySqlDataReader reader = comando.ExecuteReader(); double preciotot = reader.GetDouble(0); return preciotot; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Load_App : Form { public Load_App() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { progressBar1.Maximum = 200; progressBar1.Minimum = 0; progressBar1.Step = 1; timer1.Start(); this.progressBar1.Visible = true; } private void timer1_Tick(object sender, EventArgs e) { this.progressBar1.Increment(1); progressBar1.PerformStep(); // or progressBar1.Value++; if (progressBar1.Value == 200) // check with the value { new Welcome_Form().Show(); this.Hide(); timer1.Stop(); } } } }
using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using App1.Renderer; using App1.iOS.Renderer; using Google.MobileAds; [assembly: ExportRenderer(typeof(AdMobBannerView), typeof(AdMobBannerRenderer))] namespace App1.iOS.Renderer { public class AdMobBannerRenderer : ViewRenderer { BannerView adView; bool viewOnScreen = false; public static void Init() { } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e) { base.OnElementChanged(e); var adMobElement = Element; adView = new BannerView(AdSizeCons.Banner) { AdUnitID = "ca-app-pub-3940256099942544/6300978111",//"광고 ID";, RootViewController = UIApplication.SharedApplication.Windows[0].RootViewController }; adView.AdReceived += (sender, args) => { if (!viewOnScreen) { AddSubview(adView); } viewOnScreen = true; }; adView.LoadRequest(Request.GetDefaultRequest()); base.SetNativeControl(adView); } } }
using System; namespace Desafio_01___04___2 { class Program { static void Main(string[] args) { //https://youtu.be/20B4ruiOmHs //Entradas Console.WriteLine("Ingrese el ángulo d"); double d = double.Parse(Console.ReadLine()); Console.WriteLine("Ingrese el ángulo b"); double b = double.Parse(Console.ReadLine()); Console.WriteLine("Ingrese el lado y"); double y = double.Parse(Console.ReadLine()); //Proceso //Cálculo del ángulo a double a = 180 - 90 - b - d; //Conversion grad a rad de a double aRad = a * Math.PI / 180; //Cálculo del lado z double z = y / Math.Tan(aRad); //Salidas Console.WriteLine("El lado z es:"); Console.WriteLine(z); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// In game scene reference controller; /// </summary> public class IGRC : MonoBehaviour { public static IGRC IGIS; //In game scene isntance; public Transform Cat_TRANS; protected virtual void Awake() { IGIS = this; } // Start is called before the first frame update protected virtual void Start() { } // Update is called once per frame protected virtual void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WF.SDK.Models.Internal { [Serializable] public class FileItem { public string ContentDisposition { get; set; } public string ContentEncoding { get; set; } public int ContentLength { get; set; } public string ContentType { get; set; } public string Filename { get; set; } public byte[] FileContents { get; set; } public string Url { get; set; } public FileItem() { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IDamaging { public abstract float Damage { get; } }
using Innouvous.Utils; using Innouvous.Utils.MVVM; using System; using System.IO; using System.Windows; using System.Windows.Input; using EXP = ToDo.Client.Export.Exporter; namespace ToDo.Client.ViewModels { public class ExportImportViewModel : ViewModel { private Window window; public ExportImportViewModel(Window window) { this.window = window; DatabaseUpdated = false; } public bool DatabaseUpdated { get; private set; } #region Export private string exportPath; public string ExportPath { get { return exportPath; } set { exportPath = value; RaisePropertyChanged(); } } public ICommand BrowseForExportCommand { get { return new CommandHelper(BrowseForExport); } } private void BrowseForExport() { var sfd = DialogsUtility.CreateSaveFileDialog("Export"); DialogsUtility.AddExtension(sfd, "XML File", "*.xml"); sfd.ShowDialog(); ExportPath = sfd.FileName; } public ICommand ExportCommand { get { return new CommandHelper(Export); } } public void Export() { try { if (string.IsNullOrEmpty(ExportPath)) throw new Exception("Path cannot be empty."); EXP.Export(ExportPath); MessageBoxFactory.ShowInfo("Database exported to: " + ExportPath, "Exported"); } catch (Exception e) { MessageBoxFactory.ShowError(e); } } #endregion #region Import private string importPath; public string ImportPath { get { return importPath; } set { importPath = value; RaisePropertyChanged(); } } public ICommand BrowseForImportCommand { get { return new CommandHelper(BrowseForImport); } } private void BrowseForImport() { var ofd = DialogsUtility.CreateOpenFileDialog("Import"); DialogsUtility.AddExtension(ofd, "XML File", "*.xml"); ofd.ShowDialog(); ImportPath = ofd.FileName; } public ICommand ImportCommand { get { return new CommandHelper(Import); } } public void Import() { try { if (string.IsNullOrEmpty(importPath) || !File.Exists(ImportPath)) throw new Exception("File not found."); EXP.Import(importPath); MessageBoxFactory.ShowInfo("Database has been imported.", "Imported"); DatabaseUpdated = true; } catch (Exception e) { MessageBoxFactory.ShowError(e); } } #endregion public ICommand ClearDatabaseCommand { get { return new CommandHelper(ClearDatabase); } } private void ClearDatabase() { if (MessageBoxFactory.ShowConfirmAsBool("Are you sure you want to clear the database?", "Confirm Clear Database", MessageBoxImage.Exclamation)) { var DB = Workspace.Instance; DB.Comments.RemoveRange(DB.Comments); DB.Lists.RemoveRange(DB.Lists); DB.Tasks.RemoveRange(DB.Tasks); DB.TasksLog.RemoveRange(DB.TasksLog); DatabaseUpdated = true; } } public ICommand CloseCommand { get { return new CommandHelper(() => window.Close()); } } } }
using System; using System.Collections.Generic; using NetPayroll.Guides.Common; using NetPayroll.Guides.History; using NetPayroll.Guides.Interfaces; namespace NetPayroll.Guides.Contract.Employ { public class ContractEmployHistory : HistoryContract<IContractEmploy> { private const string NAME_SPACE_PREFIX = "NetPayroll.Guides.Contract.Employ"; private const string CLASS_NAME_PREFIX = "ContractEmploy"; private static readonly Period DEFAULT_PERIOD = new Period(2017, 1); private ContractEmployHistory() { } public static IHistoryContract<IContractEmploy> CreateInstance() { return new ContractEmployHistory(); } public static IHistoryContract<IContractEmploy> CreateContracts() { IHistoryContract<IContractEmploy> contracts = CreateInstance(); var initContracts = new Dictionary<PeriodSpan, IContractEmploy>() { {new PeriodSpan(2011), new ContractEmploy2011() } }; contracts.InitContracts(DEFAULT_PERIOD, initContracts); return contracts; } #region implemented abstract members of GeneralEngines protected override string NamespacePrefix() { return NAME_SPACE_PREFIX; } protected override string ClassnamePrefix() { return CLASS_NAME_PREFIX; } #endregion } }
using Kowalski.Common; using Kowalski.Models; using Kowalski.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using System.Windows.Input; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Metadata; using Windows.Media.SpeechRecognition; using Windows.Storage; using Windows.System; using Windows.System.Profile; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Kowalski.Views { public sealed partial class MainPage : Page { public ICommand ConnectCommand { get; } public ICommand DisconnectCommand { get; } public ICommand ShutdownCommand { get; } public ICommand PingCommand { get; } public MainPage() { this.InitializeComponent(); Unloaded += MainPage_Unloaded; ConnectCommand = new RelayCommand(Connect); DisconnectCommand = new RelayCommand(Disconnect); ShutdownCommand = new RelayCommand(Shutdown); PingCommand = new RelayCommand(Ping); } protected override void OnNavigatedTo(NavigationEventArgs e) { SoundPlayer.Instance.Play(Sounds.Startup); Assistant.OnStartRecognition += Assistant_OnStartRecognition; Assistant.OnCommandReceived += Assistant_OnCommandReceived; Assistant.OnResponseReceived += Assistant_OnResponseReceived; if (AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.IoT") { Assistant.StartService(); } base.OnNavigatedTo(e); } private void Assistant_OnStartRecognition(object sender, EventArgs e) { ResponseBubble.Visibility = Visibility.Collapsed; BotResponse.Text = string.Empty; } private void Assistant_OnCommandReceived(object sender, EventArgs e) { WaitingRing.Visibility = Visibility.Visible; } private async void Assistant_OnResponseReceived(object sender, BotEventArgs e) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { WaitingRing.Visibility = Visibility.Collapsed; BotResponse.Text = e.Text; ResponseBubble.Visibility = Visibility.Visible; }); } private void MainPage_Unloaded(object sender, RoutedEventArgs e) { Assistant.StopService(); Assistant.OnStartRecognition -= Assistant_OnStartRecognition; Assistant.OnResponseReceived -= Assistant_OnResponseReceived; } private void Connect() { Assistant.StartService(); } private void Disconnect() { Assistant.StopService(); } private void Shutdown() { try { // Shutdowns the device immediately. if (ApiInformation.IsTypePresent("Windows.System.ShutdownManager")) { SoundPlayer.Instance.Play(Sounds.Shutdown); ShutdownManager.BeginShutdown(ShutdownKind.Shutdown, TimeSpan.FromSeconds(3)); } } catch { } } private void Ping() { SoundPlayer.Instance.Play(Sounds.Startup); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DiscordDice.Commands { internal static class CommandsHelp { public static string Create(IReadOnlyCollection<Command> commands) { var resultBuilder = new StringBuilder(); resultBuilder.Append($@"**DiceBotのヘルプ** **# ダイスの振り方** 例えば下のように書き込むことでダイスを振ることができます。 `1d6` `2d100` `-1d20` `1d4-2d10+10` **# コマンド一覧** [ と ] で囲まれた部分はオプションです。オプションは省略可能であり、順不同です。 "); foreach (var command in commands) { var commandText = ToString(command); if (commandText != null) { resultBuilder.Append($"\r\n{commandText}"); } } return resultBuilder.ToString(); } private static string ToString(Command command) { if (command.Help == null) { return null; } var resultBuilder = new StringBuilder($"{command.Help.CommandName}コマンド\r\n```"); { var isFirst = true; foreach (var body in command.GetBodies()) { resultBuilder.Append($"{(isFirst ? "" : "\r\n")}{(command.NeedMentioned ? "<@DiceBot> " : "")}{body}"); isFirst = false; } } foreach (var option in command.Options ?? new CommandOption[] { }) { if (option == null) continue; resultBuilder.Append(" ["); // パターン1: [-k | --key] // パターン2: [--key value] // パターン3: [(-k | --key) value] // としたとき、パターン3の処理 if (option.Keys.Count >= 2 && option.OptionValueHelpText != null) { resultBuilder.Append("("); } var optionString = option.Keys .SelectMany(key => new[] { " | ", key }) .Skip(1) .Aggregate(new StringBuilder(), (sb, str) => sb.Append(str)); resultBuilder.Append(optionString); // パターン3の処理 if (option.Keys.Count >= 2 && option.OptionValueHelpText != null) { resultBuilder.Append(")"); } if (option.OptionValueHelpText != null) { resultBuilder.Append(" "); resultBuilder.Append(option.OptionValueHelpText); } resultBuilder.Append("]"); } resultBuilder.Append($"\r\n\r\n説明:\r\n{command.Help.Text}"); { var isFirst = true; foreach (var option in command.Options ?? new CommandOption[] { }) { if (option == null) continue; if (isFirst) { resultBuilder.Append("\r\n\r\nオプション:"); } foreach(var key in option.Keys) { resultBuilder.Append($"\r\n{ key } { option.OptionValueHelpText }"); } resultBuilder.Append($"\r\n{ option.OptionInstructionHelpText }"); isFirst = false; } } resultBuilder.Append("```"); return resultBuilder.ToString(); } } }
using Microsoft.AspNetCore.Mvc; using WebSite1.Models; using WebSite1.ViewModels; namespace WebSite1.Controllers { public class HomeController : Controller { private readonly IItemRepository _itemRepository; public HomeController(IItemRepository itemRepository) { _itemRepository = itemRepository; } public IActionResult Index() { var homeViewModel = new HomeViewModel { ItemOnSale = _itemRepository.GetItemOnSale }; return View(homeViewModel); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using Grisaia.Geometry; using Grisaia.Mvvm.Utils; namespace Grisaia.Mvvm.Services { /// <summary> /// An service for creating and loading bitmaps. /// </summary> public class BitmapFactory { #region Fields /// <summary> /// The service for performing UI actions such as dispatcher invoking. /// </summary> private readonly UIService ui; #endregion #region Constructors /// <summary> /// Constructs the <see cref="BitmapFactory"/>. /// </summary> public BitmapFactory(UIService ui) { this.ui = ui; } #endregion #region Create /// <summary> /// Creates a new writeable bitmap. /// </summary> /// <param name="size">The size of the bitmap.</param> /// <returns>The new writeable bitmap.</returns> public WriteableBitmap CreateBitmap(Point2I size) { return ui.Invoke(() => new WriteableBitmap(size.X, size.Y, 96, 96, PixelFormats.Bgra32, null)); } #endregion #region From Source /// <summary> /// Loads a bitmap from the specified resource path. /// </summary> /// <param name="resourcePath">The resource path to load the bitmap from.</param> /// <param name="assembly">The assembly to load teh embedded resource from.</param> /// <returns>The loaded bitmap.</returns> public BitmapSource FromResource(string resourcePath, Assembly assembly = null) { assembly = assembly ?? Assembly.GetCallingAssembly(); return ui.Invoke(() => { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.UriSource = WpfUtils.MakePackUri(resourcePath, assembly); bitmapImage.EndInit(); bitmapImage.Freeze(); return bitmapImage; }); } /// <summary> /// Loads a bitmap from the specified file path. /// </summary> /// <param name="filePath">The file path to load the bitmap from.</param> /// <returns>The loaded bitmap.</returns> public BitmapSource FromFile(string filePath) { return ui.Invoke(() => { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.UriSource = new Uri(filePath); bitmapImage.EndInit(); bitmapImage.Freeze(); return bitmapImage; }); } /// <summary> /// Loads a bitmap from the specified stream. /// </summary> /// <param name="stream">The stream to load the bitmap from.</param> /// <returns>The loaded bitmap.</returns> public BitmapSource FromStream(Stream stream) { return ui.Invoke(() => { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); bitmapImage.Freeze(); return bitmapImage; }); } /// <summary> /// Loads a bitmap from the specified icon handle. /// </summary> /// <param name="handle">The handle of the icon to load.</param> /// <returns>The loaded bitmap.</returns> public BitmapSource FromHIcon(IntPtr hIcon) { return ui.Invoke(() => { return Imaging.CreateBitmapSourceFromHIcon( hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); }); } #endregion } /*/// <summary>An implementation for a UI-independent WPF bitmap.</summary> public class WpfBitmap : IBitmap { #region Fields /// <summary>Gets the actual bitmap object.</summary> public BitmapSource Source { get; } /// <summary>Gets the width of the bitmap.</summary> public int Width { get; } /// <summary>Gets the height of the bitmap.</summary> public int Height { get; } #endregion #region Constructors /// <summary>Constructs the <see cref="WpfBitmap"/>.</summary> public WpfBitmap(BitmapSource source) { Source = source; Width = source.PixelWidth; Height = source.PixelHeight; } #endregion #region Properties /// <summary>Gets the size of the bitmap.</summary> public Point2I Size => new Point2I(Width, Height); /// <summary>Gets the bounds of the bitmap.</summary> public Rectangle2I Bounds => new Rectangle2I(Width, Height); /// <summary>Gets the actual bitmap object.</summary> object IBitmap.Source => Source; #endregion } /// <summary>An implementation for a UI-independent WPF bitmap with writeable pixels.</summary> public class WpfWriteableBitmap : WpfBitmap, IWriteableBitmap { #region Fields /// <summary>Gets the service for invoking UI actions.</summary> protected readonly UIService ui; #endregion #region Constructors /// <summary>Constructs the <see cref="WpfWriteableBitmap"/>.</summary> public WpfWriteableBitmap(UIService ui, WriteableBitmap source) : base(source) { this.ui = ui; } #endregion #region Pixels /// <summary>Creates a new array of pixels for populating the bitmap.</summary> public Rgba32Color[] CreatePixels() { return new Rgba32Color[Width * Height * 4]; } /// <summary>Gets the bitmap's pixels.</summary> public Rgba32Color[] GetPixels() { Rgba32Color[] pixels = CreatePixels(); ui.Invoke(() => Source.CopyPixels(pixels, Width * 4, 0)); return pixels; } /// <summary>Sets the bitmap's pixels.</summary> public void SetPixels(Rgba32Color[] pixels) { ui.Invoke(() => Source.WritePixels((Int32Rect) Bounds, pixels, Stride, 0)); } /// <summary>Sets the bitmap's pixels.</summary> public unsafe void SetPixels(Rgba32Color* pixels) { ui.Invoke(() => Source.WritePixels((Int32Rect) Bounds, (IntPtr) pixels, BufferSize, Stride)); } #endregion #region Properties /// <summary>Gets the actual bitmap object.</summary> public new WriteableBitmap Source => (WriteableBitmap) base.Source; /// <summary>Gets the stride for the bitmap.</summary> public int Stride => Width * 4; /// <summary>Gets the buffer size for the bitmap.</summary> public int BufferSize => Width * Height * 4; #endregion }*/ }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Rhea.Data.Entities; namespace Rhea.Business { /// <summary> /// 房产服务 /// </summary> public class EstateService { #region BuildingGroupService /// <summary> /// 获取楼群列表 /// </summary> /// <returns></returns> public IEnumerable<BuildingGroup> GetBuildingGroupList() { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("buildinggroup"); if (response.IsSuccessStatusCode) { var buildingGroups = response.Content.ReadAsAsync<IEnumerable<BuildingGroup>>().Result; return buildingGroups.OrderBy(r => r.Id); } else { return null; } } /// <summary> /// 获取楼群 /// </summary> /// <param name="id">楼群ID</param> /// <returns></returns> public BuildingGroup GetBuildingGroup(int id) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("BuildingGroup?id=" + id.ToString()); if (response.IsSuccessStatusCode) { var buildingGroup = response.Content.ReadAsAsync<BuildingGroup>().Result; return buildingGroup; } else return null; } /// <summary> /// 更新楼群 /// </summary> /// <param name="buildingGroup">楼群模型</param> /// <returns></returns> public bool UpdateBuildingGroup(BuildingGroup buildingGroup) { ApiService api = new ApiService(); HttpResponseMessage response = api.Put("BuildingGroup", buildingGroup.Id, buildingGroup); return response.IsSuccessStatusCode; } /// <summary> /// 添加楼群 /// </summary> /// <param name="buildingGroup">楼群模型</param> /// <returns></returns> public int CreateBuildingGroup(BuildingGroup buildingGroup) { ApiService api = new ApiService(); HttpResponseMessage response = api.Post("BuildingGroup", buildingGroup); if (response.IsSuccessStatusCode) { int id = response.Content.ReadAsAsync<int>().Result; return id; } else return 0; } /// <summary> /// 删除楼群 /// </summary> /// <param name="id">楼群ID</param> /// <returns></returns> public bool DeleteBuildingGroup(int id) { ApiService api = new ApiService(); HttpResponseMessage response = api.Delete("BuildingGroup", id); return response.IsSuccessStatusCode; } #endregion //BuildingGroupService #region BuildingService /// <summary> /// 获取楼宇列表 /// </summary> /// <returns></returns> public IEnumerable<Building> GetBuildingList() { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("building"); if (response.IsSuccessStatusCode) { var buildings = response.Content.ReadAsAsync<IEnumerable<Building>>().Result; return buildings.OrderBy(r => r.Id); } else { return null; } } /// <summary> /// 获取楼宇 /// </summary> /// <param name="id">楼宇ID</param> /// <returns></returns> public Building GetBuilding(int id) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Building?id=" + id.ToString()); if (response.IsSuccessStatusCode) { var building = response.Content.ReadAsAsync<Building>().Result; return building; } else return null; } /// <summary> /// 获取楼宇 /// </summary> /// <param name="buildingGroupId">所属楼群ID</param> /// <returns></returns> public IEnumerable<Building> GetBuildingByGroup(int buildingGroupId) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Building?BuildingGroupId=" + buildingGroupId.ToString()); if (response.IsSuccessStatusCode) { var buildings = response.Content.ReadAsAsync<IEnumerable<Building>>().Result; return buildings; } else return null; } /// <summary> /// 添加楼宇 /// </summary> /// <param name="building">楼宇模型</param> /// <returns>0:添加失败</returns> public int CreateBuilding(Building building) { ApiService api = new ApiService(); HttpResponseMessage response = api.Post("Building", building); if (response.IsSuccessStatusCode) { int id = response.Content.ReadAsAsync<int>().Result; return id; } else return 0; } /// <summary> /// 更新楼宇 /// </summary> /// <param name="building">楼宇模型</param> /// <returns></returns> public bool UpdateBuilding(Building building) { ApiService api = new ApiService(); HttpResponseMessage response = api.Put("Building", building.Id, building); return response.IsSuccessStatusCode; } /// <summary> /// 删除楼宇 /// </summary> /// <param name="id">楼宇ID</param> /// <returns></returns> public bool DeleteBuilding(int id) { ApiService api = new ApiService(); HttpResponseMessage response = api.Delete("Building", id); return response.IsSuccessStatusCode; } /// <summary> /// 添加楼层 /// </summary> /// <param name="buildingId">楼宇ID</param> /// <param name="floor">楼层数据</param> /// <returns></returns> public int CreateFloor(int buildingId, Floor floor) { ApiService api = new ApiService(); HttpResponseMessage response = api.Post("Building?id=" + buildingId.ToString(), floor); if (response.IsSuccessStatusCode) { int id = response.Content.ReadAsAsync<int>().Result; return id; } else return 0; } /// <summary> /// 更新楼层 /// </summary> /// <param name="buildingId">楼宇ID</param> /// <param name="floor">楼层数据</param> /// <returns></returns> public bool UpdateFloor(int buildingId, Floor floor) { ApiService api = new ApiService(); HttpResponseMessage response = api.Put("Building?id=" + buildingId.ToString() + "&floorId=" + floor.Id, floor); return response.IsSuccessStatusCode; } /// <summary> /// 删除楼层 /// </summary> /// <param name="buildingId">楼宇ID</param> /// <param name="floorId">楼层ID</param> /// <returns></returns> public bool DeleteFloor(int buildingId, int floorId) { ApiService api = new ApiService(); HttpResponseMessage response = api.Delete("Building?id=" + buildingId.ToString() + "&floorId=" + floorId); return response.IsSuccessStatusCode; } #endregion //BuildingService #region RoomService /// <summary> /// 获取房间 /// </summary> /// <param name="id">房间ID</param> /// <returns></returns> public Room GetRoom(int id) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Room?Id=" + id.ToString()); if (response.IsSuccessStatusCode) { var room = response.Content.ReadAsAsync<Room>().Result; return room; } else return null; } /// <summary> /// 获取房间 /// </summary> /// <param name="buildingId">楼宇ID</param> /// <returns></returns> public IEnumerable<Room> GetRoomByBuilding(int buildingId) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Room?BuildingId=" + buildingId.ToString()); if (response.IsSuccessStatusCode) { var rooms = response.Content.ReadAsAsync<IEnumerable<Room>>().Result; return rooms; } else return null; } /// <summary> /// 获取房间 /// </summary> /// <param name="buildingId">楼宇ID</param> /// <param name="floor">楼层</param> /// <returns></returns> public IEnumerable<Room> GetRoomByBuilding(int buildingId, int floor) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Room?buildingId=" + buildingId.ToString() + "&floor=" + floor.ToString()); if (response.IsSuccessStatusCode) { var rooms = response.Content.ReadAsAsync<IEnumerable<Room>>().Result; return rooms; } else return null; } /// <summary> /// 获取房间 /// </summary> /// <param name="departmentId">部门ID</param> /// <returns></returns> public IEnumerable<Room> GetRoomByDepartment(int departmentId) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Room?DepartmentId=" + departmentId.ToString()); if (response.IsSuccessStatusCode) { var rooms = response.Content.ReadAsAsync<IEnumerable<Room>>().Result; return rooms; } else return null; } /// <summary> /// 添加房间 /// </summary> /// <param name="room">房间数据</param> /// <returns>房间ID,0:添加失败</returns> public int CreateRoom(Room room) { ApiService api = new ApiService(); HttpResponseMessage response = api.Post("Room", room); if (response.IsSuccessStatusCode) { int id = response.Content.ReadAsAsync<int>().Result; return id; } else return 0; } /// <summary> /// 编辑房间 /// </summary> /// <param name="room">房间数据</param> /// <returns></returns> public bool UpdateRoom(Room room) { ApiService api = new ApiService(); HttpResponseMessage response = api.Put("Room", room.Id, room); return response.IsSuccessStatusCode; } /// <summary> /// 删除房间 /// </summary> /// <param name="id">房间ID</param> /// <returns></returns> public bool DeleteRoom(int id) { ApiService api = new ApiService(); HttpResponseMessage response = api.Delete("Room", id); return response.IsSuccessStatusCode; } #endregion //RoomService #region Statistic Service /// <summary> /// 得到统计面积数据 /// </summary> /// <param name="type">统计类型</param> /// <remarks>type=1:学院分类用房面积</remarks> /// <returns></returns> public T GetStatisticArea<T>(int type) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Statistic?type=" + type.ToString()); if (response.IsSuccessStatusCode) { var data = response.Content.ReadAsAsync<T>().Result; return data; } else return default(T); } /// <summary> /// 获取对象数量 /// </summary> /// <param name="type"></param> /// <returns></returns> public int GetEntitySize(int type) { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("Statistic?type=" + type.ToString()); if (response.IsSuccessStatusCode) { var data = response.Content.ReadAsAsync<int>().Result; return data; } else return 0; } #endregion //Statistic Service #region General Service /// <summary> /// 获取房间属性列表 /// </summary> /// <returns></returns> public IEnumerable<RoomFunctionCode> GetFunctionCodeList() { ApiService api = new ApiService(); HttpResponseMessage response = api.Get("GeneralProperty?name=RoomFunctionCode"); if (response.IsSuccessStatusCode) { var data = response.Content.ReadAsAsync<IEnumerable<RoomFunctionCode>>().Result; return data; } else return null; } #endregion //General Service } }
using GalaSoft.MvvmLight.Messaging; using System; namespace ProConstructionsManagment.Desktop.Services { public class MessengerService : IMessengerService { public void Send<TMessage>(TMessage message) { Messenger.Default.Send(message); } public void Register<TMessage>(object receipient, Action<TMessage> action) { Messenger.Default.Register(receipient, action); } public void UnregisterAllMessages(object context) { Messenger.Default.Unregister(context); } } }
 #region Namespace Imports using System; using System.Windows; using System.Windows.Controls; #endregion namespace Vasu.Wpf.Controls { /// <summary> /// Defines a <see cref="PropertyEditor"/> used in <see cref="PropertyGrid"/>. /// </summary> internal class PropertyEditor : IDisposable { #region Ctor public PropertyEditor(FrameworkElement editor, PropertyField field) { Init(editor, field); } private void Init(FrameworkElement editor, PropertyField field) { VisualEditor = editor; Field = field; WireEditor(); } #endregion #region Memebers public FrameworkElement VisualEditor { get; private set; } public PropertyField Field { get; private set; } #endregion #region Implementations private void WireEditor() { if (VisualEditor is TextBox) (VisualEditor as TextBox).TextChanged += OnTextChanged; else if (VisualEditor is ComboBox) (VisualEditor as ComboBox).SelectionChanged += OnSelectionChanged; } private void UnWireEditor() { if (VisualEditor is TextBox) (VisualEditor as TextBox).TextChanged -= OnTextChanged; else if (VisualEditor is ComboBox) (VisualEditor as ComboBox).SelectionChanged += OnSelectionChanged; } #endregion #region Events and Handlers /// <summary> /// Raised when the value is changed by the <see cref="PropertyGrid"/>. /// </summary> public event ValueChangedEventHandler RequestValueChange; private void RaiseRequestValueChange(object newValue) { var handler = RequestValueChange; if (handler != null) handler(this, new ValueChangedEventArgs(Field.Name, Field.PropertyDescriptor, Field.PropertyInfo, Field.SourceObject, newValue, Field.Value)); } private void OnTextChanged(object sender, EventArgs e) { var textBox = sender as TextBox; if (textBox == null) return; RaiseRequestValueChange(textBox.Text); } private void OnSelectionChanged(object sender, EventArgs e) { var comboBox = sender as ComboBox; if (comboBox == null) return; RaiseRequestValueChange(comboBox.SelectedValue); } #endregion #region IDisposable public void Dispose() { UnWireEditor(); VisualEditor = null; Field = null; } #endregion } }
using System; namespace CompressionStocking { public class VibrationMotor : IIndicator { public void On() { Console.WriteLine("VibrationMotor::On() is called"); } public void Off() { Console.WriteLine("VibrationMotor::Off() is called"); } } }
namespace Tresana.Data.DataAccess.Migrations { using System; using System.Data.Entity.Migrations; public partial class init : DbMigration { public override void Up() { CreateTable( "dbo.Priorities", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Weight = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Projects", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), StartDate = c.DateTime(nullable: false), Duedate = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Users", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), LastName = c.String(), UserName = c.String(), Mail = c.String(), Project_Id = c.Int(), Task_Id = c.Int(), Team_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Projects", t => t.Project_Id) .ForeignKey("dbo.Tasks", t => t.Task_Id) .ForeignKey("dbo.Teams", t => t.Team_Id) .Index(t => t.Project_Id) .Index(t => t.Task_Id) .Index(t => t.Team_Id); CreateTable( "dbo.Status", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Ordinal = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Tasks", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Description = c.String(), StartDate = c.DateTime(nullable: false), FinishDate = c.DateTime(nullable: false), Estimation = c.Int(), CreationDate = c.DateTime(nullable: false), DueDate = c.DateTime(nullable: false), Creator_Id = c.Int(), Priority_Id = c.Int(), Status_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.Creator_Id) .ForeignKey("dbo.Priorities", t => t.Priority_Id) .ForeignKey("dbo.Status", t => t.Status_Id) .Index(t => t.Creator_Id) .Index(t => t.Priority_Id) .Index(t => t.Status_Id); CreateTable( "dbo.Teams", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Url = c.String(), }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.Users", "Team_Id", "dbo.Teams"); DropForeignKey("dbo.Tasks", "Status_Id", "dbo.Status"); DropForeignKey("dbo.Users", "Task_Id", "dbo.Tasks"); DropForeignKey("dbo.Tasks", "Priority_Id", "dbo.Priorities"); DropForeignKey("dbo.Tasks", "Creator_Id", "dbo.Users"); DropForeignKey("dbo.Users", "Project_Id", "dbo.Projects"); DropIndex("dbo.Tasks", new[] { "Status_Id" }); DropIndex("dbo.Tasks", new[] { "Priority_Id" }); DropIndex("dbo.Tasks", new[] { "Creator_Id" }); DropIndex("dbo.Users", new[] { "Team_Id" }); DropIndex("dbo.Users", new[] { "Task_Id" }); DropIndex("dbo.Users", new[] { "Project_Id" }); DropTable("dbo.Teams"); DropTable("dbo.Tasks"); DropTable("dbo.Status"); DropTable("dbo.Users"); DropTable("dbo.Projects"); DropTable("dbo.Priorities"); } } }
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.Data; namespace YiXiangLibrary { public partial class d_bibgli_del : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void AgainButton_Click(object sender, EventArgs e) { PatientName.Text = " "; PatientID.Text = " "; } protected void DelButton_Click(object sender, EventArgs e) { try { string connstr = "server=.;database=yixiang;Integrated Security=SSPI"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); //连接并且打开数据库 SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select * from records where u_idcard = '" + PatientID.Text + "' and u_name ='" + PatientName.Text + "'"; SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { dr.Close(); cmd.CommandText = "delete from records where u_idcard = '" + PatientID.Text + "' "; cmd.ExecuteNonQuery(); catchLabel.Text = "删除成功!"; } else { catchLabel.Text = "身份证与姓名不符,请重新输入!"; dr.Close(); } conn.Close(); } catch (Exception err) { catchLabel.Text = err.ToString(); } } } }