text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using Aqueduct.Extensions; using Aqueduct.Domain; using System.Collections; using Aqueduct.Common; using Aqueduct.DataAccess; namespace Aqueduct.SitecoreLib.DataAccess.ValueResolvers { public class DomainEntityListResolver : IValueResolver { private IDomainEntityRepository m_repository; private ISitecoreDataAccessSettings m_settings; private ISitecoreDataAccessSettings Settings { get { if (m_settings == null) return SitecoreDataAccess.Settings; return m_settings; } } public DomainEntityListResolver(IDomainEntityRepository repository, ISitecoreDataAccessSettings settings) { m_settings = settings; m_repository = repository; } public DomainEntityListResolver(IDomainEntityRepository repository) : this(repository, null) { } #region IValueResolver Members public bool CanResolve(Type type) { return IsGenericListOfEnities(type); } public object ResolveEntityPropertyValue(string rawValue, Type propertyType) { Type genericParameterType = propertyType.GetGenericArguments()[0]; if (rawValue.IsNullOrEmpty()) return CreateEmptyTypedList(genericParameterType); return CreateLazyList(genericParameterType, () => { IList list = CreateEmptyTypedList(genericParameterType); var delimiter = new[] { Settings.ValueDelimiter }; string[] itemIds = rawValue.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); IMap listTypeMap = MapFinder.FindMap(genericParameterType); foreach ( ISitecoreDomainEntity entity in m_repository.GetEntities(itemIds.Select(itemId => new Guid(itemId)), listTypeMap)) { list.Add(entity); } return list; }); } public object ResolveItemFieldValue(object rawValue) { throw new NotImplementedException(); } #endregion private static IList CreateEmptyTypedList(Type argType) { return Activator.CreateInstance(typeof(List<>).MakeGenericType(argType)) as IList; } private static IList CreateLazyList(Type genericParameterType, Func<IEnumerable> loader) { return Activator.CreateInstance(typeof(LazyList<>).MakeGenericType(genericParameterType), loader) as IList; } private static bool IsGenericListOfEnities(Type propertyType) { return propertyType.IsGenericType && IsGenericIList(propertyType) && IsGenericParameterOfTypeISitecoreDomainEnitity(propertyType); } private static bool IsGenericParameterOfTypeISitecoreDomainEnitity(Type propertyType) { return typeof(ISitecoreDomainEntity).IsAssignableFrom(propertyType.GetGenericArguments()[0]); } private static bool IsGenericIList(Type propertyType) { return propertyType.GetGenericTypeDefinition() == typeof(IList<>); } } }
using System; using System.IO; using System.Reflection; using OpenQA.Selenium.Chrome; namespace SeleniumWebCheck { class Program { static void Main(string[] args) { // ChromeOptionsオブジェクトを生成 var options = new ChromeOptions(); // --headlessを追加 options.AddArgument("--headless"); // ChromeOptions付きでChromeDriverオブジェクトを生成 var chrome = new ChromeDriver(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), options); // URLに移動 chrome.Url = @"https://scout.nezas.net/auth/login"; // タイトルを表示 Console.WriteLine(chrome.Title); // ログインID(メールアドレス)入力 var elementLoginId = chrome.FindElement(OpenQA.Selenium.By.Name("email")); elementLoginId.SendKeys("testnezas+support02@e2info.com"); // パスワード入力 var elementPassword = chrome.FindElement(OpenQA.Selenium.By.Name("password")); elementPassword.SendKeys("qX4CermARKQv"); // ログインボタンをクリック var elementLoginButton = chrome.FindElement(OpenQA.Selenium.By.CssSelector(".btn")); elementLoginButton.Click(); // マイページ画面に遷移したことを確認 var elementLoginUser = chrome.FindElement(OpenQA.Selenium.By.ClassName("active")).Text; Console.WriteLine(elementLoginUser); // すぐ終了しないよう、キーが押されるまで待機 Console.ReadKey(); // ブラウザを閉じる chrome.Quit(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FourGimmick : IMap { public override void InitMap() { base.InitMap(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; [System.Serializable] public class IInteraction { public KeyCode interactionKey; public UnityEvent onClick; public string description; }
using UnityEngine; using System.Collections; namespace Minigame31 { public class Trash : MonoBehaviour { #region variables public Direction currentDirection; #endregion void OnTriggerEnter(Collider other) { switch(other.name) { case "Collider": MiniGame31_Manager.instance.TrashInTheBasket(this); break; case "ColliderGameEnd": MiniGame31_Manager.instance.TrashOnTheFloor(this); break; } } public void Hide() { gameObject.SetActive(false); } } }
using UnityEngine; namespace TypingGameKit.AlienTyping { /// <summary> /// Displays the result panel. /// </summary> public class ResultsPanel : MonoBehaviour { [SerializeField] private GameObject _content = null; [SerializeField] private UnityEngine.UI.Text _titleText = null; [SerializeField] private UnityEngine.UI.Text _scoreText = null; [SerializeField] private UnityEngine.UI.Text _highScoreText = null; private void Awake() { _content.SetActive(false); } private void GameOver() { AlienGameManager.Instance.Pause(); _titleText.text = "Game Over"; _content.SetActive(true); UpdateScore(); } private void LevelCompleted() { AlienGameManager.Instance.Pause(); _titleText.text = "Level Completed"; _content.SetActive(true); UpdateScore(); } private void Start() { AlienGameManager.Instance.OnGameOver += GameOver; AlienGameManager.Instance.OnLevelCompleted += LevelCompleted; } private void UpdateScore() { var currentScore = AlienGameManager.Instance.Score; var highestScore = HighScore.GetHighScore(); if (currentScore > highestScore) { HighScore.SetHighScore(currentScore); _scoreText.text = currentScore.ToString(); _highScoreText.text = "-"; } else { _scoreText.text = $"{currentScore}"; _highScoreText.text = $"{highestScore}"; } } } }
using System; namespace Pryda.GUnit { static class PkgCmdIDList { public const uint cmdidGUnitTool = 0x101; public const uint cmdidRunEnabled = 0x2001; public const uint cmdidDebugEnabled = 0x2002; public const uint cmdidStopRun = 0x2003; public const uint cmdidShowResults = 0x2004; }; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SalaoG.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoginView : ContentPage { public LoginView() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); MessagingCenter.Subscribe<LoginException>(this, "FalhaLogin", async (exc) => { await DisplayAlert("Login", exc.Message, "Ok"); }); } protected override void OnDisappearing() { base.OnDisappearing(); MessagingCenter.Unsubscribe<LoginException>(this, "FalhaLogin"); } private async void RecuperaSenha(object sender, EventArgs e) { // MainPage = new SalaoG.Views.RecuperaSenha(); await Navigation.PushModalAsync(new RecuperaSenha()); //DisplayAlert("Login", "Senha enviada por e-mail", "Ok"); } //private async void Button_Clicked(object sender, EventArgs e) //{ // await Navigation.PushAsync(new Menu()); //} //private async void Button_Clicked_1(object sender, EventArgs e) //{ // await Navigation.PopAsync(new RecuperaSenha(), true); // //await Navigation.PushAsync(new Menu()); //} } }
using System; namespace Framework.Db.LightWeight { public class CxLwColumn { public string Name { get; set; } public Type DataType { get; set; } public override string ToString() { return Name ?? base.ToString(); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.DataStudio.Solutions.Helpers; using Microsoft.DataStudio.Solutions.Validators; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.RetryPolicies; using Microsoft.WindowsAzure.Storage.Table; namespace Microsoft.DataStudio.Solutions.Tables { public class TableStorage<T> : ITableStorage<T> where T : TableEntity, new() { // Batch operations are limited to 100 items. private const int MaxBatchSize = 100; // ReSharper disable once StaticMemberInGenericType private static readonly TableRequestOptions DefaultRequestOptions = new TableRequestOptions { RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 3) }; protected readonly CloudTable CloudTable; public TableStorage(string tableName, string connectionString) : this(tableName, CloudStorageAccount.Parse(connectionString), DefaultRequestOptions) { } public TableStorage(string tableName, CloudStorageAccount storageAccount, TableRequestOptions tableRequestOptions = null) { Validate.TableName(tableName, "tableName"); tableRequestOptions = tableRequestOptions ?? DefaultRequestOptions; var cloudTableClient = storageAccount.CreateCloudTableClient(); cloudTableClient.DefaultRequestOptions = tableRequestOptions; this.CloudTable = cloudTableClient.GetTableReference(tableName); this.CloudTable.CreateIfNotExists(); } public virtual async Task CreateEntityAsync(T entity) { ThrowIf.Null(entity, "entity"); var insertOperation = TableOperation.Insert(entity); await CloudTable.ExecuteAsync(insertOperation); } public virtual async Task CreateEntitiesAsync(IEnumerable<T> entities) { ThrowIf.Null(entities, "entities"); var batchOperation = new TableBatchOperation(); foreach (var entity in entities) { batchOperation.Insert(entity); } await CloudTable.ExecuteBatchAsync(batchOperation); } public virtual async Task DeleteEntityAsync(string partitionKey, string rowKey) { Validate.TablePropertyValue(partitionKey, "partitionKey"); Validate.TablePropertyValue(rowKey, "rowKey"); var retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey); var retrievedResult = await CloudTable.ExecuteAsync(retrieveOperation); var entityToDelete = retrievedResult.Result as T; if (entityToDelete != null) { var deleteOperation = TableOperation.Delete(entityToDelete); await CloudTable.ExecuteAsync(deleteOperation); } } public virtual async Task DeleteEntitiesByPartitionKeyAsync(string partitionKey) { Validate.TablePropertyValue(partitionKey, "partitionKey"); var query = new TableQuery<T>() .Where(TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, partitionKey)); var results = await CloudTable.ExecuteQueryAsync(query); var batchOperation = new TableBatchOperation(); var counter = 0; foreach (var entity in results) { batchOperation.Delete(entity); counter++; // When we reach MaxBatchSize, we commit and clear the operation if (counter == MaxBatchSize) { await CloudTable.ExecuteBatchAsync(batchOperation); batchOperation = new TableBatchOperation(); counter = 0; } } } public async Task DeleteEntitiesByRowKeyAsync(string rowKey) { Validate.TablePropertyValue(rowKey, "rowKey"); var query = new TableQuery<T>() .Where(TableQuery.GenerateFilterCondition( "RowKey", QueryComparisons.Equal, rowKey)); var results = await CloudTable.ExecuteQueryAsync(query); var batchOperation = new TableBatchOperation(); var counter = 0; foreach (var entity in results) { batchOperation.Delete(entity); counter++; // When we reach MaxBatchSize, we commit and clear the operation if (counter == MaxBatchSize) { await CloudTable.ExecuteBatchAsync(batchOperation); batchOperation = new TableBatchOperation(); counter = 0; } } } public async Task<T> GetEntityAsync(string partitionKey, string rowKey) { var retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey); var retrievedResult = await CloudTable.ExecuteAsync(retrieveOperation); return retrievedResult.Result as T; } public async Task<IEnumerable<T>> GetEntitiesByPartitionKeyAsync(string partitionKey) { Validate.TablePropertyValue(partitionKey, "partitionKey"); var query = new TableQuery<T>() .Where(TableQuery.GenerateFilterCondition( "PartitionKey", QueryComparisons.Equal, partitionKey)); return await CloudTable.ExecuteQueryAsync(query); } public async Task<IEnumerable<T>> GetEntitiesByRowKeyAsync(string rowKey) { Validate.TablePropertyValue(rowKey, "rowKey"); var query = new TableQuery<T>() .Where(TableQuery.GenerateFilterCondition( "RowKey", QueryComparisons.Equal, rowKey)); return await CloudTable.ExecuteQueryAsync(query); } public async Task InsertOrUpdateAsync(T entity) { ThrowIf.Null(entity, "entity"); var insertOrUpdateOperation = TableOperation.InsertOrMerge(entity); await CloudTable.ExecuteAsync(insertOrUpdateOperation); } public async Task<IEnumerable<T>> ExecuteQueryAsync(TableQuery<T> query, CancellationToken ct) { return await this.CloudTable.ExecuteQueryAsync(query, ct); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FileMerger { /// <summary> /// 运行参数 /// </summary> public class Config { // 源控制 public string Folder { get; set; } public string[] Extensions { get; set; } public string Encoding { get; set; } // 辅助参数 public bool SkipBlankLines { get; set; } public bool SkipCommentLines { get; set; } public bool OpenWhenFinished { get; set; } // 输出控制 public string OutFile { get; set; } public int OutLines { get; set; } = 9000; public Encoding Enc { get { try { return System.Text.Encoding.GetEncoding(this.Encoding); } catch (Exception ex) { return System.Text.Encoding.UTF8; } } } } }
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.Shapes; using MySql.Data.MySqlClient; using System.Data; namespace WS.Forms { /// <summary> /// Логика взаимодействия для SettingsForm.xaml /// </summary> public partial class SettingsForm : Window { private User editUser; private MySqlDataAdapter AdapterDataGrid; private MySqlDataAdapter AdapterDataGrid1; private MySqlDataAdapter AdapterDataGrid2; private DataTable dataTable; private DataTable dataTable1; private DataTable dataTable2; public SettingsForm() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { Title = Config.PROGRAM_TITLE + " - " + Config.PROGRAM_TITLE_SETTINGS; if (!UserManager.currentUser.isAdmin) { App.Current.Shutdown(); } } #region DataGrid private void UpdateDataGrid() { dataTable = new DataTable(); AdapterDataGrid = new MySqlDataAdapter("SELECT * FROM `users`", App.database.mysqlConnection); AdapterDataGrid.Fill(dataTable); foreach (DataColumn column in dataTable.Columns) { column.ReadOnly = true; } dataTable.Columns[0].ColumnName = "ID"; dataTable.Columns[1].ColumnName = "Логин"; dataTable.Columns[2].ColumnName = "Хэш"; dataTable.Columns[3].ColumnName = "Фамилия"; dataTable.Columns[4].ColumnName = "Имя"; dataTable.Columns[5].ColumnName = "Отчество"; dataTable.Columns[6].ColumnName = "Активированный аккаунт"; dataTable.Columns[7].ColumnName = "Администратор"; dataGrid.HeadersVisibility = DataGridHeadersVisibility.Column; dataGrid.SelectionMode = DataGridSelectionMode.Single; dataGrid.DataContext = dataTable; AddLoginTextBox.Text = ""; AddSurnameTextBox.Text = ""; AddNameTextBox.Text = ""; AddPatronymicTextBox.Text = ""; EditLoginTextBox.Text = ""; EditSurnameTextBox.Text = ""; EditNameTextBox.Text = ""; EditPatronymicTextBox.Text = ""; AddPassword.Password = ""; EditPassword.Password = ""; AddIsActivatedCheckBox.IsChecked = false; AddIsAdminCheckBox.IsChecked = false; EditIsActivatedCheckBox.IsChecked = false; EditIsAdminCheckBox.IsChecked = false; EditIsActivatedCheckBox.IsEnabled = false; EditIsAdminCheckBox.IsEnabled = false; AddButton.IsEnabled = false; EditButton.IsEnabled = false; DeleteButton.IsEnabled = false; Utils.SetErrorOnElement(AddLoginTextBox, false); Utils.SetErrorOnElement(AddSurnameTextBox, false); Utils.SetErrorOnElement(AddNameTextBox, false); Utils.SetErrorOnElement(EditLoginTextBox, false); Utils.SetErrorOnElement(EditSurnameTextBox, false); Utils.SetErrorOnElement(EditNameTextBox, false); Utils.SetErrorOnElement(AddPassword, false); Utils.SetErrorOnElement(EditPassword, false); editUser = new User(); } private void DataGrid_Loaded(object sender, RoutedEventArgs e) { UpdateDataGrid(); } private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count != 0) { DataRowView view = (DataRowView)dataGrid.SelectedItem; editUser = new User(view); EditLoginTextBox.Text = editUser.login; EditPassword.Password = "WS_PASSWORD"; EditSurnameTextBox.Text = editUser.surname; EditNameTextBox.Text = editUser.name; EditPatronymicTextBox.Text = editUser.patronymic; EditIsActivatedCheckBox.IsChecked = editUser.isActivated; EditIsAdminCheckBox.IsChecked = editUser.isAdmin; EditButton.IsEnabled = true; if (editUser.login != UserManager.currentUser.login) { EditIsActivatedCheckBox.IsEnabled = true; EditIsAdminCheckBox.IsEnabled = true; DeleteButton.IsEnabled = true; } else { EditIsActivatedCheckBox.IsEnabled = false; EditIsAdminCheckBox.IsEnabled = false; DeleteButton.IsEnabled = false; } } } private void AddLoginTextBox_TextChanged(object sender, TextChangedEventArgs e) { Utils.ButtonCheck(AddButton, AddLoginTextBox, AddPassword, AddSurnameTextBox, AddNameTextBox); } private void AddPassword_PasswordChanged(object sender, RoutedEventArgs e) { Utils.ButtonCheck(AddButton, AddLoginTextBox, AddPassword, AddSurnameTextBox, AddNameTextBox); } private void AddSurnameTextBox_TextChanged(object sender, TextChangedEventArgs e) { Utils.ButtonCheck(AddButton, AddLoginTextBox, AddPassword, AddSurnameTextBox, AddNameTextBox); } private void AddNameTextBox_TextChanged(object sender, TextChangedEventArgs e) { Utils.ButtonCheck(AddButton, AddLoginTextBox, AddPassword, AddSurnameTextBox, AddNameTextBox); } private void AddButton_Click(object sender, RoutedEventArgs e) { User newUser = new User(); newUser.login = AddLoginTextBox.Text; newUser.passHash = Utils.CalculateMD5(AddPassword.Password); newUser.surname = AddSurnameTextBox.Text; newUser.name = AddNameTextBox.Text; newUser.patronymic = AddPatronymicTextBox.Text; newUser.isActivated = AddIsActivatedCheckBox.IsChecked ?? false; newUser.isAdmin = AddIsAdminCheckBox.IsChecked ?? false; if (UserManager.TryRegister(newUser)) { UpdateDataGrid(); } else { MessageBox.Show("Не удалось зарегистрировать пользователя!\nВозможно данный логин уже занят", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); AddPassword.Password = ""; Utils.ButtonCheck(AddButton, AddLoginTextBox, AddPassword, AddSurnameTextBox, AddNameTextBox); } } private void EditLoginTextBox_TextChanged(object sender, TextChangedEventArgs e) { Utils.ButtonCheck(EditButton, EditLoginTextBox, EditPassword, EditSurnameTextBox, EditNameTextBox); } private void EditPassword_PasswordChanged(object sender, RoutedEventArgs e) { Utils.ButtonCheck(EditButton, EditLoginTextBox, EditPassword, EditSurnameTextBox, EditNameTextBox); } private void EditSurnameTextBox_TextChanged(object sender, TextChangedEventArgs e) { Utils.ButtonCheck(EditButton, EditLoginTextBox, EditPassword, EditSurnameTextBox, EditNameTextBox); } private void EditNameTextBox_TextChanged(object sender, TextChangedEventArgs e) { Utils.ButtonCheck(EditButton, EditLoginTextBox, EditPassword, EditSurnameTextBox, EditNameTextBox); } private void EditButton_Click(object sender, RoutedEventArgs e) { editUser.login = EditLoginTextBox.Text; if (EditPassword.Password != "WS_PASSWORD") { editUser.passHash = Utils.CalculateMD5(EditPassword.Password); } editUser.surname = EditSurnameTextBox.Text; editUser.name = EditNameTextBox.Text; editUser.patronymic = EditPatronymicTextBox.Text; editUser.isActivated = EditIsActivatedCheckBox.IsChecked ?? false; editUser.isAdmin = EditIsAdminCheckBox.IsChecked ?? false; UserManager.EditUser(editUser); UpdateDataGrid(); } private void DeleteButton_Click(object sender, RoutedEventArgs e) { if (MessageBox.Show("Вы действительно хотите удалить пользователя " + editUser.login + "?", "Внимание!", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) { App.database.QueryNon("DELETE FROM users WHERE id = " + editUser.id); UpdateDataGrid(); } } #endregion #region DataGridCities private void dataGrid1_Loaded(object sender, RoutedEventArgs e) { dataTable1 = new DataTable(); AdapterDataGrid1 = new MySqlDataAdapter("SELECT * FROM `cities`", App.database.mysqlConnection); AdapterDataGrid1.FillAsync(dataTable1); string ai_index = App.database.Query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'ws' AND TABLE_NAME = 'cities'")[0][0]; dataTable1.Columns[0].ColumnName = "ID"; dataTable1.Columns[1].ColumnName = "Город"; dataTable1.Columns[0].AutoIncrement = true; dataTable1.Columns[0].AutoIncrementSeed = Convert.ToInt32(ai_index); dataTable1.Columns[0].ReadOnly = true; dataGrid1.DataContext = dataTable1; } private void SaveButton_Click(object sender, RoutedEventArgs e) { DataTable changes = dataTable1.GetChanges(); changes.Columns[0].ColumnName = "id"; changes.Columns[1].ColumnName = "city"; if (dataTable1.GetChanges() != null) { MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(AdapterDataGrid1); AdapterDataGrid1.Update(changes); dataTable1.AcceptChanges(); } } private void CancelButton_Click(object sender, RoutedEventArgs e) { dataTable1.RejectChanges(); } #endregion #region DataGridConsults private void dataGrid2_Loaded(object sender, RoutedEventArgs e) { dataTable2 = new DataTable(); AdapterDataGrid2 = new MySqlDataAdapter("SELECT * FROM `consults`", App.database.mysqlConnection); AdapterDataGrid2.FillAsync(dataTable2); string ai_index = App.database.Query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'ws' AND TABLE_NAME = 'consults'")[0][0]; dataTable2.Columns[0].ColumnName = "ID"; dataTable2.Columns[1].ColumnName = "Тип консультации"; dataTable2.Columns[0].AutoIncrement = true; dataTable2.Columns[0].AutoIncrementSeed = Convert.ToInt32(ai_index); dataTable2.Columns[0].ReadOnly = true; dataGrid2.DataContext = dataTable2; } private void ButtonSave1_Click(object sender, RoutedEventArgs e) { DataTable changes = dataTable2.GetChanges(); changes.Columns[0].ColumnName = "id"; changes.Columns[1].ColumnName = "type"; if (dataTable2.GetChanges() != null) { MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(AdapterDataGrid2); AdapterDataGrid2.Update(changes); dataTable2.AcceptChanges(); } } private void CancelButton1_Click(object sender, RoutedEventArgs e) { dataTable2.RejectChanges(); } #endregion } }
using CTP; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JiangJihua.SlippageHunter { /// <summary> /// 封装CTP,加入1秒钟不准许查询多次的限制功能 /// </summary> public class CTPTrader : CTPTraderAdapter { } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TestInheritance.DomainModels; using NHibernate.Mapping.ByCode.Conformist; namespace TestInheritance.DomainModelMappings { public class BusinessEntityMapping : ClassMapping<BusinessEntity> { public BusinessEntityMapping() { Table("Person.BusinessEntity"); Id(x => x.BusinessEntityID, m => m.Generator(NHibernate.Mapping.ByCode.Generators.Identity)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _09_Multitude5ZeroSum { class Program { static void Main(string[] args) { const int NUMBERS_COUNT = 5; double[] number = new double[5]; bool subsetFound = false; try { number[0] = double.Parse(Console.In.ReadLine()); number[1] = double.Parse(Console.In.ReadLine()); number[2] = double.Parse(Console.In.ReadLine()); number[3] = double.Parse(Console.In.ReadLine()); number[4] = double.Parse(Console.In.ReadLine()); } catch (FormatException) { Console.WriteLine("Please, input valid number values."); return; } catch (OverflowException) { Console.WriteLine("Please, input valid number."); return; } for (int startPosition = 0; startPosition < NUMBERS_COUNT; startPosition++) { double sum = 0; for (int endPosition = startPosition; endPosition < NUMBERS_COUNT; endPosition++) { sum += number[endPosition]; if (sum == 0) { Console.Write("Subset found: "); subsetFound = true; for (int interator = startPosition; interator <= endPosition; interator++) { Console.Write("{0} ", number[interator]); } Console.WriteLine(); } } } if (subsetFound = false) { Console.WriteLine("No subset found!"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignment_1 { class SortedList { static void Main() { // ::: Declare two integer arrays with five elements each int[] array1 = { 1, 2, 3, 4, 5 }; int[] array2 = { 6, 7, 8, 9, 10 }; // ::: Loop through the two arrays and print them foreach (int element in array1) { Console.WriteLine(element); } Console.WriteLine("--------------------------------------------"); foreach (int element in array2) { Console.WriteLine(element); } Console.WriteLine("--------------------------------------------"); // ::: Create new List of integers and call AddRange twice var list = new List<int>(); list.AddRange(array1); list.AddRange(array2); // ::: Call ToArray to convert List to array int[] array3 = list.ToArray(); // ::: Loop through array elements of combined array and print them foreach (int element in array3) { Console.WriteLine(element); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace ArgosyPack { public class Wem { public int loadedId; public string name { get; set; } public uint id { get; set; } public uint length { get; set; } public byte[] file; public Wem(string aName, string aId, BinaryReader aFile, int loadId) { loadedId = loadId; name = Path.GetFileName(aName); id = Convert.ToUInt32(aId); length = (uint)aFile.BaseStream.Length; file = aFile.ReadBytes((int)length); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using System.Linq; using dojoTest.Models; using Microsoft.AspNetCore.Identity; namespace dojoTest.Controllers { public class UserController : Controller { private DojoContext _context; public UserController(DojoContext context) { _context = context; } [HttpGet] [Route("")] public IActionResult RegisterPage() { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return View("Register"); } else { return RedirectToAction("Dashboard", "Home"); } } [HttpGet] [Route("/login")] public IActionResult LoginPage() { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return View("Login"); } else { return RedirectToAction("Dashboard", "Home"); } } [HttpPost] [Route("register")] public IActionResult Register (Register regUser) { if(ModelState.IsValid) { User exists = _context.Users.SingleOrDefault(user=>user.Email == regUser.Email); if(exists !=null) { ModelState.AddModelError("Email", "An account with this email already exists!"); return View("Register"); } else { PasswordHasher<Register> Hasher = new PasswordHasher<Register>(); string hashed = Hasher.HashPassword(regUser, regUser.Password); User newUser = new User { FirstName = regUser.FirstName, LastName = regUser.LastName, Email = regUser.Email, Password = hashed }; _context.Add(newUser); _context.SaveChanges(); User user = _context.Users.Where(u=>u.Email == regUser.Email).SingleOrDefault(); HttpContext.Session.SetInt32("userId", user.UserId); HttpContext.Session.SetString("name", user.FirstName + " " + user.LastName); return RedirectToAction("Dashboard", "Home"); } } else { return View("Register"); } } [HttpPost] [Route("loginuser")] public IActionResult Login (Login loginUser) { if(ModelState.IsValid) { User exists = _context.Users.Where(u=>u.Email == loginUser.Email).SingleOrDefault(); if(exists == null) { ModelState.AddModelError("Error", "Email not found"); return View("Login"); } else { var hasher = new PasswordHasher<User>(); if(hasher.VerifyHashedPassword(exists, exists.Password, loginUser.Password) == 0) { ModelState.AddModelError("Password", "Password incorrect"); return View("Login"); } else { HttpContext.Session.SetInt32("userId", exists.UserId); HttpContext.Session.SetString("name", exists.FirstName + " " + exists.LastName); int? id = HttpContext.Session.GetInt32("userId"); return RedirectToAction("Dashboard", "Home"); } } } else { return View("Login"); } } [HttpGet] [Route("logout")] public IActionResult Logout() { HttpContext.Session.Clear(); return RedirectToAction("LoginPage"); } } }
using CheckMySymptoms.Utils; namespace CheckMySymptoms.Forms.View { //[JsonConverter(typeof(ViewConverter))] public abstract class ViewBase { public string TypeFullName { get { return this.GetType().ToTypeString(); } } public abstract void UpdateFields(object fields); } }
using System.Threading.Tasks; using VideoServiceBL.DTOs.MoviesDtos; using VideoServiceBL.DTOs.RentalsDtos; namespace VideoServiceBL.Services.Interfaces { public interface IRentalService : IBaseService<RentalDto> { Task<QueryResultDto<RentalDto>> GetAllRentalMoviesAsync(RentalDataTableSettings settings); Task<QueryResultDto<RentalDto>> GetAllRentalMoviesWithUsersAsync(RentalDataTableSettings settings); Task AddRentalByUserIdAndMovieIdAsync(AddRentalDto model); } }
using System; using System.Collections.Generic; using System.Linq; namespace Lab3 { class Program { class Bucket { public int Timestamp; public int Size; public Bucket() { Timestamp = 1; Size = 1; } } static void Main(string[] args) { var N = int.Parse(Console.ReadLine()); var buckets = new LinkedList<Bucket>(); string line; while (!string.IsNullOrWhiteSpace( line = Console.ReadLine() )) { line.Trim(); if (line.StartsWith("q")) { var k = int.Parse(line.Split(' ')[1]); var bound = buckets.Where(b => b.Timestamp <= k); var first = bound.FirstOrDefault() != null ? (bound.First().Size / 2) : 0; var result = first + bound.Skip(1).Select(b => b.Size).Sum(); Console.WriteLine(result); } else { foreach (var bit in line) { foreach (var b in buckets) b.Timestamp++; if (buckets.Count > 0 && buckets.First.Value.Timestamp > N) buckets.RemoveFirst(); if (bit == '1') { buckets.AddLast(new Bucket()); var hasBucketsToMerge = buckets.Count >= 3; var checkFrom = buckets.Count - 1; while (hasBucketsToMerge) { hasBucketsToMerge = false; var counter = 1; // checkElem is the first var i = buckets.Count; Bucket checkElem = null; foreach (var elem in buckets.Reverse()) { i--; if (i == checkFrom) checkElem = elem; if (i >= checkFrom) continue; if (elem.Size == checkElem.Size) { counter++; if (counter == 3) { hasBucketsToMerge = true; break; } } } if (hasBucketsToMerge) { checkFrom -= 2; buckets.Remove(buckets.ElementAt(checkFrom)); buckets.ElementAt(checkFrom).Size *= 2; hasBucketsToMerge = hasBucketsToMerge && checkFrom >= 2; } } } } } } } } }
using LowLevelNetworking.Shared; using System; using System.Text; using System.Linq; using BinaryConversions; namespace WUIShared.Packets { public enum PacketTypes { PlayerJoined, PlayerLeft, SpawnGameObject, ChangeGameObjectUID, FreeTempUID, DestroyGameObject, SetParentOfGameObject, OwnershipPacket, AssetSend, TransformPositionSet, TransformSizeSet, RawTextureRendererTextureSet, RawTextureRendererRotationSet, PlayerSpeedSet, MovingObjectClientCollision, CameraSetFollow, SendLocalScripts, ScriptSendString, ByteArrayUserPacket, SaveWorldPacket, } public class PlayerJoined : Packet { public override int PacketType { get; } = (int)PacketTypes.PlayerJoined; public override int Size { get => +4 + 4 + 4 + username.Length; } public override int RawSerializeSize => Size + 5; public int PID; public int UID; public string username; public PlayerJoined() { } public PlayerJoined(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(PID >> 0); arr[start++] = (byte)(PID >> 8); arr[start++] = (byte)(PID >> 16); arr[start++] = (byte)(PID >> 24); } unchecked { arr[start++] = (byte)(UID >> 0); arr[start++] = (byte)(UID >> 8); arr[start++] = (byte)(UID >> 16); arr[start++] = (byte)(UID >> 24); } unchecked { arr[start++] = (byte)(username.Length >> 0); arr[start++] = (byte)(username.Length >> 8); arr[start++] = (byte)(username.Length >> 16); arr[start++] = (byte)(username.Length >> 24); } Encoding.ASCII.GetBytes(username, 0, username.Length, arr, start); start += username.Length; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { PID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; UID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; { int strlen = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; username = ASCIIEncoding.ASCII.GetString(arr, start, strlen); start += strlen; } return start; } public override string ToString() => $"int PID = {PID}\nint UID = {UID}\nstring username = {username}\n"; } public class PlayerLeft : Packet { public override int PacketType { get; } = (int)PacketTypes.PlayerLeft; public override int Size { get => +4; } public override int RawSerializeSize => Size + 5; public int PID; public PlayerLeft() { } public PlayerLeft(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(PID >> 0); arr[start++] = (byte)(PID >> 8); arr[start++] = (byte)(PID >> 16); arr[start++] = (byte)(PID >> 24); } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { PID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; return start; } public override string ToString() => $"int PID = {PID}\n"; } public class SpawnGameObject : Packet { public override int PacketType { get; } = (int)PacketTypes.SpawnGameObject; public override int Size { get => +4 + 4 + 4 + 4 + name.Length; } public override int RawSerializeSize => Size + 5; public int ObjType; public int UID; public int parentUID; public string name; public SpawnGameObject() { } public SpawnGameObject(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(ObjType >> 0); arr[start++] = (byte)(ObjType >> 8); arr[start++] = (byte)(ObjType >> 16); arr[start++] = (byte)(ObjType >> 24); } unchecked { arr[start++] = (byte)(UID >> 0); arr[start++] = (byte)(UID >> 8); arr[start++] = (byte)(UID >> 16); arr[start++] = (byte)(UID >> 24); } unchecked { arr[start++] = (byte)(parentUID >> 0); arr[start++] = (byte)(parentUID >> 8); arr[start++] = (byte)(parentUID >> 16); arr[start++] = (byte)(parentUID >> 24); } unchecked { arr[start++] = (byte)(name.Length >> 0); arr[start++] = (byte)(name.Length >> 8); arr[start++] = (byte)(name.Length >> 16); arr[start++] = (byte)(name.Length >> 24); } Encoding.ASCII.GetBytes(name, 0, name.Length, arr, start); start += name.Length; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { ObjType = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; UID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; parentUID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; { int strlen = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; name = ASCIIEncoding.ASCII.GetString(arr, start, strlen); start += strlen; } return start; } public override string ToString() => $"int ObjType = {ObjType}\nint UID = {UID}\nint parentUID = {parentUID}\nstring name = {name}\n"; } public class ChangeGameObjectUID : Packet { public override int PacketType { get; } = (int)PacketTypes.ChangeGameObjectUID; public override int Size { get => +4 + 4; } public override int RawSerializeSize => Size + 5; public int oldUID; public int newUID; public ChangeGameObjectUID() { } public ChangeGameObjectUID(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(oldUID >> 0); arr[start++] = (byte)(oldUID >> 8); arr[start++] = (byte)(oldUID >> 16); arr[start++] = (byte)(oldUID >> 24); } unchecked { arr[start++] = (byte)(newUID >> 0); arr[start++] = (byte)(newUID >> 8); arr[start++] = (byte)(newUID >> 16); arr[start++] = (byte)(newUID >> 24); } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { oldUID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; newUID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; return start; } public override string ToString() => $"int oldUID = {oldUID}\nint newUID = {newUID}\n"; } public class FreeTempUID : Packet { public override int PacketType { get; } = (int)PacketTypes.FreeTempUID; public override int Size { get => +4; } public override int RawSerializeSize => Size + 5; public int UID; public FreeTempUID() { } public FreeTempUID(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(UID >> 0); arr[start++] = (byte)(UID >> 8); arr[start++] = (byte)(UID >> 16); arr[start++] = (byte)(UID >> 24); } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { UID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; return start; } public override string ToString() => $"int UID = {UID}\n"; } public class DestroyGameObject : Packet { public override int PacketType { get; } = (int)PacketTypes.DestroyGameObject; public override int Size { get => +4; } public override int RawSerializeSize => Size + 5; public int UID; public DestroyGameObject() { } public DestroyGameObject(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(UID >> 0); arr[start++] = (byte)(UID >> 8); arr[start++] = (byte)(UID >> 16); arr[start++] = (byte)(UID >> 24); } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { UID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; return start; } public override string ToString() => $"int UID = {UID}\n"; } public class SetParentOfGameObject : Packet { public override int PacketType { get; } = (int)PacketTypes.SetParentOfGameObject; public override int Size { get => +4 + 4; } public override int RawSerializeSize => Size + 5; public int UID; public int newParentUID; public SetParentOfGameObject() { } public SetParentOfGameObject(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(UID >> 0); arr[start++] = (byte)(UID >> 8); arr[start++] = (byte)(UID >> 16); arr[start++] = (byte)(UID >> 24); } unchecked { arr[start++] = (byte)(newParentUID >> 0); arr[start++] = (byte)(newParentUID >> 8); arr[start++] = (byte)(newParentUID >> 16); arr[start++] = (byte)(newParentUID >> 24); } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { UID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; newParentUID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; return start; } public override string ToString() => $"int UID = {UID}\nint newParentUID = {newParentUID}\n"; } public class OwnershipPacket : Packet { public override int PacketType { get; } = (int)PacketTypes.OwnershipPacket; public override int Size { get => +4 + 1; } public override int RawSerializeSize => Size + 5; public int UID; public bool Owned; public OwnershipPacket() { } public OwnershipPacket(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(UID >> 0); arr[start++] = (byte)(UID >> 8); arr[start++] = (byte)(UID >> 16); arr[start++] = (byte)(UID >> 24); } arr[start++] = (byte)(Owned ? 1 : 0); return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { UID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; Owned = arr[start++] == 1; return start; } public override string ToString() => $"int UID = {UID}\nbool Owned = {Owned}\n"; } public class AssetSend : Packet { public override int PacketType { get; } = (int)PacketTypes.AssetSend; public override int Size { get => +4 + assetName.Length + 4 + asset.Length * +1; } public override int RawSerializeSize => Size + 5; public string assetName; public byte[] asset; public AssetSend() { } public AssetSend(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(assetName.Length >> 0); arr[start++] = (byte)(assetName.Length >> 8); arr[start++] = (byte)(assetName.Length >> 16); arr[start++] = (byte)(assetName.Length >> 24); } Encoding.ASCII.GetBytes(assetName, 0, assetName.Length, arr, start); start += assetName.Length; unchecked { arr[start++] = (byte)(asset.Length >> 0); arr[start++] = (byte)(asset.Length >> 8); arr[start++] = (byte)(asset.Length >> 16); arr[start++] = (byte)(asset.Length >> 24); } for (int i = 0; i < asset.Length; i++) { arr[start++] = asset[i]; } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { { int strlen = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; assetName = ASCIIEncoding.ASCII.GetString(arr, start, strlen); start += strlen; } { int length = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; asset = new byte[length]; for (int i = 0; i < asset.Length; i++) { asset[i] = arr[start++]; } } return start; } public override string ToString() => $"string assetName = {assetName}\nbyte[] asset = {asset}\n"; } public class TransformPositionSet : Packet { public override int PacketType { get; } = (int)PacketTypes.TransformPositionSet; public override int Size { get => +4 + 4; } public override int RawSerializeSize => Size + 1; public float x; public float y; public TransformPositionSet() { } public TransformPositionSet(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; BinConversion.GetBytes(arr, start, x); start += 4; BinConversion.GetBytes(arr, start, y); start += 4; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { BinConversion.GetFloat(arr, start, out x); start += 4; BinConversion.GetFloat(arr, start, out y); start += 4; return start; } public override string ToString() => $"float x = {x}\nfloat y = {y}\n"; } public class TransformSizeSet : Packet { public override int PacketType { get; } = (int)PacketTypes.TransformSizeSet; public override int Size { get => +4 + 4; } public override int RawSerializeSize => Size + 1; public float x; public float y; public TransformSizeSet() { } public TransformSizeSet(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; BinConversion.GetBytes(arr, start, x); start += 4; BinConversion.GetBytes(arr, start, y); start += 4; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { BinConversion.GetFloat(arr, start, out x); start += 4; BinConversion.GetFloat(arr, start, out y); start += 4; return start; } public override string ToString() => $"float x = {x}\nfloat y = {y}\n"; } public class RawTextureRendererTextureSet : Packet { public override int PacketType { get; } = (int)PacketTypes.RawTextureRendererTextureSet; public override int Size { get => +4 + assetName.Length + 4 + 4 + 4; } public override int RawSerializeSize => Size + 1; public string assetName; public float r; public float g; public float b; public RawTextureRendererTextureSet() { } public RawTextureRendererTextureSet(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(assetName.Length >> 0); arr[start++] = (byte)(assetName.Length >> 8); arr[start++] = (byte)(assetName.Length >> 16); arr[start++] = (byte)(assetName.Length >> 24); } Encoding.ASCII.GetBytes(assetName, 0, assetName.Length, arr, start); start += assetName.Length; BinConversion.GetBytes(arr, start, r); start += 4; BinConversion.GetBytes(arr, start, g); start += 4; BinConversion.GetBytes(arr, start, b); start += 4; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { { int strlen = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; assetName = ASCIIEncoding.ASCII.GetString(arr, start, strlen); start += strlen; } BinConversion.GetFloat(arr, start, out r); start += 4; BinConversion.GetFloat(arr, start, out g); start += 4; BinConversion.GetFloat(arr, start, out b); start += 4; return start; } public override string ToString() => $"string assetName = {assetName}\nfloat r = {r}\nfloat g = {g}\nfloat b = {b}\n"; } public class RawTextureRendererRotationSet : Packet { public override int PacketType { get; } = (int)PacketTypes.RawTextureRendererRotationSet; public override int Size { get => +4; } public override int RawSerializeSize => Size + 1; public float rotation; public RawTextureRendererRotationSet() { } public RawTextureRendererRotationSet(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; BinConversion.GetBytes(arr, start, rotation); start += 4; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { BinConversion.GetFloat(arr, start, out rotation); start += 4; return start; } public override string ToString() => $"float rotation = {rotation}\n"; } public class PlayerSpeedSet : Packet { public override int PacketType { get; } = (int)PacketTypes.PlayerSpeedSet; public override int Size { get => +4 + 4; } public override int RawSerializeSize => Size + 1; public float speedX; public float speedY; public PlayerSpeedSet() { } public PlayerSpeedSet(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; BinConversion.GetBytes(arr, start, speedX); start += 4; BinConversion.GetBytes(arr, start, speedY); start += 4; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { BinConversion.GetFloat(arr, start, out speedX); start += 4; BinConversion.GetFloat(arr, start, out speedY); start += 4; return start; } public override string ToString() => $"float speedX = {speedX}\nfloat speedY = {speedY}\n"; } public class MovingObjectClientCollision : Packet { public override int PacketType { get; } = (int)PacketTypes.MovingObjectClientCollision; public override int Size { get => +4 + uidsLength * +4; } public override int RawSerializeSize => Size + 1; public int[] uids; public int uidsLength; public MovingObjectClientCollision() { uids = new int[25]; } public MovingObjectClientCollision(byte[] arr, int start = 0) { uids = new int[25]; DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(uidsLength >> 0); arr[start++] = (byte)(uidsLength >> 8); arr[start++] = (byte)(uidsLength >> 16); arr[start++] = (byte)(uidsLength >> 24); } for (int i = 0; i < uidsLength; i++) { unchecked { arr[start++] = (byte)(uids[i] >> 0); arr[start++] = (byte)(uids[i] >> 8); arr[start++] = (byte)(uids[i] >> 16); arr[start++] = (byte)(uids[i] >> 24); } } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { uidsLength = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; for (int i = 0; i < uidsLength; i++) { uids[i] = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; } return start; } public override string ToString() => $"int[p25] uids = {uids}\n"; } public class CameraSetFollow : Packet { public override int PacketType { get; } = (int)PacketTypes.CameraSetFollow; public override int Size { get => +1 + 1 + 4; } public override int RawSerializeSize => Size + 1; public bool followLocalPlayer; public bool followEnabled; public int followUID; public CameraSetFollow() { } public CameraSetFollow(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; arr[start++] = (byte)(followLocalPlayer ? 1 : 0); arr[start++] = (byte)(followEnabled ? 1 : 0); unchecked { arr[start++] = (byte)(followUID >> 0); arr[start++] = (byte)(followUID >> 8); arr[start++] = (byte)(followUID >> 16); arr[start++] = (byte)(followUID >> 24); } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { followLocalPlayer = arr[start++] == 1; followEnabled = arr[start++] == 1; followUID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; return start; } public override string ToString() => $"bool followLocalPlayer = {followLocalPlayer}\nbool followEnabled = {followEnabled}\nint followUID = {followUID}\n"; } public class SendLocalScripts : Packet { public override int PacketType { get; } = (int)PacketTypes.SendLocalScripts; public override int Size { get => +4 + eventId.Length * +4 + 4 + code.Sum((x) => x != null ? (4 + x.Length) : 0); } public override int RawSerializeSize => Size + 1; public int[] eventId; public string[] code; public SendLocalScripts() { } public SendLocalScripts(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(eventId.Length >> 0); arr[start++] = (byte)(eventId.Length >> 8); arr[start++] = (byte)(eventId.Length >> 16); arr[start++] = (byte)(eventId.Length >> 24); } for (int i = 0; i < eventId.Length; i++) { unchecked { arr[start++] = (byte)(eventId[i] >> 0); arr[start++] = (byte)(eventId[i] >> 8); arr[start++] = (byte)(eventId[i] >> 16); arr[start++] = (byte)(eventId[i] >> 24); } } unchecked { arr[start++] = (byte)(code.Length >> 0); arr[start++] = (byte)(code.Length >> 8); arr[start++] = (byte)(code.Length >> 16); arr[start++] = (byte)(code.Length >> 24); } for (int i = 0; i < code.Length; i++) { unchecked { arr[start++] = (byte)(code[i].Length >> 0); arr[start++] = (byte)(code[i].Length >> 8); arr[start++] = (byte)(code[i].Length >> 16); arr[start++] = (byte)(code[i].Length >> 24); } Encoding.ASCII.GetBytes(code[i], 0, code[i].Length, arr, start); start += code[i].Length; } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { { int length = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; eventId = new int[length]; for (int i = 0; i < eventId.Length; i++) { eventId[i] = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; } } { int length = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; code = new string[length]; for (int i = 0; i < code.Length; i++) { { int strlen = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; code[i] = ASCIIEncoding.ASCII.GetString(arr, start, strlen); start += strlen; } } } return start; } public override string ToString() => $"int[] eventId = {eventId}\nstring[] code = {code}\n"; } public class ScriptSendString : Packet { public override int PacketType { get; } = (int)PacketTypes.ScriptSendString; public override int Size { get => +4 + message.Length; } public override int RawSerializeSize => Size + 1; public string message; public ScriptSendString() { } public ScriptSendString(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(message.Length >> 0); arr[start++] = (byte)(message.Length >> 8); arr[start++] = (byte)(message.Length >> 16); arr[start++] = (byte)(message.Length >> 24); } Encoding.ASCII.GetBytes(message, 0, message.Length, arr, start); start += message.Length; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { { int strlen = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; message = ASCIIEncoding.ASCII.GetString(arr, start, strlen); start += strlen; } return start; } public override string ToString() => $"string message = {message}\n"; } public class ByteArrayUserPacket : Packet { public override int PacketType { get; } = (int)PacketTypes.ByteArrayUserPacket; public override int Size { get => +4 + 4 + dataLength * +1; } public override int RawSerializeSize => Size + 5; public int UID; public byte[] data; public int dataLength; public ByteArrayUserPacket() { data = new byte[8388608]; } public ByteArrayUserPacket(byte[] arr, int start = 0) { data = new byte[8388608]; DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(UID >> 0); arr[start++] = (byte)(UID >> 8); arr[start++] = (byte)(UID >> 16); arr[start++] = (byte)(UID >> 24); } unchecked { arr[start++] = (byte)(dataLength >> 0); arr[start++] = (byte)(dataLength >> 8); arr[start++] = (byte)(dataLength >> 16); arr[start++] = (byte)(dataLength >> 24); } for (int i = 0; i < dataLength; i++) { arr[start++] = data[i]; } return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { UID = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; dataLength = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; for (int i = 0; i < dataLength; i++) { data[i] = arr[start++]; } return start; } public override string ToString() => $"int UID = {UID}\nbyte[p8388608] data = {data}\n"; } public class SaveWorldPacket : Packet { public override int PacketType { get; } = (int)PacketTypes.SaveWorldPacket; public override int Size { get => +4 + name.Length; } public override int RawSerializeSize => Size + 5; public string name; public SaveWorldPacket() { } public SaveWorldPacket(byte[] arr, int start = 0) { DeserializeFrom(arr, start); } public override int SerializeTo(byte[] arr, int start = 0) { arr[start++] = (byte)PacketType; unchecked { arr[start++] = (byte)(Size >> 0); arr[start++] = (byte)(Size >> 8); arr[start++] = (byte)(Size >> 16); arr[start++] = (byte)(Size >> 24); } unchecked { arr[start++] = (byte)(name.Length >> 0); arr[start++] = (byte)(name.Length >> 8); arr[start++] = (byte)(name.Length >> 16); arr[start++] = (byte)(name.Length >> 24); } Encoding.ASCII.GetBytes(name, 0, name.Length, arr, start); start += name.Length; return start; } public override int DeserializeFrom(byte[] arr, int start = 0) { { int strlen = arr[start++] << 0 | arr[start++] << 8 | arr[start++] << 16 | arr[start++] << 24; name = ASCIIEncoding.ASCII.GetString(arr, start, strlen); start += strlen; } return start; } public override string ToString() => $"string name = {name}\n"; } }
using System; using System.Collections.Generic; using System.Text; namespace BoardGame { public class NegativeTile : Tile { private int _position; public NegativeTile(int position) : base(position) { _position = position; } public override string SpecialEvent(Player p) { Random rnd = new Random(); int negEvent = rnd.Next(1, 3); switch(negEvent) { case 1: return SpeedMod(p); case 2: return PositionMod(p); } return "Error with negative special event"; } public string SpeedMod(Player p) { Random rnd = new Random(); int mod = rnd.Next(1,5); p.SpeedMod += mod; return "You feel an empowering burst of energy and your speed has been increased by " + mod.ToString() + " your speed modifier is now " + p.SpeedMod; } public string PositionMod(Player p) { Random rnd = new Random(); int mod = rnd.Next(2, 11); p.Position -= mod; return "A sudden gust of wind knocks you back " + mod.ToString() + " spaces" + " you are now positioned at " + p.Position; } } }
using System; namespace Umbraco.Core.Scoping { // base class for an object that will be enlisted in scope context, if any. it // must be used in a 'using' block, and if not scoped, released when disposed, // else when scope context runs enlisted actions public abstract class ScopeContextualBase : IDisposable { private bool _using, _scoped; public static T Get<T>(IScopeProvider scopeProvider, string key, Func<bool, T> ctor) where T : ScopeContextualBase { var scopeContext = scopeProvider.Context; if (scopeContext == null) return ctor(false); var w = scopeContext.Enlist("ScopeContextualBase_" + key, () => ctor(true), (completed, item) => { item.Release(completed); }); if (w._using) throw new InvalidOperationException("panic: used."); w._using = true; w._scoped = true; return w; } public void Dispose() { _using = false; if (_scoped == false) Release(true); } public abstract void Release(bool completed); } }
using SimuladorPrestamos.BO; using SimuladorPrestamos.DAO; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using iTextSharp.text.pdf; using System.IO; namespace SimuladorPrestamos.Controllers { public class PrestamosController : Controller { SimulacionesDAO SimulacionDAO = new SimulacionesDAO(); ClientesDAO Clientes = new ClientesDAO(); // GET: Prestamos public ActionResult Simulaciones() { return View(SimulacionDAO.ListaSimulaciones().Tables[0]); } public ActionResult Editar() { return View(new SimulacionBO()); } public ActionResult ListaNombres() { return Json(Clientes.ListaNombreClientes(), JsonRequestBehavior.AllowGet); } public ActionResult Guardar(SimulacionBO Simulacion) { SimulacionDAO.Agregar(Simulacion); return RedirectToAction("Simulaciones"); } public ActionResult Archivo(int id) { SimulacionDAO.GenerarPDF(id, Server.MapPath("~/Reportes/Reporte" + id + ".pdf")); return File(Server.MapPath("~/Reportes/Reporte" + id + ".pdf"), "application/pdf", "Reporte"+id+".pdf"); } } }
using System; namespace AlienEngine.ASL { public abstract partial class ASLShader { /// <summary> /// ASL Shader attribute used to define size of arrays. /// </summary> [AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public sealed class ArraySizeAttribute : Attribute { public ArraySizeAttribute(int size) { } public ArraySizeAttribute(string size) { } } /// <summary> /// ASL Shader attribute used to define a method, a field or a structure as a buil-in GLSL element. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Struct, AllowMultiple = false)] internal sealed class BuiltInAttribute : Attribute { } /// <summary> /// ASL Shader attribute used to add comments in the compiled GLSL code. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] public sealed class CommentAttribute : Attribute { public CommentAttribute(string comment) { } } /// <summary> /// ASL Shader attribute used to enable debug capabilities when compiling the GLSL code. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class DebugAttribute : Attribute { public DebugAttribute(bool debug) { Debug = debug; } internal bool Debug { get; private set; } } /// <summary> /// ASL Shader attribute used to enable GLSL extensions. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class ExtensionAttribute : Attribute { internal string ExtensionName { get; private set; } public ExtensionAttribute(string extensionName) { ExtensionName = extensionName; } } /// <summary> /// ASL Shader attribute used to create a GLSL member with the "in" qualifier. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct, AllowMultiple = false)] public sealed class InAttribute : Attribute { } /// <summary> /// ASL Shader attribute used to create a GLSL interface block. /// </summary> [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] public sealed class InterfaceBlockAttribute : Attribute { public InterfaceBlockAttribute() { } public InterfaceBlockAttribute(string blockNamespace) { } } /// <summary> /// ASL Shader attribute used to create a GLSL member with the "out" qualifier. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct, AllowMultiple = false)] public sealed class OutAttribute : Attribute { } /// <summary> /// ASL Shader attribute used to create a GLSL member with the "uniform" qualifier. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct, AllowMultiple = false)] public sealed class UniformAttribute : Attribute { } /// <summary> /// ASL Shader attribute used to define the version of the compiled GLSL code. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class VersionAttribute : Attribute { private int _v = DefaultShaderVersion; public VersionAttribute(int version) { Version = version; } public int Version { get { return _v; } private set { _v = value; } } } /// <summary> /// ASL Shader attribute used to include parts of GLSL codes. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class IncludeAttribute : Attribute { internal string IncludeName { get; private set; } internal Type IncludeType { get; private set; } public IncludeAttribute(string includeName) { IncludeName = includeName; } public IncludeAttribute(Type includeType) { IncludeType = includeType; } } } }
using Braspag.Domain.Commands; using Braspag.Domain.DTO; using Braspag.Domain.Entities; using Braspag.Domain.Interfaces.Repository; using Braspag.Domain.Interfaces.Services; using Braspag.Domain.Interfaces.UnityOfWork; using Braspag.Domain.Service; namespace Braspag.Service { public class UsuarioAppSevice : AppService, IUsuarioServices { private readonly IUsuarioRepository iosuarioRepository; public UsuarioAppSevice( IUnitiOfWork unitOfWork, IUsuarioRepository iosuarioRepository) : base(unitOfWork) { this.iosuarioRepository = iosuarioRepository; } public Usuario Autenticacao(string login, string senha) { var dto = new UsuarioDto() { login = login, senha = senha }; dto.ValidaUsuario(); return iosuarioRepository.Autenticacao(dto); } } }
using System; using System.Collections.Generic; using RTMPStreaming; using UnityEngine; using UnityEngine.UI; using YourBitcoinController; using YourBitcoinManager; using YourCommonTools; using YourEthereumController; using YourEthereumManager; using YourNetworkingTools; namespace YourRemoteAssistance { /****************************************** * * ScreenAssistanceView * * Main screen to manage the multiple clients connected * * @author Esteban Gallardo */ public class ScreenAssistanceView : ScreenBaseView, IBasicView { public const string SCREEN_NAME = "SCREEN_ASSISTANCE"; // ---------------------------------------------- // EVENTS // ---------------------------------------------- public const string EVENT_MAINMENU_PHONE_NUMBER = "EVENT_MAINMENU_PHONE_NUMBER"; public const string EVENT_MAINMENU_PUBLIC_BITCOIN_ADDRESS = "EVENT_MAINMENU_PUBLIC_BITCOIN_ADDRESS"; public const string EVENT_MAINMENU_IS_MANAGER = "EVENT_MAINMENU_IS_MANAGER"; public const string EVENT_MAINMENU_CHECK_VALID_ORIGIN = "EVENT_MAINMENU_CHECK_VALID_ORIGIN"; public const string EVENT_MAINMENU_CHECK_AGAIN = "EVENT_MAINMENU_CHECK_AGAIN"; public const string EVENT_MAINMENU_REQUEST_PHONE_NUMBERS = "EVENT_MAINMENU_REQUEST_PHONE_NUMBERS"; public const string SUBEVENT_ACTION_CALL_PHONE_NUMBER = "SUBEVENT_ACTION_CALL_PHONE_NUMBER"; // ---------------------------------------------- // PUBLIC MEMBERS // ---------------------------------------------- public GameObject ClientItemPrefab; // ---------------------------------------------- // PRIVATE MEMBERS // ---------------------------------------------- private GameObject m_root; private Transform m_container; private Button m_clearLog; private Button m_payBitcoin; // CLIENTS private GameObject m_gridClients; private Scrollbar m_scrollbarClients; private ScrollRect m_scrollViewClients; private List<GameObject> m_clients = new List<GameObject>(); // ACTIONS private Dropdown m_colorsNetwork; private string m_colorSelected; private ItemClientView m_playerSelected; // STREAMING WINDOW private RawImage m_streamingWindow; private Vector3 m_initialPosition; #if ENABLE_STREAMING private UniversalMediaPlayer m_ump; #endif // CAMERA private GameObject m_cameraLocal; // CUSTOMER MEMBES private bool m_isCustomer = false; private List<string> m_messagesOnScreen = new List<string>(); private float m_timeOutToClean = 0; private NetworkVector3 m_forwardCamera; private bool m_rotatedTo90 = false; private float m_timeToUpdateForward = 0; private enum RotationAxes { None = 0, MouseXAndY = 1, MouseX = 2, MouseY = 3, Controller = 4 } private RotationAxes m_axes = RotationAxes.MouseXAndY; private float m_sensitivityX = 7F; private float m_sensitivityY = 7F; private float m_minimumY = -60F; private float m_maximumY = 60F; private float m_rotationY = 0F; private string m_publicKeyAddressProvider; private string m_publicKeyAddressCustomer; // ------------------------------------------- /* * Constructor */ public override void Initialize(params object[] _list) { m_isCustomer = (bool)_list[0]; m_cameraLocal = GameObject.FindGameObjectWithTag("MainCamera").gameObject; #if UNITY_EDITOR || UNITY_STANDALONE_WIN m_cameraLocal.GetComponent<Camera>().transform.forward = Vector3.right; #endif m_root = this.gameObject; m_container = m_root.transform.Find("Content"); Utilities.ApplyMaterialOnObjects(m_container.gameObject, ScreenNetworkingController.Instance.MaterialDrawOnTop); m_root.GetComponent<Canvas>().worldCamera = m_cameraLocal.GetComponent<Camera>(); // LIST OF PLAYERS m_gridClients = m_container.Find("CanvasClients/ScrollViewClients/Grid").gameObject; m_scrollViewClients = m_container.Find("CanvasClients/ScrollViewClients").gameObject.GetComponent<ScrollRect>(); m_scrollbarClients = m_container.Find("CanvasClients/ScrollbarVerticalClients").gameObject.GetComponent<Scrollbar>(); // LIST OF ACTIONS m_colorsNetwork = m_container.Find("CanvasColors/DropdownColors").GetComponent<Dropdown>(); m_colorsNetwork.onValueChanged.AddListener(OnActionSelectedChanged); m_colorsNetwork.options = new List<Dropdown.OptionData>(); m_colorsNetwork.options.Add(new Dropdown.OptionData(DrawingLinesController.COLOR_WHITE)); m_colorsNetwork.options.Add(new Dropdown.OptionData(DrawingLinesController.COLOR_BLACK)); m_colorsNetwork.options.Add(new Dropdown.OptionData(DrawingLinesController.COLOR_RED)); m_colorsNetwork.options.Add(new Dropdown.OptionData(DrawingLinesController.COLOR_BLUE)); m_colorsNetwork.options.Add(new Dropdown.OptionData(DrawingLinesController.COLOR_GREEN)); m_colorsNetwork.itemText.text = DrawingLinesController.COLOR_RED; m_colorSelected = DrawingLinesController.COLOR_RED; DrawingLinesController.Instance.ColorSelected = m_colorSelected; m_colorsNetwork.value = -1; m_colorsNetwork.value = 0; // LOG if (m_container.Find("ClearColors") != null) { m_clearLog = m_container.Find("ClearColors").GetComponent<Button>(); m_clearLog.gameObject.GetComponent<Button>().onClick.AddListener(ClearColors); } // LOG if (m_container.Find("PayBlockchain") != null) { m_payBitcoin = m_container.Find("PayBlockchain").GetComponent<Button>(); m_container.Find("PayBlockchain/IconBitcoin").gameObject.SetActive(false); m_container.Find("PayBlockchain/IconEthereum").gameObject.SetActive(false); m_payBitcoin.gameObject.GetComponent<Button>().onClick.AddListener(PayBitcoin); #if !ENABLE_BITCOIN && !ENABLE_ETHEREUM m_payBitcoin.gameObject.SetActive(false); #elif ENABLE_BITCOIN m_container.Find("PayBlockchain/IconBitcoin").gameObject.SetActive(true); #elif ENABLE_ETHEREUM m_container.Find("PayBlockchain/IconEthereum").gameObject.SetActive(true); #endif } // GET STREAMING PANEL m_streamingWindow = m_root.transform.Find("StreamingWindow").GetComponent<RawImage>(); m_initialPosition = Utilities.Clone(m_streamingWindow.gameObject.transform.position); m_streamingWindow.color = new Color(1, 1, 1, 0); NetworkEventController.Instance.NetworkEvent += new NetworkEventHandler(OnNetworkEvent); UIEventController.Instance.UIEvent += new UIEventHandler(OnUIEvent); #if ENABLE_BITCOIN BitcoinEventController.Instance.BitcoinEvent += new BitcoinEventHandler(OnBitcoinEvent); #elif ENABLE_ETHEREUM EthereumEventController.Instance.EthereumEvent += new EthereumEventHandler(OnEthereumEvent); #endif if (m_isCustomer) { m_container.Find("CanvasClients").gameObject.SetActive(false); #if UNITY_EDITOR // m_container.gameObject.SetActive(false); #endif } else { UIEventController.Instance.DelayUIEvent(UIEventController.EVENT_SCREENMAINCOMMANDCENTER_REQUEST_LIST_USERS, 1); } UIEventController.Instance.DispatchUIEvent(UIEventController.EVENT_SCREENMAINCOMMANDCENTER_ACTIVATION_VISUAL_INTERFACE); } // ------------------------------------------- /* * Destroy */ public override bool Destroy() { if (base.Destroy()) return true; if (m_isCustomer) { RTMPController.Instance.StopStream(); } NetworkEventController.Instance.NetworkEvent -= OnNetworkEvent; UIEventController.Instance.UIEvent -= OnUIEvent; #if ENABLE_BITCOIN BitcoinEventController.Instance.BitcoinEvent -= OnBitcoinEvent; #elif ENABLE_ETHEREUM EthereumEventController.Instance.EthereumEvent -= OnEthereumEvent; #endif DisposeClientsList(true); GameObject.Destroy(this.gameObject); return false; } // ------------------------------------------- /* * Clear the current list of clients */ private void DisposeClientsList(bool _destroy) { if (m_clients == null) return; for (int i = 0; i < m_clients.Count; i++) { if (m_clients[i] != null) { if (m_clients[i].GetComponent<ItemClientView>() != null) { if (_destroy) { m_clients[i].GetComponent<ItemClientView>().Destroy(); } else { m_clients[i].GetComponent<ItemClientView>().ReleaseMemory(); } } GameObject.Destroy(m_clients[i]); } } m_clients.Clear(); } // ------------------------------------------- /* * Check if the connection id is in the list of displayed clients */ private bool CheckDisplayedClientsID(int _connectionID) { for (int i = 0; i < m_clients.Count; i++) { if (m_clients[i] != null) { if (m_clients[i].GetComponent<ItemClientView>().ConnectionData.Id == _connectionID) { return true; } } } return false; } // ------------------------------------------- /* * We create all the visual instances of the items */ private void FillClientList(List<PlayerConnectionData> _listClients) { for (int i = 0; i < _listClients.Count; i++) { PlayerConnectionData client = _listClients[i]; if (client != null) { if (!CheckDisplayedClientsID(client.Id)) { GameObject instance = Utilities.AddChild(m_gridClients.transform, ClientItemPrefab); Utilities.ApplyMaterialOnObjects(instance, ScreenNetworkingController.Instance.MaterialDrawOnTop); instance.GetComponent<ItemClientView>().Initialize(m_gridClients, _listClients[i].Reference, _listClients[i]); m_clients.Add(instance); } } } } // ------------------------------------------- /* * CancelPressed */ private void CancelPressed() { Destroy(); } // ------------------------------------------- /* * OnActionSelectedChanged */ private void OnActionSelectedChanged(int _index) { m_colorSelected = m_colorsNetwork.options[_index].text; DrawingLinesController.Instance.ColorSelected = m_colorSelected; DrawingLinesController.Instance.IsPressed = false; } // ------------------------------------------- /* * Clear all the network objects drawn by the administrator */ private void ClearColors() { DrawingLinesController.Instance.DestroyMyLines(YourNetworkTools.Instance.GetUniversalNetworkID()); } // ------------------------------------------- /* * Opens the payment screen with bitcoin */ private void PayBitcoin() { #if ENABLE_BITCOIN if (m_isCustomer) { ScreenBitcoinController.Instance.InitializeBitcoin(ScreenBitcoinSendView.SCREEN_NAME, m_publicKeyAddressProvider); } else { ScreenBitcoinController.Instance.InitializeBitcoin(ScreenBitcoinSendView.SCREEN_NAME, m_publicKeyAddressCustomer); } #elif ENABLE_ETHEREUM if (m_isCustomer) { ScreenEthereumController.Instance.InitializeEthereum(ScreenEthereumSendView.SCREEN_NAME, m_publicKeyAddressProvider); } else { ScreenEthereumController.Instance.InitializeEthereum(ScreenEthereumSendView.SCREEN_NAME, m_publicKeyAddressCustomer); } #endif } // ------------------------------------------- /* * CheckForwardVectorRemote */ private void CheckForwardVectorRemote() { for (int i = 0; i < m_clients.Count; i++) { if (m_clients[i] != null) { ItemClientView itemClientView = m_clients[i].GetComponent<ItemClientView>(); if (itemClientView != null) { if (itemClientView.Forward == null) { for (int j = 0; j < NetworkVariablesController.Instance.NetworkVariables.Count; j++) { INetworkVariable variable = NetworkVariablesController.Instance.NetworkVariables[j]; if (itemClientView.ConnectionData.Id == variable.Owner) { if (variable is NetworkVector3) { itemClientView.Forward = (NetworkVector3)variable; NetworkEventController.Instance.DelayNetworkEvent(EVENT_MAINMENU_REQUEST_PHONE_NUMBERS, 0.2f); } } } } } } } } // ------------------------------------------- /* * We will apply the movement to the camera */ private void PlayUMP(string _phoneNumber) { #if ENABLE_STREAMING if (m_ump == null) { m_ump = GameObject.FindObjectOfType<UniversalMediaPlayer>(); m_ump.RenderingObjects = new GameObject[1]; } else { if (m_ump.IsPlaying) { m_ump.Stop(); } } if (m_ump != null) { m_ump.RenderingObjects[0] = m_streamingWindow.gameObject; m_ump.Path = GameConfiguration.URL_RTMP_SERVER_ASSISTANCE + _phoneNumber; m_ump.Prepare(); m_ump.AddPreparedEvent(OnPreparedVideo); } #endif } // ------------------------------------------- /* * The video is prepared and ready to play */ private void OnPreparedVideo(Texture2D _event) { #if ENABLE_STREAMING m_streamingWindow.color = new Color(1, 1, 1, 1); m_ump.Play(); #endif } // ------------------------------------------- /* * We will apply the movement to the camera */ private void MoveCameraWithMouse() { if (Input.GetKey(KeyCode.LeftShift)) { m_axes = RotationAxes.None; if ((Input.GetAxis("Mouse X") != 0) || (Input.GetAxis("Mouse Y") != 0)) { m_axes = RotationAxes.MouseXAndY; } // USE MOUSE TO ROTATE VIEW if ((m_axes != RotationAxes.Controller) && (m_axes != RotationAxes.None)) { if (m_axes == RotationAxes.MouseXAndY) { float rotationX = m_cameraLocal.transform.localEulerAngles.y + Input.GetAxis("Mouse X") * m_sensitivityX; m_rotationY += Input.GetAxis("Mouse Y") * m_sensitivityY; m_rotationY = Mathf.Clamp(m_rotationY, m_minimumY, m_maximumY); m_cameraLocal.transform.localEulerAngles = new Vector3(-m_rotationY, rotationX, 0); } else if (m_axes == RotationAxes.MouseX) { m_cameraLocal.transform.Rotate(0, Input.GetAxis("Mouse X") * m_sensitivityX, 0); } else { m_rotationY += Input.GetAxis("Mouse Y") * m_sensitivityY; m_rotationY = Mathf.Clamp(m_rotationY, m_minimumY, m_maximumY); m_cameraLocal.transform.localEulerAngles = new Vector3(-m_rotationY, transform.localEulerAngles.y, 0); } } } } // ------------------------------------------- /* * We rotate with the gyroscope */ private void GyroModifyCamera() { // Rotate the parent object by 90 degrees around the x axis if (!m_rotatedTo90) { m_rotatedTo90 = true; Input.gyro.enabled = true; m_cameraLocal.transform.parent.transform.Rotate(Vector3.right, 90); } // Invert the z and w of the gyro attitude Quaternion rotFix = new Quaternion(Input.gyro.attitude.x, Input.gyro.attitude.y, -Input.gyro.attitude.z, -Input.gyro.attitude.w); // Now set the local rotation of the child camera object m_cameraLocal.transform.localRotation = rotFix; } // ------------------------------------------- /* * We will update the forward camera vector */ private void UpdateForwardVector() { if ((YourNetworkTools.Instance.GetUniversalNetworkID() != -1) && (m_cameraLocal != null)) { if (m_forwardCamera == null) { m_forwardCamera = new NetworkVector3(); m_forwardCamera.InitRemote(YourNetworkTools.Instance.GetUniversalNetworkID(), "Vector" + YourNetworkTools.Instance.GetUniversalNetworkID(), m_cameraLocal.GetComponent<Camera>().transform.forward); DrawingLinesController.Instance.ForwardPlayer = m_forwardCamera; } else { m_timeToUpdateForward += Time.deltaTime; if (m_timeToUpdateForward > 0.3f) { m_timeToUpdateForward = 0; m_forwardCamera.SetValue(m_cameraLocal.GetComponent<Camera>().transform.forward); } } } } // ------------------------------------------- /* * OnNetworkEvent */ private void OnNetworkEvent(string _nameEvent, bool _isLocalEvent, int _networkOriginID, int _networkTargetID, params object[] _list) { if (_nameEvent == EVENT_MAINMENU_PHONE_NUMBER) { if (!m_isCustomer) { int universalID = int.Parse((string)_list[0]); string phoneNumber = (string)_list[1]; for (int i = 0; i < m_clients.Count; i++) { if (m_clients[i].GetComponent<ItemClientView>().ConnectionData.Id == universalID) { m_clients[i].GetComponent<ItemClientView>().PhoneNumber = phoneNumber; m_clients[i].SetActive(true); } } } else { PlayUMP(GameConfiguration.LoadPhoneNumber()); } } if (_nameEvent == EVENT_MAINMENU_PUBLIC_BITCOIN_ADDRESS) { int universalID = int.Parse((string)_list[0]); if (YourNetworkTools.Instance.GetUniversalNetworkID() != universalID) { if (!m_isCustomer) { string publicBlockchainAddress = (string)_list[1]; for (int i = 0; i < m_clients.Count; i++) { if (m_clients[i].GetComponent<ItemClientView>().ConnectionData.Id == universalID) { m_clients[i].GetComponent<ItemClientView>().PublicBlockchainAddress = publicBlockchainAddress; } } } else { m_publicKeyAddressProvider = (string)_list[1]; } } } if (_nameEvent == NetworkEventController.EVENT_PLAYERCONNECTIONDATA_USER_DISCONNECTED) { #if (!UNITY_WSA && !UNITY_EDITOR) || UNITY_EDITOR if (m_playerSelected != null) { if (m_playerSelected.ConnectionData.Id == (int)_list[0]) { Debug.Log("DISCONNECTED PLAYER, STOP STREAMING"); } } #endif } if (_nameEvent == BitCoinController.EVENT_BITCOINCONTROLLER_TRANSACTION_COMPLETED) { string transactionID = (string)_list[0]; string publicKeyTarget = (string)_list[1]; decimal amountTransaction = decimal.Parse((string)_list[2]); float balanceInCurrency = (float)(amountTransaction * BitCoinController.Instance.GetCurrentExchange()); string amountInCurrency = balanceInCurrency + " " + BitCoinController.Instance.CurrentCurrency; if (BitCoinController.Instance.CurrentPublicKey == publicKeyTarget) { string description = LanguageController.Instance.GetText("screen.bitcoin.transaction.in.favor.received", amountInCurrency, transactionID); ScreenNetworkingController.Instance.CreateNewInformationScreen(ScreenInformationView.SCREEN_INFORMATION, UIScreenTypePreviousAction.KEEP_CURRENT_SCREEN, LanguageController.Instance.GetText("message.info"), description, null, ""); } } if (_nameEvent == EthereumController.EVENT_ETHEREUMCONTROLLER_TRANSACTION_COMPLETED) { string transactionID = (string)_list[0]; string publicKeyTarget = (string)_list[1]; decimal amountTransaction = decimal.Parse((string)_list[2]); float balanceInCurrency = (float)(amountTransaction * EthereumController.Instance.GetCurrentExchange()); string amountInCurrency = balanceInCurrency + " " + EthereumController.Instance.CurrentCurrency; if (EthereumController.Instance.CurrentPublicKey == publicKeyTarget) { string description = LanguageController.Instance.GetText("screen.bitcoin.transaction.in.favor.received", amountInCurrency, transactionID); ScreenNetworkingController.Instance.CreateNewInformationScreen(ScreenInformationView.SCREEN_INFORMATION, UIScreenTypePreviousAction.KEEP_CURRENT_SCREEN, LanguageController.Instance.GetText("message.info"), description, null, ""); } } } // ------------------------------------------- /* * OnUIEvent */ private void OnUIEvent(string _nameEvent, params object[] _list) { if (_nameEvent == EVENT_MAINMENU_CHECK_VALID_ORIGIN) { int xPos = (int)_list[0]; int yPos = (int)_list[1]; bool isValid = !m_container.GetComponent<RectTransform>().rect.Contains(new Vector2(xPos, yPos)); UIEventController.Instance.DispatchUIEvent(DrawingLinesController.EVENT_DRAWINGLINES_VALID_POINT, isValid); } if (m_isCustomer) return; if (_nameEvent == UIEventController.EVENT_SCREENMAINCOMMANDCENTER_LIST_USERS) { m_playerSelected = null; FillClientList((List<PlayerConnectionData>)_list[0]); } if (_nameEvent == UIEventController.EVENT_SCREENMAINCOMMANDCENTER_TEXTURE_REMOTE_STREAMING_DATA) { int idPlayer = (int)_list[0]; if (m_playerSelected.ConnectionData.Id == idPlayer) { int textWidth = (int)_list[1]; int textHeight = (int)_list[2]; byte[] textureData = (byte[])_list[3]; ImageUtils.LoadBytesImage(m_streamingWindow, textWidth, textHeight, textureData); } } if (_nameEvent == BaseItemView.EVENT_ITEM_SELECTED) { GameObject itemSelected = (GameObject)_list[0]; if (itemSelected == null) return; // CLIENTS if (itemSelected.GetComponent<IBasicItemView>().ContainerParent == m_gridClients) { if (itemSelected.GetComponent<ItemClientView>() != null) { bool selected = (bool)_list[1]; int indexClicked = -1; for (int i = 0; i < m_clients.Count; i++) { if (m_clients[i].gameObject == itemSelected) { indexClicked = i; } else { if (selected) { m_clients[i].GetComponent<BaseItemView>().Selected = false; } } } if (indexClicked != -1) { if (selected) { m_playerSelected = m_clients[indexClicked].GetComponent<ItemClientView>(); if (m_playerSelected.Forward != null) { DrawingLinesController.Instance.ForwardPlayer = m_playerSelected.Forward; PlayUMP(m_playerSelected.PhoneNumber); m_publicKeyAddressCustomer = m_playerSelected.PublicBlockchainAddress; ScreenNetworkingController.Instance.CreatePopUpScreenConfirmation(LanguageController.Instance.GetText("text.call.me"), LanguageController.Instance.GetText("text.do.you.want.to.call") + " " + m_playerSelected.PhoneNumber, SUBEVENT_ACTION_CALL_PHONE_NUMBER); } } else { m_playerSelected = null; #if ENABLE_STREAMING if (m_ump != null) m_ump.Stop(); #endif DrawingLinesController.Instance.ForwardPlayer = null; } } } } } if (_nameEvent == ScreenController.EVENT_CONFIRMATION_POPUP) { GameObject screen = (GameObject)_list[0]; bool accepted = (bool)_list[1]; string subnameEvent = (string)_list[2]; if (subnameEvent == SUBEVENT_ACTION_CALL_PHONE_NUMBER) { if (m_playerSelected != null) { if (accepted) { Application.OpenURL("tel://" + m_playerSelected.PhoneNumber); } } } } } // ------------------------------------------- /* * OnBitcoinEvent */ private void OnBitcoinEvent(string _nameEvent, object[] _list) { if (_nameEvent == BitCoinController.EVENT_BITCOINCONTROLLER_TRANSACTION_COMPLETED) { if ((bool)_list[0]) { string transactionID = (string)_list[1]; string publicKeyTarget = (string)_list[2]; string amountTransaction = (string)_list[3]; NetworkEventController.Instance.DispatchNetworkEvent(BitCoinController.EVENT_BITCOINCONTROLLER_TRANSACTION_COMPLETED, transactionID, publicKeyTarget, amountTransaction); } } } // ------------------------------------------- /* * OnEthereumEvent */ private void OnEthereumEvent(string _nameEvent, object[] _list) { if (_nameEvent == EthereumController.EVENT_ETHEREUMCONTROLLER_TRANSACTION_COMPLETED) { if ((bool)_list[0]) { string transactionID = (string)_list[1]; string publicKeyTarget = (string)_list[2]; string amountTransaction = (string)_list[3]; NetworkEventController.Instance.DispatchNetworkEvent(EthereumController.EVENT_ETHEREUMCONTROLLER_TRANSACTION_COMPLETED, transactionID, publicKeyTarget, amountTransaction); } } } // ------------------------------------------- /* * If it's the provider of services it updates the direction of the camera, * if it's the customer then allows to move the camera */ void Update() { if (!m_isCustomer) { if (DrawingLinesController.Instance.ForwardPlayer != null) { m_cameraLocal.transform.forward = (Vector3)DrawingLinesController.Instance.ForwardPlayer.GetValue(); } CheckForwardVectorRemote(); } else { if (m_timeOutToClean > 0) { m_timeOutToClean -= Time.deltaTime; if (m_timeOutToClean <= 0) { m_messagesOnScreen.Clear(); } } #if UNITY_EDITOR || UNITY_STANDALONE_WIN MoveCameraWithMouse(); #else GyroModifyCamera(); #endif UpdateForwardVector(); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Threading.Tasks; using System.Windows.Forms; using TutteeFrame2.Model; using TutteeFrame2.Controller; namespace TutteeFrame2.View { enum mouse { Ver, Hori, none } public partial class Schedule : UserControl { Graphics g; List<Session> t = new List<Session>(); List<Subject> subject = new List<Subject>(); List<Cs> cs = new List<Cs>(); public string scheduleID; Bitmap bitmap; Rim r = new Rim(); Point Lastmouse = new Point(0, 0); bool ismousedown = false; bool chosen = false; bool chosing = false; bool edge = false; mouse m = mouse.none; readonly ScheduleController scheduleController; public HomeView homeView; List<Class> classes = new List<Class>(); public Schedule() { InitializeComponent(); scheduleController = new ScheduleController(this); Create(); ReDraw(); pictureBox1.MouseMove += (s, e) => { if (!ismousedown) { for (int i = 1; i < 7; i++) { if (e.X == r.Ver[i]) { edge = true; return; } } for (int i = 1; i < 11; i++) { if (e.Y == r.Hori[i]) { edge = true; return; } } edge = false; } else { if (m == mouse.Ver) { int j = new int(); for (int i = 1; i < 7; i++) { if (r.Ver[i] == Lastmouse.X) { j = i; break; } } r.Ver[j] = e.X; Lastmouse = e.Location; UpdateIntersec(); ReDraw(); } if (m == mouse.Hori) { int j = new int(); for (int i = 1; i < 11; i++) { if (r.Hori[i] == Lastmouse.Y) { j = i; break; } } r.Hori[j] = e.Y; Lastmouse = e.Location; UpdateIntersec(); ReDraw(); } } }; pictureBox1.MouseDown += (s, e) => { if (!edge) { bool found1 = false; bool found2 = false; int a = new int(); int b = new int(); int c = new int(); int d = new int(); for (int i = 1; i < 8 && !found1; i++) { for (int j = i; j < 8; j++) { if (r.Ver[i] < e.X && r.Ver[j] > e.X && j - i == 1) { a = i; b = j; found1 = true; break; } } } for (int i = 1; i < 12 && !found2; i++) { for (int j = i; j < 12; j++) { if (r.Hori[i] < e.Y && r.Hori[j] > e.Y && j - i == 1) { c = i; d = j; found2 = true; break; } } } if (found1 && found2) { chosing = true; if (chosen == false) { DrawLine(a, b, c, d); getinfo(a, c); chosen = true; } else { if (materialComboBox4.Text == (a + 1).ToString() && materialComboBox5.Text == c.ToString()) { ReDraw(); materialComboBox4.SelectedIndex = -1; materialComboBox5.SelectedIndex = -1; materialComboBox6.SelectedIndex = -1; chosen = false; chosing = false; containedButton2.Enabled = false; } else { ReDraw(); DrawLine(a, b, c, d); getinfo(a, c); } } } } }; pictureBox1.MouseUp += (s, e) => { ismousedown = false; }; } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); if (g == null) return; Create(); ReDraw(); } private void VeBang() { g.Clear(Color.White); Font f = new Font("Arial", 12); Brush br = new SolidBrush(Color.Black); for (int i = 0; i < 8; i++) { g.DrawLine(new Pen(Color.Black, 1), r.Ver[i], 0, r.Ver[i], pictureBox1.Height); } for (int i = 0; i < 12; i++) { g.DrawLine(new Pen(Color.Black, 1), 0, r.Hori[i], pictureBox1.Width, r.Hori[i]); } for (int i = 1; i < 7; i++) { g.DrawString("Thứ " + (i + 1).ToString(), f, br, r.Intersec[0, i].X + pictureBox1.Width / 35, r.Intersec[0, i].Y + pictureBox1.Height / 55); } for (int i = 1; i < 11; i++) { g.DrawString(i.ToString(), f, br, r.Intersec[i, 0].X + pictureBox1.Width / 21, r.Intersec[i, 0].Y + pictureBox1.Height / 55); } update(); } private void button1_Click(object sender, EventArgs e) { Session tkb = new Session(); string day = materialComboBox4.SelectedItem.ToString(); tkb.thu = Int32.Parse(day); string session = materialComboBox5.SelectedItem.ToString(); tkb.tiet = Int32.Parse(session); tkb.mon = ConvertToID(materialComboBox6.SelectedItem.ToString()); materialComboBox4.SelectedIndex = -1; materialComboBox5.SelectedIndex = -1; materialComboBox6.SelectedIndex = -1; tkb.ID = scheduleID + (tkb.thu * 10 + tkb.tiet).ToString(); add(tkb); chosen = false; containedButton2.Enabled = false; ReDraw(); } private async void add(Session tkb) { homeView.SetLoad(true, "Đang thêm..."); foreach (Session s in t) { if (s.thu == tkb.thu && s.tiet == tkb.tiet) { homeView.SetLoad(true, "Đang sửa..."); s.mon = tkb.mon; await Task.Delay(600); await Task.Run(() => { scheduleController.Detele(tkb.ID); }); await Task.Delay(600); await Task.Run(() => { scheduleController.Add(tkb, scheduleID); }); ReDraw(); homeView.SetLoad(false); return; } } homeView.SetLoad(true, "Đang thêm..."); await Task.Delay(600); await Task.Run(() => { scheduleController.Add(tkb, scheduleID); }); t.Add(tkb); draw(tkb); homeView.SetLoad(false); } private void update() { pictureBox1.Image = bitmap; } private void draw(Session tkb) { Font f = this.Font; Brush br = new SolidBrush(Color.Black); g.DrawString(ConvertToName(tkb.mon), f, br, r.Intersec[tkb.tiet, tkb.thu - 1].X + pictureBox1.Width / 35, r.Intersec[tkb.tiet, tkb.thu - 1].Y + pictureBox1.Height / 55); update(); } public void ReDraw() { bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height); g = Graphics.FromImage(bitmap); VeBang(); foreach (Session tkb in t) { draw(tkb); } } private void Create() { for (int i = 0; i < 12; i++) { r.Hori[i] = i * pictureBox1.Height / 11; } r.Hori[11] = r.Hori[11] - 1; for (int i = 0; i < 8; i++) { r.Ver[i] = i * pictureBox1.Width / 7; } r.Ver[7] = r.Ver[7] - 1; UpdateIntersec(); } private void UpdateIntersec() { for (int i = 0; i < 12; i++) { for (int j = 0; j < 8; j++) { r.Intersec[i, j].X = r.Ver[j]; r.Intersec[i, j].Y = r.Hori[i]; } } } private void DrawLine(int a, int b, int c, int d) { g.DrawLine(new Pen(Color.Red), r.Ver[a] + 1, r.Hori[c] + 1, r.Ver[b] - 1, r.Hori[c] + 1); //trên g.DrawLine(new Pen(Color.Red), r.Ver[a] + 1, r.Hori[d] - 1, r.Ver[b] - 1, r.Hori[d] - 1); //dưới g.DrawLine(new Pen(Color.Red), r.Ver[a] + 1, r.Hori[c] + 1, r.Ver[a] + 1, r.Hori[d] - 1); //trái g.DrawLine(new Pen(Color.Red), r.Ver[b] - 1, r.Hori[c] + 1, r.Ver[b] - 1, r.Hori[d] - 1); //phải Brush br = new SolidBrush(Color.Black); Brush br1 = new SolidBrush(Color.FromArgb(60, 47, 144, 176)); Brush br2 = new SolidBrush(Color.FromArgb(127, 47, 144, 176)); g.FillRectangle(br1, r.Ver[a] + 1, 1, r.Ver[b] - r.Ver[a] - 1, pictureBox1.Height / 11 - 1); g.FillRectangle(br1, 1, r.Hori[c] + 1, pictureBox1.Width / 7 - 1, r.Hori[d] - r.Hori[c] - 1); g.FillRectangle(br2, r.Ver[a] + 1, r.Hori[c] + 1, r.Ver[b] - r.Ver[a] - 1, r.Hori[d] - r.Hori[c] - 1); Font f = new Font("Arial", 12); for (int i = 1; i < 7; i++) { g.DrawString("Thứ " + (i + 1).ToString(), f, br, r.Intersec[0, i].X + pictureBox1.Width / 35, r.Intersec[0, i].Y + pictureBox1.Height / 55); } for (int i = 1; i < 11; i++) { g.DrawString(i.ToString(), f, br, r.Intersec[i, 0].X + pictureBox1.Width / 21, r.Intersec[i, 0].Y + pictureBox1.Height / 55); } update(); } private void getinfo(int a, int b) { materialComboBox4.SelectedIndex = a - 1; materialComboBox5.SelectedIndex = b - 1; materialComboBox6.SelectedIndex = -1; foreach (Session tkb in t) { if (tkb.thu == a + 1 && tkb.tiet == b) { foreach (Cs c in cs) { if (c.name == ConvertToName(tkb.mon)) { materialComboBox6.SelectedIndex = c.index; break; } } break; } } if (materialComboBox6.SelectedIndex != -1) containedButton2.Enabled = true; else containedButton2.Enabled = false; return; } private void PickSubject(int a, int b) { materialComboBox6.SelectedIndex = -1; foreach (Session tkb in t) { if (tkb.thu == a + 1 && tkb.tiet == b) { foreach (Cs c in cs) { if (c.name == ConvertToName(tkb.mon)) { materialComboBox6.SelectedIndex = c.index; break; } } break; } } if (materialComboBox6.SelectedIndex != -1) containedButton2.Enabled = true; else containedButton2.Enabled = false; return; } private void materialComboBox2_SelectedIndexChanged(object sender, EventArgs e) { materialComboBox3.Items.Clear(); switch (materialComboBox2.SelectedItem) { case "10": { scheduleController.GetClass("10"); break; } case "11": { scheduleController.GetClass("11"); break; } case "12": { scheduleController.GetClass("12"); break; } default: break; } } public void AddClasses() { classes = scheduleController.classes; AddItems(); } private delegate void dlgAddItem(); private void AddItems() { foreach (Class @class in classes) { materialComboBox3.Items.Add(@class.ClassID); } materialComboBox3.SelectedIndex = -1; } private async void button3_Click(object sender, EventArgs e) { homeView.SetLoad(true, "Đang tải thời khóa biểu"); string lop = materialComboBox3.Text; int hk = Int32.Parse(materialComboBox1.Text); int nam = 2020; await Task.Delay(300); await Task.Run(() => { scheduleController.GetSchedule(lop, hk, nam); }); homeView.SetLoad(false); } private async void AutoViewSchedule() { homeView.SetLoad(true, "Đang tải thời khóa biểu"); string lop = materialComboBox3.Text; int hk = Int32.Parse(materialComboBox1.Text); int nam = 2020; await Task.Delay(300); await Task.Run(() => { scheduleController.GetSchedule(lop, hk, nam); }); homeView.SetLoad(false); } public async void GetSchedule() { await Task.Run(() => { scheduleID = scheduleController.scheduleID; scheduleController.FetchSchedule(scheduleID); }); } private string ConvertToID(string sub) { string id = new string(new char[] { }); foreach (Subject s in subject) { if (s.Name == sub) { id = s.ID; return id; } } return null; } private string ConvertToName(string id) { string sub = new string(new char[] { }); foreach (Subject s in subject) { if (s.ID == id) { sub = s.Name; return sub; } } return null; } public void FetchData() { ReDraw(); scheduleController.FetchData(); } public void GetSubject() { //materialComboBox6.Items.Clear(); subject = scheduleController.subject; foreach (Subject s in scheduleController.subject) { materialComboBox6.Items.Add(s.Name); Cs c = new Cs(); c.name = s.Name; c.index = cs.Count; cs.Add(c); } } public void FetchSchedule() { t = scheduleController.sessions; ReDraw(); } private async void containedButton2_Click(object sender, EventArgs e) { homeView.SetLoad(true, "Đang xóa..."); int thu = Int32.Parse(materialComboBox4.Text); int tiet = Int32.Parse(materialComboBox5.Text); string id = scheduleID + (thu * 10 + tiet).ToString(); await Task.Delay(600); await Task.Run(() => { scheduleController.Detele(id); }); materialComboBox4.SelectedIndex = -1; materialComboBox5.SelectedIndex = -1; materialComboBox6.SelectedIndex = -1; foreach (Session s in t) { if (s.thu == thu && s.tiet == tiet) { t.Remove(s); ReDraw(); containedButton2.Enabled = false; homeView.SetLoad(false); return; } } } private void materialComboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (materialComboBox1.SelectedIndex != -1 && materialComboBox3.SelectedIndex != -1) { AutoViewSchedule(); materialComboBox4.SelectedIndex = materialComboBox5.SelectedIndex = materialComboBox6.SelectedIndex = -1; chosen = false; } } private void materialComboBox4_SelectedIndexChanged(object sender, EventArgs e) { int a = materialComboBox4.SelectedIndex; if (materialComboBox4.SelectedIndex != -1 && materialComboBox5.SelectedIndex != -1) { if (materialComboBox6.SelectedIndex != -1 && scheduleID != null) containedButton1.Enabled = true; else containedButton1.Enabled = false; } else { containedButton1.Enabled = false; return; } if (chosing) { if (sender == materialComboBox5) { chosing = false; } return; } chosen = true; if (materialComboBox4.SelectedIndex != -1 && materialComboBox5.SelectedIndex != -1) { ReDraw(); PickSubject(materialComboBox4.SelectedIndex + 1, materialComboBox5.SelectedIndex + 1); DrawLine(materialComboBox4.SelectedIndex + 1, materialComboBox4.SelectedIndex + 2, materialComboBox5.SelectedIndex + 1, materialComboBox5.SelectedIndex + 2); } } public void SetHome(HomeView homeView) { this.homeView = homeView; } private void containedButton3_Click(object sender, EventArgs e) { ReDraw(); SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "Jpg files (*.jpg)|*.jpg|Png files (*.png)|*.png"; dialog.FilterIndex = 2; dialog.FileName = "Thời khóa biểu lớp " + materialComboBox3.Text; if (dialog.ShowDialog() == DialogResult.OK) { bitmap.Save(dialog.FileName); dialog.FileName = ""; } } private void materialComboBox6_SelectedIndexChanged(object sender, EventArgs e) { if (materialComboBox4.SelectedIndex != -1 && materialComboBox5.SelectedIndex != -1) { if (materialComboBox6.SelectedIndex != -1 && scheduleID != null) containedButton1.Enabled = true; else containedButton1.Enabled = false; } else { containedButton1.Enabled = false; return; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataGenerator.GenerateHelper; namespace DataGenerator { public static class Generator { public static List<string> Generate() { return new BatchGenerator().Start(); } } }
namespace ConrollerLicença { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Cliente")] public partial class Cliente { public int ID { get; set; } [StringLength(450)] public string Nome { get; set; } [StringLength(450)] public string Documento { get; set; } [StringLength(450)] public string Observação { get; set; } public DateTime? DataVencimento { get; set; } public DateTime? DataAplicação { get; set; } public string Chave { get; set; } public bool Ativo { get; set; } } }
using Selenite.Models; namespace Selenite.Client.ViewModels.WebAutomation { public class TestCollectionViewModel : TreeViewModelBase<TestViewModel> { public string Name { get { return Get(() => Name); } set { Set(value, () => Name); } } public string Domain { get { return Get(() => Domain); } set { Set(value, () => Domain); } } public bool IsEnabled { get { return Get(() => IsEnabled); } set { Set(value, () => IsEnabled); } } public TestCollection ToModel() { return new TestCollection(); } } }
using BPiaoBao.SystemSetting.Domain.Models.SMS; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; namespace BPiaoBao.SystemSetting.EFRepository.BusinessmenMap { public class SMSMap:EntityTypeConfiguration<SMS> { public SMSMap() { this.HasKey(t => t.BusinessmanCode); this.HasRequired(t => t.Businessman).WithRequiredDependent(t=>t.SMS); } } }
using CSharpUtils.StatusLoggerServiceReference; namespace CSharpUtils.Utils.StatusLogger { public class RemoteStatusLogger : BaseStatusLogger, IStatusLoggerServiceCallback { public void OnChanged(StatusLoggerServiceReference.StatusChangeEventArgs e) { Changed(this, StatusChangeEventArgs.FromService(e)); } } }
using System; using System.Collections.Generic; using productsapi.Models; using System.Linq; using System.Threading.Tasks; namespace productsapi.Repositories { public interface ICategory : IDefaultRepo<Category> { //IEnumerable<Category> getAll(); //Category getOneById(int id); //void add(Category category); //void edit(Category category); //void delete(int id); Category getParent(Guid id); IEnumerable<Category> getChilds(Guid id); IEnumerable<Product> getProducts(Guid id); //void SaveChanges(); } }
using System; using System.Linq; namespace Solution1 { class Program { static void Main(string[] args) { int[] arr1 = { 11, 23, 83, 41, 95, 36, 77, 81, 90 }; int[] arr2 = { 11, 33, 88, 41, 77, 8, 4, 10 }; Console.WriteLine(String.Join(", ", ArrayDiff(arr1, arr2))); } static T[] ArrayDiff<T>(T[] arr1, T[] arr2) { var res = arr1.ToList(); foreach (var item in arr1) { if(arr2.Contains(item)) { res.Remove(item); } } return res.ToArray(); } } }
using UnityEngine; using System.Collections; public class GeneralButton : ftlManager { public string hotKey; public Rect GuiRect = new Rect (0,0,10,10); private Color tb; CheckButtons cb = new CheckButtons(); void Awake() { var tmpCol = Color.black; tmpCol.a = GetComponent<SpriteRenderer>().color.a; } void OnMouseDown() { if (GetComponent<SpriteRenderer> ().color == ButtonGrey || GetComponent<SpriteRenderer> ().color == Invisible) return; foreach (var touch in Input.touches) { if (touch.phase == TouchPhase.Began && tag != "FolderButton") return; } cb.PressButton (gameObject); } void OnMouseUp() { if (GetComponent<SpriteRenderer> ().color == ButtonGrey || GetComponent<SpriteRenderer> ().color == Invisible) return; foreach (var touch in Input.touches) { if (touch.phase == TouchPhase.Ended && tag != "FolderButton") return; } cb.ReleaseButton (gameObject); } private void OnGUI() { var tmpCol = Color.black; tmpCol.a = GetComponent<SpriteRenderer>().color.a; var style = buttonText; style.normal.textColor = tmpCol; if (GetComponent<SpriteRenderer> ().color == Invisible) { GetComponent<Collider>().enabled = false; } else { if (GetComponent<SpriteRenderer> ().color == ButtonGrey) GetComponent<Collider>().enabled = false; else GetComponent<Collider>().enabled = true; if (tag == "FolderButton") { style.normal.textColor = new Color ( 0.35f, 0.239f, 0.024f, 1f); style.font = GameFont; var centroid = transformToObject( new Vector3( Screen.width/2 , Screen.height/2 , 0) , gameObject); GuiRect = new Rect (centroid.x - 100, centroid.y - 50, 200 , 100); var thisName = name.Split ('\\'); var shortName = thisName[thisName.Length - 1]; GUI.Label (GuiRect, shortName, style); } } } public void press () { if (!Camera.main.GetComponent<AudioSource> ().isPlaying) Camera.main.GetComponent<AudioSource> ().PlayOneShot (Camera.main.GetComponent<AudioSource> ().clip); GetComponent<SpriteRenderer> ().color = ButtonPressed; } public void release () { GetComponent<SpriteRenderer> ().color = ButtonNormal; } }
using UnityEngine; namespace HoloToolkitExtensions.Utilities { public class MeshBuilder : MonoBehaviour { void Start() { var meshFilters = GetComponentsInChildren<MeshFilter>(); foreach (var meshFilter in meshFilters) { meshFilter.transform.gameObject.AddComponent(typeof(MeshCollider)); } } } }
using DiscordBotTest.Models; using HtmlAgilityPack; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DiscordBotTest.Helpers { public class SkinInfoGetter { public async Task<string> GetAsync() { var mainUrl = "https://csgostash.com/containers/skin-cases"; var web = new HtmlWeb(); var doc = await web.LoadFromWebAsync(mainUrl); var xpathCases = "//*[@class='col-lg-4 col-md-6 col-widen text-center']"; var valueNodeCases = doc.DocumentNode.SelectNodes(xpathCases).ToList(); var skinInfoList = new List<SkinInfo>(); foreach (var caseNode in valueNodeCases) { var caseUrl = caseNode.SelectSingleNode($"{caseNode.XPath}/div/a")?.GetAttributeValue("href", string.Empty) ?? string.Empty; var caseDoc = await web.LoadFromWebAsync(caseUrl); var xpathSkins = "//*[@class='col-lg-4 col-md-6 col-widen text-center']"; var valueNodes = caseDoc.DocumentNode.SelectNodes(xpathSkins).ToList(); var xpathCaseName = "/html/body/div[2]/div[3]/div/div[2]/h1"; var caseName = caseDoc.DocumentNode.SelectNodes(xpathCaseName).SingleOrDefault()?.InnerText ?? string.Empty; foreach (var node in valueNodes) { var name = node.SelectSingleNode($"{node.XPath}/div/h3")?.InnerText ?? string.Empty; var rarityText = node.SelectSingleNode($"{node.XPath}/div/a[1]/div/p")?.InnerText?.Replace("-", "") ?? string.Empty; var rarity = GetRarity(rarityText); var imageUrl = node.SelectSingleNode($"{node.XPath}/div/a[2]/img")?.GetAttributeValue("src", string.Empty) ?? string.Empty; var skinInfo = new SkinInfo(name, rarity, imageUrl, caseName); skinInfoList.Add(skinInfo); } } return JsonConvert.SerializeObject(skinInfoList); } private Rarity GetRarity(string rarityText) { if (rarityText.Contains(RarityName.MilSpec.ToString())) { return Rarity.Blue; } else if (rarityText.Contains(RarityName.Restricted.ToString())) { return Rarity.Purple; } else if (rarityText.Contains(RarityName.Classified.ToString())) { return Rarity.Pink; } else if (rarityText.Contains(RarityName.Covert.ToString())) { return Rarity.Red; } else if (rarityText.Contains(RarityName.Knifes.ToString())) { return Rarity.Knife; } else { throw new Exception("Invaid rarity for rarity name."); } } } }
using System; using System.Collections.Generic; using UnityEngine; [Serializable] public class ReportList { public List<Report> reports = new List<Report>(); } [Serializable] public class Report { [SerializeField] string conditionVariable = ""; [SerializeField] string cityName = ""; [SerializeField] string reportName = ""; [SerializeField] string reportText = ""; [SerializeField] int turnNo = 1; [SerializeField] bool isEnabled = false; [SerializeField] bool isUserNotified = false; [SerializeField] bool isReportDone = false; public Report(string conditionVariable, string cityName, string reportName, string reportText, int turnNo = 0, bool isEnabled = false, bool isUserNotified = false, bool isReportDone = false) { this.conditionVariable = conditionVariable; this.cityName = cityName; this.reportName = reportName; this.reportText = reportText; this.turnNo = turnNo; this.isEnabled = isEnabled; this.isUserNotified = isUserNotified; this.isReportDone = isReportDone; } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; using FirebirdDataModel; namespace ExpManagerToOwnMoney.Helpers { public static class DBConformity { /// <summary> /// Соответсвие счетов. 1 - ExpManager, 2 - OwnMoney /// </summary> public static Dictionary<int, int> AccountConformityEMtoOM { get { var result = new Dictionary<int, int>(); if (MemoryCache.Default["AccountConformityEMtoOM"] == null) { using (var db = new BudgetDB()) { var dbAccounts = db.MONEY_ACCOUNT.ToList(); foreach (var account in ExpManagerWorker.ExpManagerXmlModel.Dictionaries.Accounts) { try { // Сопоставление по названию var item = dbAccounts.FirstOrDefault(c => c.NAME == account.Name); if(item != null) result.Add(account.Id, item.ID); } catch (Exception) { // Ненайденные пропускаем } } } MemoryCache.Default["AccountConformityEMtoOM"] = result; } else { result = MemoryCache.Default["AccountConformityEMtoOM"] as Dictionary<int, int>; } return result; } } /// <summary> /// Соответсвие категорий. 1 - ExpManager, 2 - OwnMoney /// </summary> public static Dictionary<int, int> CategoryConformityEMtoOM { get { var result = new Dictionary<int, int>(); if (MemoryCache.Default["CategoryConformityEMtoOM"] == null) { using (var db = new BudgetDB()) { var dbCategories = db.EXPENCE_ITEM.ToList(); foreach (var category in ExpManagerWorker.ExpManagerXmlModel.Dictionaries.Categories) { try { // Сопоставление по названию var item = dbCategories.FirstOrDefault(c => c.NAME == category.Name); if (item != null) result.Add(category.Id, item.ID); } catch (Exception) { // Ненайденные пропускаем } } } MemoryCache.Default["CategoryConformityEMtoOM"] = result; } else { result = MemoryCache.Default["CategoryConformityEMtoOM"] as Dictionary<int, int>; } return result; } } /// <summary> /// Соответсвие типов операций. 1 - ExpManager, 2 - OwnMoney /// </summary> public static Dictionary<int, int> OperationTypeConformityEMtoOM = new Dictionary<int, int>() { { 0, 3 }, // Расход { 1, 2 }, // Доход }; /// <summary> /// Соответсвие валют операций. 1 - ExpManager, 2 - OwnMoney /// </summary> public static Dictionary<int, int> CurrencyConformityEMtoOM = new Dictionary<int, int>() { { 1, 1 }, // Доллар { 2, 2 }, // Евро { 8, 168 }, // Польский злотый { 62, 151 }, // Белорусский рубль { 0, 3 }, // Российский рубль }; } }
using System; using System.Windows.Forms; using System.Text; namespace QuanLyTiemGiatLa.Danhmuc { public partial class frmCTNhanVien : Form { public OnSaved onsaved; private TrangThai TrangThai; private string _passBefore; public frmCTNhanVien() { InitializeComponent(); this.LoadComboQuyen(); this.Load += new EventHandler(frmCTNhanVien_Load); } private void LoadComboQuyen() { cboQuyen.Items.Clear(); cboQuyen.Items.Insert(0, "Nhân viên"); cboQuyen.Items.Insert(1, "Kế toán"); cboQuyen.Items.Insert(2, "Admin"); cboQuyen.SelectedIndex = 0; } private void frmCTNhanVien_Load(object sender, EventArgs e) { try { TrangThai = this.NhanVien == null ? TrangThai.Them : TrangThai.Sua; if (TrangThai == TrangThai.Them) { } else { _passBefore = NhanVien.Password; txtRePass.Text = NhanVien.Password; cboQuyen.SelectedIndex = NhanVien.Quyen; txtUsername.Enabled = false; if (NhanVien.UserName == "admin") { cboQuyen.Enabled = false; for (int i = 0; i < this.groupBox2.Controls.Count; i++) { if (this.groupBox2.Controls[i] is CheckBox) { CheckBox chk = this.groupBox2.Controls[i] as CheckBox; if (chk != null) { chk.Checked = true; chk.Enabled = false; } } } } else { if (NhanVien.QuyenHan.Length == 17) { Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.BangChotKet], chkBangChotKet); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.BangGia], chkBangGia); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.CatDo], chkCatDo); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.CauHinh], chkCauHinh); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.DanhSachPhieu], chkDanhSachPhieu); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.DoiMatKhau], chkDoiMatKhau); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.DotGiamGia], chkDotGiamGia); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.GiaDeDo], chkGiaDeDo); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.KieuGiat], chkKieuGiat); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.KhachHang], chkKhachHang); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.LapPhieu], chkLapPhieu); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.LoaiHang], chkLoaiHang); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.LoaiKhachHang], chkLoaiKhachHang); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.MatHang], chkMatHang); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.NhanVien], chkNhanVien); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.NhungViecCanLam], chkNhungViecCanLam); Check1QuyenHan(NhanVien.QuyenHan[(Int32)ThuTuButton.ThongKeThuNhap], chkThongKeThuNhap); } } } } catch (System.Exception ex) { MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Check1QuyenHan(char c, CheckBox chk) { chk.Checked = c == '1'; } public Entity.UserEntity NhanVien { set { bndsrcNhanVien.DataSource = value; } get { return bndsrcNhanVien.DataSource as Entity.UserEntity; } } private Boolean CheckForm() { if (String.IsNullOrEmpty(txtUsername.Text)) { txtUsername.Focus(); MessageBox.Show("Tài khoản trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } txtHoten.Text = txtHoten.Text.Trim(); if (String.IsNullOrEmpty(txtHoten.Text)) { txtHoten.Focus(); MessageBox.Show("Họ tên trống!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (String.IsNullOrEmpty(txtPassword.Text)) { txtPassword.Focus(); MessageBox.Show("Mật khẩu trống!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (String.IsNullOrEmpty(txtRePass.Text)) { txtRePass.Focus(); MessageBox.Show("Đánh lại mật khẩu trống!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (txtRePass.Text != txtPassword.Text) { txtRePass.Focus(); txtRePass.SelectAll(); MessageBox.Show("Đánh lại mật khẩu không đúng!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (cboQuyen.SelectedIndex == -1) { cboQuyen.Focus(); MessageBox.Show("Bạn chưa chọn quyền!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return true; } private void btnGhi_Click(object sender, EventArgs e) { try { if (!this.CheckForm()) return; Entity.UserEntity nv = new Entity.UserEntity() { UserName = txtUsername.Text, Password = txtPassword.Text, HoTen = txtHoten.Text, Quyen = Convert.ToByte(cboQuyen.SelectedIndex), QuyenHan = BuildQuyenhan() }; if (TrangThai == TrangThai.Them) { try { nv.Password = Xuly.Xuly.MaHoaPassword(nv.Password); Business.UserBO.Insert(nv); } catch { MessageBox.Show("Đã tồn tại tài khoản '" + nv.UserName + "'", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } onsaved(); this.Close(); } else { if (_passBefore != txtPassword.Text) { nv.Password = Xuly.Xuly.MaHoaPassword(nv.Password); } Int32 kq = Business.UserBO.Update(nv); onsaved(); this.Close(); } } catch (System.Exception ex) { MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private String BuildQuyenhan() { Char[] str = new Char[17]; // dộ dài chuỗi là 17 for (int i = 0; i < str.Length; i++) { str[i] = '0'; } str[(Int32)ThuTuButton.BangChotKet] = BuildMotBit(chkBangChotKet.Checked); str[(Int32)ThuTuButton.BangGia] = BuildMotBit(chkBangGia.Checked); str[(Int32)ThuTuButton.CatDo] = BuildMotBit(chkCatDo.Checked); str[(Int32)ThuTuButton.CauHinh] = BuildMotBit(chkCauHinh.Checked); str[(Int32)ThuTuButton.DanhSachPhieu] = BuildMotBit(chkDanhSachPhieu.Checked); str[(Int32)ThuTuButton.DoiMatKhau] = BuildMotBit(chkDoiMatKhau.Checked); str[(Int32)ThuTuButton.DotGiamGia] = BuildMotBit(chkDotGiamGia.Checked); str[(Int32)ThuTuButton.GiaDeDo] = BuildMotBit(chkGiaDeDo.Checked); str[(Int32)ThuTuButton.KieuGiat] = BuildMotBit(chkKieuGiat.Checked); str[(Int32)ThuTuButton.KhachHang] = BuildMotBit(chkKhachHang.Checked); str[(Int32)ThuTuButton.LapPhieu] = BuildMotBit(chkLapPhieu.Checked); str[(Int32)ThuTuButton.LoaiHang] = BuildMotBit(chkLoaiHang.Checked); str[(Int32)ThuTuButton.LoaiKhachHang] = BuildMotBit(chkLoaiKhachHang.Checked); str[(Int32)ThuTuButton.MatHang] = BuildMotBit(chkMatHang.Checked); str[(Int32)ThuTuButton.NhanVien] = BuildMotBit(chkNhanVien.Checked); str[(Int32)ThuTuButton.NhungViecCanLam]= BuildMotBit(chkNhungViecCanLam.Checked); str[(Int32)ThuTuButton.ThongKeThuNhap] = BuildMotBit(chkThongKeThuNhap.Checked); return new String(str); } private char BuildMotBit(Boolean b) { return b ? '1' : '0'; } private void btnThoat_Click(object sender, EventArgs e) { this.Close(); } private void txtUsername_KeyDown(object sender, KeyEventArgs e) { Xuly.Xuly.ControlFocus(e, txtHoten); } private void txtHoten_KeyDown(object sender, KeyEventArgs e) { Xuly.Xuly.ControlFocus(e, txtPassword); } private void txtPassword_KeyDown(object sender, KeyEventArgs e) { Xuly.Xuly.ControlFocus(e, txtRePass); } private void txtRePass_KeyDown(object sender, KeyEventArgs e) { Xuly.Xuly.ControlFocus(e, cboQuyen); } private void cboQuyen_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) btnGhi_Click(sender, e); } } }
using Common.Lib.Extensions; using Reception.Handlers.Abstractions; using Reception.Contracts.Requests; using Reception.Domain.Entities; using Reception.Domain.Services.Abstractions; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Reception.Domain.Services { /// <summary> /// Реализация доменного сервиса оборудования. /// </summary> public class EquipmentService : IEquipmentService { private readonly IReadOnlyRepository<Equipment> _equipmentRepository; /// <summary> /// Инициализирует экземпляр <see cref="EquipmentService"/>. /// </summary> /// <param name="equipmentRepository">Репозиторий оборудования.</param> public EquipmentService(IReadOnlyRepository<Equipment> equipmentRepository) { _equipmentRepository = equipmentRepository; } public Task<IReadOnlyCollection<Equipment>> GetByRequestAsync(EquipmentRequest request, CancellationToken cancellation) { return _equipmentRepository.QueryCollectionAsync(q=> { var query = q; if (request.Node.HasValue) query = query.Where(e => e.IsNode == request.Node.Value); query = request.ParentIds.IsNotEmpty() ? query.Where(e => e.ParentId != null && request.ParentIds.Contains(e.ParentId.Value)) : query.Where(e => e.ParentId == null); if (!string.IsNullOrEmpty(request.Name)) query = query.Where(e => e.Name.StartsWith(request.Name)); return query; }, cancellation); } /// <inheritdoc/> public Task<Equipment> GetOrDefaultAsync(int id, CancellationToken cancellation) { return _equipmentRepository.FindAsync(id, cancellation); } } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Reflection; namespace Ayende.NHibernateQueryAnalyzer.SchemaEditing { /// <summary> /// Summary description for TextNodeFieldReference. /// </summary> public class TextNodeFieldReference : AttributeFieldReference { public TextNodeFieldReference(object parent, FieldInfo field) :base(parent, field, null) {} public override string Name { get { return "text()"; } } public override object Value { get { object value = base.Value; if(value==null) return null; return ((string[])value)[0]; } set { base.Value = new string[]{(string)value}; } } public override Type Type { get { return typeof(string); } } } }
using System.Text; using DotNetty.Buffers; namespace Plus.Communication.Packets.Incoming { public class ClientPacket { private readonly IByteBuffer _buffer; public short Id { get; } public ClientPacket(short id, IByteBuffer buf) { Id = id; _buffer = buf; } public string PopString() { int length = _buffer.ReadShort(); IByteBuffer data = _buffer.ReadBytes(length); return Encoding.UTF8.GetString(data.Array); } public int PopInt() { return _buffer.ReadInt(); } public bool PopBoolean() { return _buffer.ReadByte() == 1; } public int RemainingLength() { return _buffer.ReadableBytes; } } }
namespace Promact.Oauth.Server.StringLiterals { public class StringLiteral { public Account Account { get; set; } public ConsumerApp ConsumerApp { get; set; } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace SDKWebPortalWebAPI.Migrations { public partial class HouseIdAdd : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "HouseId", table: "PersonelQuestions", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "HouseId", table: "PersonelAnswers", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "HouseId", table: "ObservationQuestions", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "HouseId", table: "ObservationAnswers", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<int>( name: "HouseId", table: "HouseQuestions", nullable: false, defaultValue: 0); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "HouseId", table: "PersonelQuestions"); migrationBuilder.DropColumn( name: "HouseId", table: "PersonelAnswers"); migrationBuilder.DropColumn( name: "HouseId", table: "ObservationQuestions"); migrationBuilder.DropColumn( name: "HouseId", table: "ObservationAnswers"); migrationBuilder.DropColumn( name: "HouseId", table: "HouseQuestions"); } } }
using FindSelf.Application.Configuration.Vaildation; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FindSelf.API.SeedWork { public class InvalidCommandExceptionProblemDetail : ProblemDetails { public InvalidCommandExceptionProblemDetail(InvalidCommandException exception) { this.Detail = exception.Details; this.Title = exception.Message; this.Status = StatusCodes.Status400BadRequest; this.Type = "https://somedomain/validation-error"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.Kinect; using PPt = Microsoft.Office.Interop.PowerPoint; using System.Runtime.InteropServices; /* @Auther Somin Lee(makersm, sayyo1120@gmail.com) * This is ppt eventlisteners list. * You have to write conditions in each of functions. * PPT eventlists' conditions are using skeleton event. */ namespace PreHands.PPT { public class ppt_eventLists { private static SkeletonPoint lastHandPoint; private static SkeletonPoint curHandPoint; private static int rightCount = 0; private static int leftCount = 0; static bool startFlag = false; static bool endFlag = false; private static Timer timer; private static int controlChecker = 0; // Define PowerPoint Application object private static PPt.Application pptApplication; // Define Presentation object private static PPt.Presentation presentation; // Define Slide collection private static PPt.Slides slides; private static PPt.Slide slide; // Slide count private static int slidescount; // slide index private static int slideIndex; public static void PPTSearch() { try { // Get Running PowerPoint Application object pptApplication = Marshal.GetActiveObject("PowerPoint.Application") as PPt.Application; // Get PowerPoint application successfully, then set control button enable } catch { MessageBox.Show("Please Run PowerPoint Firstly", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } if (pptApplication != null) { // Get Presentation Object presentation = pptApplication.ActivePresentation; // Get Slide collection object slides = presentation.Slides; // Get Slide count slidescount = slides.Count; // Get current selected slide try { // Get selected slide object in normal view slide = slides[pptApplication.ActiveWindow.Selection.SlideRange.SlideNumber]; } catch { // Get selected slide object in reading view slide = pptApplication.SlideShowWindows[1].View.Slide; } } } public static void nextPage() { slideIndex = slide.SlideIndex + 1; if (slideIndex > slidescount) { MessageBox.Show("It is already last page"); } else { try { slide = slides[slideIndex]; slides[slideIndex].Select(); } catch { pptApplication.SlideShowWindows[1].View.Next(); slide = pptApplication.SlideShowWindows[1].View.Slide; } } } public static void previousPage() { slideIndex = slide.SlideIndex - 1; if (slideIndex >= 1) { try { slide = slides[slideIndex]; slides[slideIndex].Select(); } catch { pptApplication.SlideShowWindows[1].View.Previous(); slide = pptApplication.SlideShowWindows[1].View.Slide; } } else { MessageBox.Show("It is already Fist Page"); } } public static void startPPTControl(object sender, EventArgs e) { Skeleton_eventArgs eventarg = e as Skeleton_eventArgs; SkeletonPoint r_hand = eventarg.skeleton.Joints[JointType.HandRight].Position; SkeletonPoint head = eventarg.skeleton.Joints[JointType.Head].Position; SkeletonPoint r_shoulder = eventarg.skeleton.Joints[JointType.ShoulderRight].Position; if (controlChecker == 90) { //MainWindow.isPPTActive = MainWindow.isPPTActive == true ? false : true; System.Diagnostics.Debug.WriteLine("active"); } if (head.Y >= r_hand.Y && r_shoulder.X + 0.1 >= r_hand.X) { controlChecker++; } else { controlChecker = 0; } } private static bool isSlideGestureReady(SkeletonPoint hand, SkeletonPoint shoulder) { return (Math.Abs(shoulder.Y - hand.Y) < 0.15 && !(hand.X == shoulder.X)) ? true : false; } private static bool isGestureReady(object sender, EventArgs e) { Skeleton_eventArgs eventarg = e as Skeleton_eventArgs; SkeletonPoint r_shoulder = eventarg.skeleton.Joints[JointType.ShoulderRight].Position; SkeletonPoint l_shoulder = eventarg.skeleton.Joints[JointType.ShoulderLeft].Position; //System.Diagnostics.Debug.WriteLine("r_shoulder z : " + r_shoulder.Z); //System.Diagnostics.Debug.WriteLine("l_shoulder z : " + l_shoulder.Z); //System.Diagnostics.Debug.WriteLine("spine z : " + spine.Z); return (Math.Abs(r_shoulder.Z - l_shoulder.Z) >= 0.085) ? false : true; } public static void startPPT(object sender, EventArgs e) { if (!isGestureReady(sender, e)) return; Skeleton_eventArgs eventarg = e as Skeleton_eventArgs; SkeletonPoint head = eventarg.skeleton.Joints[JointType.Head].Position; SkeletonPoint compare = eventarg.skeleton.Joints[JointType.HandRight].Position; float shoulder = eventarg.skeleton.Joints[JointType.ShoulderRight].Position.Y; if (head.Y <= compare.Y && head.Z < compare.Z) { if (!startFlag) { // SendKeys.SendWait("{F5}"); PPTSearch(); presentation.SlideShowSettings.Run(); System.Diagnostics.Debug.WriteLine("f5"); startFlag = true; } } else { startFlag = false; } } private static void SlideTimer(Object sender, EventArgs eventarg) { timer.Enabled = false; } public static void SlideChecker(object sender, EventArgs e) { if (!isGestureReady(sender, e)) return; Skeleton_eventArgs eventarg = e as Skeleton_eventArgs; SkeletonPoint hand = eventarg.skeleton.Joints[JointType.HandRight].Position; SkeletonPoint shoulder = eventarg.skeleton.Joints[JointType.ShoulderRight].Position; SkeletonPoint spine = eventarg.skeleton.Joints[JointType.Spine].Position; if (isSlideGestureReady(hand, shoulder)) { if (lastHandPoint == null) lastHandPoint = hand; curHandPoint = hand; if (curHandPoint.X - lastHandPoint.X > 0.01) { if (curHandPoint.X < shoulder.X) return; rightCount++; leftCount = 0; } else if (curHandPoint.X - lastHandPoint.X < -0.01) { leftCount++; rightCount = 0; } if (rightCount > 6 && spine.X < curHandPoint.X) { goNextSlide(); rightCount = 0; } if (leftCount > 4 && spine.X > curHandPoint.X) { goPreviousSlide(); leftCount = 0; } lastHandPoint = curHandPoint; } } private static void goPreviousSlide() { SendKeys.SendWait("{left}"); System.Diagnostics.Debug.WriteLine("left"); } private static void goNextSlide() { SendKeys.SendWait("{right}"); System.Diagnostics.Debug.WriteLine("right"); } public static void endPPT(object sender, EventArgs e) { if (!isGestureReady(sender, e)) return; Skeleton_eventArgs eventarg = e as Skeleton_eventArgs; SkeletonPoint hand = eventarg.skeleton.Joints[JointType.HandRight].Position; SkeletonPoint hip = eventarg.skeleton.Joints[JointType.HipRight].Position; if (hand.Y < hip.Y && hand.Z > hip.Z) { if (!endFlag) { SendKeys.SendWait("{esc}"); System.Diagnostics.Debug.WriteLine("esc"); endFlag = true; //MainWindow.isPPTActive = false; } } else { endFlag = false; } } } }
// ---------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="IMessageTransciever.cs" company="David Eiwen"> // Copyright (c) David Eiwen. All rights reserved. // </copyright> // <author>David Eiwen</author> // <summary> // This file contains the IMessageTransciever interface. // </summary> // ---------------------------------------------------------------------------------------------------------------------------------------- namespace IndiePortable.Communication.Core.Devices { /// <summary> /// Represents a logical device that can send and receive <see cref="Messages.MessageBase" /> objects. /// </summary> /// <seealso cref="IMessageReceiver" /> /// <seealso cref="IMessageTransmitter" /> public interface IMessageTransciever : IMessageReceiver, IMessageTransmitter { } }
using UnityEngine; using System.Collections; using System.IO; using System; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using VectorExtension; public static class Serialization { public static string saveFolderName = "data"; public static bool LoadArray(string fileName, int saveSlot, out float[] array) { string saveFile = GetSaveFileNameAndDirectory(fileName, saveSlot); array = new float[0]; if (!File.Exists(saveFile)) return false; IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(saveFile, FileMode.Open); float[] newArray = (float[])formatter.Deserialize(stream); array = newArray; stream.Close(); return true; } public static bool SaveArray(string fileName, float[] array, int saveSlot) { string saveFile = GetSaveFileNameAndDirectory(fileName, saveSlot); IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, array); stream.Close(); return true; } #region class data public static bool LoadClassData(string fileName, int saveSlot, out System.Object serializedObject) { string saveFile = GetSaveFileNameAndDirectory(fileName, saveSlot); serializedObject = new System.Object(); if (!File.Exists(saveFile)) return false; IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(saveFile, FileMode.Open); serializedObject = formatter.Deserialize(stream); stream.Close(); return true; } public static bool SaveClassData(IPersistence objectToSave, int saveSlot) { string saveFile = GetSaveFileNameAndDirectory(objectToSave.fileName, saveSlot); IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, objectToSave); stream.Close(); return true; } private static string GetSaveFileNameAndDirectory(string fileName, int saveSlot) { string[] saveFolders = { "saves", "slot_" + saveSlot.ToString() }; if (fileName.Contains("year")) saveFolders = new string[] { saveFolders[0], saveFolders[1], "trajectory"}; // tick data are saved in the trajectory folder string saveFile = SaveLocation(saveFolders); saveFile += fileName; return saveFile; } #endregion #region raster public static bool LoadRaster2D(string fileName, Rect sector, out float[,] output) { string saveFile = SaveLocation("terrain"); saveFile += fileName; int sectorWidth = Mathf.FloorToInt(sector.width); int sectorHeight = Mathf.FloorToInt(sector.height); output = new float[sectorWidth, sectorHeight]; if (!File.Exists(saveFile)) return false; IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(saveFile, FileMode.Open); float[,] raster = (float[,])formatter.Deserialize(stream); if (raster.GetLength(0) < sectorWidth || raster.GetLength(1) < sectorHeight) { Debug.Log("Error in Serialization: sector is too large or raster file too small."); return false; } for (int x = 0; x < sectorWidth; x++) { for (int y = 0; y < sectorHeight; y++) { output[y, x] = raster[Mathf.FloorToInt(sector.y) + y, Mathf.FloorToInt(sector.x) + x]; } } stream.Close(); return true; } public static bool LoadRaster3D(string fileName, Rect sector, int var3D, out float[,,] output) { string saveFile = SaveLocation("terrain"); saveFile += fileName; int sectorWidth = Mathf.FloorToInt(sector.width); int sectorHeight = Mathf.FloorToInt(sector.height); output = new float[sectorWidth, sectorHeight, var3D]; if (!File.Exists(saveFile)) return false; IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(saveFile, FileMode.Open); float[,,] raster = (float[,,])formatter.Deserialize(stream); if (raster.GetLength(0) < sectorWidth || raster.GetLength(1) < sectorHeight) { Debug.LogError("Sector is too large or raster file too small."); return false; } if (raster.GetLength(2) != var3D) { Debug.LogError("Raster in file has " + raster.GetLength(2) + " variables while " + var3D + " are requested."); } for (int x = 0; x < sectorWidth; x++) { for (int y = 0; y < sectorHeight; y++) { for (int i = 0; i < var3D; i++) { output[y, x, i] = raster[Mathf.FloorToInt(sector.y) + y, Mathf.FloorToInt(sector.x) + x, i]; } } } stream.Close(); return true; } public static void SaveRaster2D(string fileName, float[,] raster) { string saveFile = SaveLocation("terrain"); saveFile += fileName; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, raster); stream.Close(); } public static void SaveRaster3D(string fileName, float[,,] raster) { string saveFile = SaveLocation("terrain"); saveFile += fileName; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, raster); stream.Close(); } public static void SaveAlphamap(float[,,] alphamap) { string saveFile = SaveLocation("terrain"); saveFile += "alphamap"; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, alphamap); stream.Close(); } public static void SaveHeightmap(float[,] heightmap) { string saveFile = SaveLocation("terrain"); saveFile += "heightmap"; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, heightmap); stream.Close(); } #endregion public static string SaveLocation(string folderName) { string[] folderNames = { folderName }; return SaveLocation(folderNames); } public static string SaveLocation(string[] folderNames) { string saveLocation = saveFolderName + "/"; foreach (string folderName in folderNames) { saveLocation += folderName + "/"; if (!Directory.Exists(saveLocation)) { Directory.CreateDirectory(saveLocation); } } return saveLocation; } }
using Microsoft.Xna.Framework; namespace MonoGame.Extended.NuclexGui { /// <summary>Two-dimensional rectangle of combined fraction and offset coordinates</summary> public struct UniRectangle { /// <summary>An empty unified rectangle</summary> public static readonly UniRectangle Empty = new UniRectangle(); /// <summary>X coordinate of the rectangle's left border</summary> public UniScalar Left { get { return Location.X; } set { Location.X = value; } } /// <summary>Y coordinate of the rectangle's upper border</summary> public UniScalar Top { get { return Location.Y; } set { Location.Y = value; } } /// <summary>X coordinate of the rectangle's right border</summary> public UniScalar Right { get { return Location.X + Size.X; } set { Size.X = value - Location.X; } } /// <summary>Y coordinate of the rectangle's lower border</summary> public UniScalar Bottom { get { return Location.Y + Size.Y; } set { Size.Y = value - Location.Y; } } /// <summary>Point consisting of the lesser coordinates of the rectangle</summary> public UniVector Min { get { return Location; } set { // In short: this.Size += this.Location - value; // Done for performance reasons Size.X.Fraction += Location.X.Fraction - value.X.Fraction; Size.X.Offset += Location.X.Offset - value.X.Offset; Size.Y.Fraction += Location.Y.Fraction - value.Y.Fraction; Size.Y.Offset += Location.Y.Offset - value.Y.Offset; Location = value; } } /// <summary>Point consisting of the greater coordinates of the rectangle</summary> public UniVector Max { get { return Location + Size; } set { // In short: this.Size = value - this.Location; // Done for performance reasons Size.X.Fraction = value.X.Fraction - Location.X.Fraction; Size.X.Offset = value.X.Offset - Location.X.Offset; Size.Y.Fraction = value.Y.Fraction - Location.X.Fraction; Size.Y.Offset = value.Y.Offset - Location.Y.Offset; } } /// <summary>The location of the rectangle's upper left corner</summary> public UniVector Location; /// <summary>The size of the rectangle</summary> public UniVector Size; /// <summary>Initializes a new rectangle from a location and a size</summary> /// <param name="location">Location of the rectangle's upper left corner</param> /// <param name="size">Size of the area covered by the rectangle</param> public UniRectangle(UniVector location, UniVector size) { Location = location; Size = size; } /// <summary>Initializes a new rectangle from the provided individual coordinates</summary> /// <param name="x">X coordinate of the rectangle's left border</param> /// <param name="y">Y coordinate of the rectangle's upper border</param> /// <param name="width">Width of the area covered by the rectangle</param> /// <param name="height">Height of the area covered by the rectangle</param> public UniRectangle(UniScalar x, UniScalar y, UniScalar width, UniScalar height) { Location = new UniVector(x, y); Size = new UniVector(width, height); } /// <summary>Converts the rectangle into pure offset coordinates</summary> /// <param name="containerSize">Dimensions of the container the fractional part of the rectangle count for</param> /// <returns>A rectangle with the pure offset coordinates of the rectangle</returns> public RectangleF ToOffset(Vector2 containerSize) { return ToOffset(containerSize.X, containerSize.Y); } /// <summary>Converts the rectangle into pure offset coordinates</summary> /// <param name="containerWidth">Width of the container the fractional part of the rectangle counts for</param> /// <param name="containerHeight">Height of the container the fractional part of the rectangle counts for</param> /// <returns>A rectangle with the pure offset coordinates of the rectangle</returns> public RectangleF ToOffset(float containerWidth, float containerHeight) { var leftOffset = Left.Fraction*containerWidth + Left.Offset; var topOffset = Top.Fraction*containerHeight + Top.Offset; return new RectangleF( leftOffset, topOffset, Right.Fraction*containerWidth + Right.Offset - leftOffset, Bottom.Fraction*containerHeight + Bottom.Offset - topOffset ); } /// <summary>Checks two rectangles for inequality</summary> /// <param name="first">First rectangle to be compared</param> /// <param name="second">Second rectangle to be compared</param> /// <returns>True if the instances differ or exactly one reference is set to null</returns> public static bool operator !=(UniRectangle first, UniRectangle second) { return !(first == second); } /// <summary>Checks two rectangles for equality</summary> /// <param name="first">First rectangle to be compared</param> /// <param name="second">Second rectangle to be compared</param> /// <returns>True if both instances are equal or both references are null</returns> public static bool operator ==(UniRectangle first, UniRectangle second) { // For a struct, neither 'first' nor 'second' can be null return first.Equals(second); } /// <summary>Checks whether another instance is equal to this instance</summary> /// <param name="other">Other instance to compare to this instance</param> /// <returns>True if the other instance is equal to this instance</returns> public override bool Equals(object other) { if (!(other is UniRectangle)) return false; return Equals((UniRectangle) other); } /// <summary>Checks whether another instance is equal to this instance</summary> /// <param name="other">Other instance to compare to this instance</param> /// <returns>True if the other instance is equal to this instance</returns> public bool Equals(UniRectangle other) { // For a struct, 'other' cannot be null return (Location == other.Location) && (Size == other.Size); } /// <summary>Obtains a hash code of this instance</summary> /// <returns>The hash code of the instance</returns> public override int GetHashCode() { return Location.GetHashCode() ^ Size.GetHashCode(); } /// <summary> /// Returns a human-readable string representation for the unified rectangle /// </summary> /// <returns>The human-readable string representation of the unified rectangle</returns> public override string ToString() { return string.Format( "{{Location:{0}, Size:{1}}}", Location, Size ); } /// <summary> /// Moves unified rectangle by the absolute values /// </summary> public void AbsoluteOffset(float x, float y) { Location.X.Offset += x; Location.Y.Offset += y; } public void FractionalOffset(float x, float y) { Location.X.Fraction += x; Location.Y.Fraction += y; } } }
using UnityEngine; namespace UnityAssets.Camera_Aspect_Ratio_Rectifier { public class cameraZoomController : MonoBehaviour { public bool maintainWidth=true; //what should i maintain [Range(-1,1)] public int adaptPosition=0; //in what direction to anchor Vector3 cameraPos; //gets default camera position float defaultHeight; //needed to keep anchor top or bottom float defaultAspectRatio; //needed to keep anchor in the sides float defaultWidth = 5 ; //not needed, since could be obtained from other two void Start () { cameraPos = Camera.main.transform.position; //reference to camera position defaultAspectRatio = Camera.main.aspect; //reference to default aspect defaultHeight = Camera.main.orthographicSize; //reference to default orthosize defaultWidth = Camera.main.aspect * Camera.main.orthographicSize; cameraPos = Camera.main.transform.position; } // Update is called once per frame void Update () { //ATTENTION IS ONLY HERE FOR TESTING, AFTER TESTING PUT IT ON THE END //of Start() TO AVOID REPETITION //maintains width of screen for multiple formats if (maintainWidth) { Camera.main.orthographicSize = defaultWidth/ Camera.main.aspect; Camera.main.transform.position = cameraPos+new Vector3 ( 0, adaptPosition*(defaultHeight- Camera.main.orthographicSize), -10); } else //screen height is maintained by default { Camera.main.transform.position = cameraPos+new Vector3 ( adaptPosition*(defaultAspectRatio*Camera.main.orthographicSize - Camera.main.aspect * Camera.main.orthographicSize), 0, -10); } } } }
using System.Collections; using System.Collections.Generic; using System.Runtime.ExceptionServices; using UnityEngine; public class WeaponManager : MonoBehaviour { public static bool isChangeWeapon = false; [SerializeField] private float changeWeaponDelayTime; [SerializeField] private float changeWeaponEndDealyTime; //무기 종류들 관리. [SerializeField] private Gun_Manager[] guns; public static Transform currentWeapon; private Dictionary<string, Gun_Manager> GunDictionary = new Dictionary<string, Gun_Manager>(); void Start() { for (int i = 0; i < guns.Length; i++) { GunDictionary.Add(guns[i].GunName, guns[i]); } } // Update is called once per frame void Update() { if(!isChangeWeapon) { if(Input.GetKeyDown(KeyCode.Alpha1)) { StartCoroutine(ChangeWeaponCoroutine("AR")); } if (Input.GetKeyDown(KeyCode.Alpha2)) { StartCoroutine(ChangeWeaponCoroutine("SubMachinGun")); } if (Input.GetKeyDown(KeyCode.Alpha3)) { StartCoroutine(ChangeWeaponCoroutine("ShootGun")); } } } public IEnumerator ChangeWeaponCoroutine(string _name) { isChangeWeapon = true; yield return new WaitForSeconds(changeWeaponDelayTime); Gun_Shooting.instance.CancelReload(); Gun_Shooting.instance.GunChange(GunDictionary[_name]); yield return new WaitForSeconds(changeWeaponEndDealyTime); isChangeWeapon = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace nutrition.Services.Models { public class NutritionFactsResults { public int total_hits { get; set; } public float max_score { get; set; } public Hit[] hits { get; set; } } public class Hit { public string _index { get; set; } public string _type { get; set; } public string _id { get; set; } public float _score { get; set; } public Fields fields { get; set; } } public class Fields { public string item_id { get; set; } public string item_name { get; set; } public string brand_name { get; set; } public float nf_calories { get; set; } public int nf_serving_size_qty { get; set; } public string nf_serving_size_unit { get; set; } } }
using System; using System.Globalization; using Humanizer; using Humanizer.Localisation; namespace Mitheti.Wpf.ViewModels { public static class Extensions { internal static string LanguageCodeConfigKey = "Language:Code"; internal static string HumanizeForStatistic(this TimeSpan timeSpan, string languageCode) => timeSpan.Humanize( precision: 2, countEmptyUnits: true, culture: new CultureInfo(languageCode), minUnit: TimeUnit.Second, maxUnit: TimeUnit.Day, toWords: false); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Game.Web.UI; using Game.Kernel; using System.Text; using Game.Utils; using System.Data; using Game.Facade; namespace Game.Web.Module.AccountManager { public partial class AccountsInsureTop : AdminPage { protected void Page_Load( object sender, EventArgs e ) { if( !IsPostBack ) { BindData(); } } //绑定数据 private void BindData() { DataSet ds = FacadeManage.aideTreasureFacade.GetUserTransferTop100(); if( ds.Tables[0].Rows.Count > 0 ) { rptDataList.Visible = true; litNoData.Visible = false; rptDataList.DataSource = ds; rptDataList.DataBind(); } else { rptDataList.Visible = true; litNoData.Visible = false; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScreenShake : MonoBehaviour { private Animator anim; void Awake() { anim = GetComponent<Animator>(); } public void DoScreenShake(int intensity) { if (intensity == 1) anim.SetTrigger("Shake01"); else if (intensity == 2) anim.SetTrigger("Shake02"); } }
namespace uDateFoldersy.Helpers { using System; using System.Globalization; public class DateHelper { /// <summary> /// Gets month name /// </summary> /// <param name="month"></param> /// <param name="abbreviate"></param> /// <param name="provider"></param> /// <returns></returns> public static string GetMonthName(int month, bool abbreviate, IFormatProvider provider) { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(provider); if (abbreviate) return info.GetAbbreviatedMonthName(month); return info.GetMonthName(month); } /// <summary> /// Gets abbreviated month name /// </summary> /// <param name="month"></param> /// <param name="abbreviate"></param> /// <returns></returns> public static string GetMonthName(int month, bool abbreviate) { return GetMonthName(month, abbreviate, null); } /// <summary> /// Gets non-abbreviated month name. /// </summary> /// <param name="month"></param> /// <param name="provider"></param> /// <returns></returns> public static string GetMonthName(int month, IFormatProvider provider) { return GetMonthName(month, false, provider); } /// <summary> /// Gets non-abbreviated month name. /// </summary> /// <param name="month"></param> /// <returns></returns> public static string GetMonthName(int month) { return GetMonthName(month, false, null); } /// <summary> /// Gets day name. /// </summary> /// <param name="day"></param> /// <param name="abbreviate"></param> /// <param name="provider"></param> /// <returns></returns> public static string GetDayName(int day, bool abbreviate, IFormatProvider provider) { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(provider); DateTime date = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, day); if (abbreviate) return info.GetAbbreviatedDayName(date.DayOfWeek); return info.GetDayName(date.DayOfWeek); } /// <summary> /// Gets abbreviated day name. /// </summary> /// <param name="day"></param> /// <param name="abbreviate"></param> /// <returns></returns> public static string GetDayName(int day, bool abbreviate) { return GetDayName(day, abbreviate, null); } /// <summary> /// Gets day name. /// </summary> /// <param name="day"></param> /// <param name="provider"></param> /// <returns></returns> public static string GetDayName(int day, IFormatProvider provider) { return GetDayName(day, false, provider); } /// <summary> /// Gets non-abbreviated day name. /// </summary> /// <param name="day"></param> /// <returns></returns> public static string GetDayName(int day) { return GetDayName(day, false, null); } /// <summary> /// Determines which format the month name should be in based on format. /// </summary> /// <param name="format"></param> /// <param name="monthNumber"></param> /// <returns></returns> public static string GetMonthNameWithFormat(int monthNumber, string format) { if (format == "M") { return monthNumber.ToString(); } var date = new DateTime(2012, monthNumber, 1); var month = date.ToString(format); return month; } /// <summary> /// Determines which format the day name should be in based on format. /// </summary> /// <param name="format"></param> /// <param name="dayNumber"></param> /// <returns></returns> public static string GetDayNameWithFormat(int dayNumber, string format) { if (format == "d") { return dayNumber.ToString(); } var date = new DateTime(2012, 1, dayNumber); var day = date.ToString(format); return day; } } }
using System; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace WorkflowHandler.IPFS_EXCHANGE { class Requestor: IDisposable { private readonly IConnection connection; private readonly IModel channel; public Requestor(string hostname) { ConnectionFactory factory = new ConnectionFactory() { HostName = hostname }; this.connection = factory.CreateConnection(); this.channel = connection.CreateModel(); this.channel.ExchangeDeclare(exchange: "data_save_request", type: "direct"); } public void CommitData(string module, string schema, string name, bool isUpdate, JObject data, Action<string> responseHandler) { Guid requestId = Guid.NewGuid(); responseHandler(requestId.ToString()); Console.WriteLine($" [*] Sending message to exchange `data_save_request` with requestId {requestId}"); byte[] parts = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { REQUEST_ID = requestId, MODULE = module, SCHEMA = schema, NAME = name, IS_UPDATE = isUpdate, DATA = data })); this.channel.BasicPublish(exchange: "data_save_request", routingKey: "", basicProperties: null, body: parts); } void IDisposable.Dispose() { this.connection.Dispose(); this.channel.Dispose(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Application.DTO { public class PostTagDto : BaseDto { public PostDto PostId { get; set; } public TagDto TagId { get; set; } public ICollection<TagDto> Tags { get; set; } public ICollection<PostDto> Posts { get; set; } } }
using System.Collections.Generic; using System.Linq; using ServicesLibrary.Helpers; using ServicesLibrary.Interfaces; using ServicesLibrary.Models; namespace ServicesLibrary.Services { public class LocalService: ILocalService { private readonly DataContext _context; public LocalService(DataContext context) { this._context = context; } public List<ServiceDto> GetAllServices() { return this._context.Services.ToList(); } public List<StoreDto> GetAllStores() { return this._context.Stores.ToList(); } public List<StoreDto> GetAllStoresOrderedByRank() { return this._context.Stores.OrderBy(x => x.Rank).ToList(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IActionResult.cs" company=""> // // </copyright> // <summary> // The ActionResult interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleWebServer.Framework.Actions { using ConsoleWebServer.Framework.Http; /// <summary> /// The ActionResult interface. Used to get the response from the server. /// </summary> public interface IActionResult { /// <summary> /// HttpResponse response returned after performed action /// </summary> /// <returns> /// The <see cref="HttpResponse" />. /// </returns> HttpResponse GetResponse(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace ListViewApp { class Data { public string txtTootja { get; set; } public string txtModel { get; set; } public string txtKW { get; set; } public int image { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Starby : MonoBehaviour { public GameObject bulletObject; public float volume; const float JUMP_VELOCITY = 10.0f; const float WALK_VELOCITY = 7.0f; const float DAMAGE_VELOCITY_X = 7.0f; const float DAMAGE_VELOCITY_Y = 10.0f; const float SPIT_OUT_FORCE = 800.0f; const float JUMP_KEY_MAX_TIME = 0.2f; const float STOP_TIME = 0.5f; const float INVINCIBLE_TIME = 1.0f; const float SWALLOW_TIME = 0.3f; private Animator animator; private Rigidbody2D rb; private SpriteRenderer spriteRenderer; public enum State { Stand = 0, Walk = 1, Jump = 2, Crouching = 3, Sucking = 4, MouthFullStand = 10, MouthFullWalk = 11, MouthFullJump = 12, MouthFullCrouching = 13 }; State state, beforeState; GameObject suckingEffect; AudioSource suckingAudioSource; Gauge hpGaugeScript; FootJudgement footJudgement; bool isMouthFull, isRight; float velocityX, velocityY; float invincibleTime, stopTime; float pressJumpKeyTime, pressCrouchingKeyTime, pressMoveKeyTime, singingTime; void Awake() { animator = GetComponent<Animator>(); rb = GetComponent<Rigidbody2D>(); spriteRenderer = GetComponent<SpriteRenderer>(); suckingAudioSource = GetComponent<AudioSource>(); } void Start() { footJudgement = GetComponentInChildren<FootJudgement>(); suckingEffect = GameObject.Find("SuckingEffect"); hpGaugeScript = GameObject.Find("HP").GetComponent<Gauge>(); Init(); // とりあえずここ置いとく //AudioManager.Instance.FadeInBGM("bgm_maoudamashii_8bit25"); AudioManager.Instance.PlayBGM("bgm_maoudamashii_8bit25", volume); } void Init() { state = State.Stand; beforeState = State.Stand; isMouthFull = false; isRight = true; invincibleTime = 0; stopTime = 0; singingTime = 0; transform.position = StaticValues.playerPos; } void Update() { velocityX = rb.velocity.x; velocityY = rb.velocity.y; UpdateColor(); UpdateTimes(); UpdateMove(); UpdateJump(); UpdateSuckingEffect(); if (isMouthFull && Input.GetButtonDown("Shot")) // 吐き出し SpitOut(); // 飲み込み if (state == State.MouthFullCrouching && (pressCrouchingKeyTime >= SWALLOW_TIME)) { AudioManager.Instance.PlaySE("InMouth", volume); string yummyVoice = "umai" + Random.Range(1, 6); AudioManager.Instance.PlayExVoice(yummyVoice, 0.5f); hpGaugeScript.Heal(10); isMouthFull = false; } // 仮 鼻歌 if (singingTime >= 7.0f && !AudioManager.Instance.IsPlayingExVoice()) { string singVoice = "hanauta" + Random.Range(1, 6); AudioManager.Instance.PlayExVoice(singVoice, 0.5f); singingTime = 0; } else { singingTime += Time.deltaTime; } // デバッグ用 if (Input.GetKey(KeyCode.LeftShift)) { velocityX *= 5; } if (CanMove()) rb.velocity = new Vector2(velocityX, velocityY); UpdateState(); } private void UpdateColor() { if (IsInvincible()) spriteRenderer.color = new Vector4(1, 1, 1, 0.5f); else spriteRenderer.color = new Vector4(1, 1, 1, 1); } private void UpdateTimes() { stopTime -= Time.deltaTime; invincibleTime -= Time.deltaTime; if (CanMove()) { if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.LeftArrow)) pressMoveKeyTime += Time.deltaTime; else pressMoveKeyTime = 0; } } // 移動処理 private void UpdateMove() { if (CanMove()) { if (Input.GetKey(KeyCode.RightArrow)) { velocityX = WALK_VELOCITY * Mathf.Min(pressMoveKeyTime * 5, 1); isRight = true; transform.localScale = new Vector2(1, 1); } else if (Input.GetKey(KeyCode.LeftArrow)) { velocityX = -WALK_VELOCITY * Mathf.Min(pressMoveKeyTime * 5, 1); isRight = false; transform.localScale = new Vector2(-1, 1); } if (!footJudgement.IsLanding()) { if (isMouthFull) state = State.MouthFullJump; else state = State.Jump; } else { if (isMouthFull) state = State.MouthFullStand; else state = State.Stand; } } } // ジャンプ処理 private void UpdateJump() { if (state == State.Jump || state == State.MouthFullJump) { if (Input.GetButton("Jump") && pressJumpKeyTime < JUMP_KEY_MAX_TIME) { pressJumpKeyTime += Time.deltaTime; velocityY = JUMP_VELOCITY; } if (Input.GetButtonUp("Jump")) { pressJumpKeyTime = JUMP_KEY_MAX_TIME; } } else if (CanJump()) { if (Input.GetButtonDown("Jump")) { if (isMouthFull) state = State.MouthFullJump; else state = State.Jump; velocityY = JUMP_VELOCITY; pressJumpKeyTime = 0; AudioManager.Instance.PlaySE("Jump", volume); } } } private void UpdateSuckingEffect() { suckingEffect.SetActive(state == State.Sucking); if (state == State.Sucking) { if (suckingAudioSource != null && suckingAudioSource.isPlaying) { // ループポイントへジャンプ if (suckingAudioSource.time >= 2.2f) suckingAudioSource.time = 1.0f; } else { suckingAudioSource.volume = volume; suckingAudioSource.Play(); } } else { suckingAudioSource.time = 0; suckingAudioSource.Stop(); } } // ステート切り替え private void UpdateState() { switch (state) { case State.Stand: case State.Walk: case State.Crouching: case State.Sucking: case State.MouthFullStand: case State.MouthFullWalk: case State.MouthFullCrouching: if (isMouthFull) { if (System.Math.Abs(velocityX) >= WALK_VELOCITY / 2) // 移動 state = State.MouthFullWalk; else if (Input.GetKey(KeyCode.DownArrow)) { // しゃがみ state = State.MouthFullCrouching; pressCrouchingKeyTime += Time.deltaTime; } else { state = State.MouthFullStand; pressCrouchingKeyTime = 0; } } else { if (Input.GetButton("Shot")) // 吸い込み state = State.Sucking; else if (System.Math.Abs(velocityX) >= WALK_VELOCITY / 2) // 移動 state = State.Walk; else if (Input.GetKey(KeyCode.DownArrow)) // しゃがみ state = State.Crouching; else state = State.Stand; } break; case State.Jump: case State.MouthFullJump: if (Input.GetButton("Shot")) // 吸い込み state = State.Sucking; break; default: break; } if (state != beforeState) { beforeState = state; animator.SetInteger("state", (int)state); } } private bool IsInvincible() { return invincibleTime > 0; } private bool IsStop() { return stopTime > 0; } private bool CanMove() { if (IsStop() || StaticValues.isPause) { return false; } switch (state) { case State.Stand: case State.Walk: case State.Jump: case State.MouthFullStand: case State.MouthFullWalk: case State.MouthFullJump: return true; default: return false; } } private bool CanJump() { if (IsStop()) { return false; } switch (state) { case State.Stand: case State.Walk: case State.Jump: case State.Crouching: case State.MouthFullStand: case State.MouthFullWalk: case State.MouthFullJump: case State.MouthFullCrouching: return true; default: return false; } } public void PutInMouth() { isMouthFull = true; state = State.MouthFullStand; AudioManager.Instance.PlaySE("InMouth", volume); } // 吐き出し public void SpitOut() { AudioManager.Instance.PlaySE("Spit", volume); state = State.Sucking; GameObject bullet = Instantiate(bulletObject); float force = isRight ? SPIT_OUT_FORCE : -SPIT_OUT_FORCE; bullet.transform.position = this.transform.position; bullet.GetComponent<Rigidbody2D>().AddForce(new Vector2(force, 0)); bullet.GetComponent<Rigidbody2D>().AddTorque(500.0f); bullet.GetComponent<Bullet>().SetDeadTime(1.0f); isMouthFull = false; state = State.Stand; } public void TouchEnemy(int damage) { if (!IsInvincible()) { stopTime = STOP_TIME; invincibleTime = INVINCIBLE_TIME; velocityX = isRight ? -DAMAGE_VELOCITY_X : DAMAGE_VELOCITY_X; rb.velocity = new Vector2(velocityX, DAMAGE_VELOCITY_Y); AudioManager.Instance.PlaySE("Damage", volume); hpGaugeScript.Damage(damage); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace SCT_BL.SCT { public class SCT_BAL { public SCT_BAL() { // TODO: Add constructor logic here } private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SCT_BAL)); //*************************************************************************************************** public SCT_AuthUser authenticateUser_BAL(string UserId_BAL, string Pwd_BAL) { try { logger.Info("Method : authenticateUser_BAL Start"); logger.DebugFormat("Input parameter Id : {0} ", UserId_BAL); logger.DebugFormat("Input parameter Password : {0} ", Pwd_BAL); string[] userIds = {"4400","8297","7327","9308"}; string[] userNames = { "Rajat Gautam", "Harish", "Atul", "Deepak Jain" }; SCT_AuthUser authResult = new SCT_AuthUser(); authResult.StatusFlag = 1; authResult.Message = SCT_Constants.AuthFailure; for (int i = 0; i < userIds.Length; i++) { if (UserId_BAL.Equals(userIds[i]) && Pwd_BAL.Equals("password")) { authResult.StatusFlag = 0; authResult.Message = SCT_Constants.AuthSuccess; authResult.Name = userNames[i]; break; } } logger.DebugFormat("Authentication StatusFlag value : {0}", authResult.StatusFlag); logger.DebugFormat("Authentication Message value : {0}", authResult.Message); logger.Info("Method : authenticateUser_BAL Stop"); return authResult; } catch (Exception ex) { logger.Fatal("Exception At BAL - authenticateUser_BAL : " + ex.Message.ToString()); logger.Error("Method : authenticateUser_BAL Stop"); throw ex; } } // <summary> /// This Method validates the input parameter for the getPurchaseRequestDetails function /// </summary> /// <param name="PReqNo_BAL"></param> /// <returns></returns> /// <history> /// Hari haran 07/05/2012 created /// </history> public SCT_Emp searchEmployee_BAL(string Name_BAL, string MgrId_BAL, string Flag) { try { logger.Info("Method : searchEmployee_BAL Start"); int validateParam = searchParam(Name_BAL, MgrId_BAL, Flag); if ( validateParam == 1 ) { SCT_Emp sct_Details = new SCT_Emp(); sct_Details.SCT_headerDetails.StatusFlag = 21; sct_Details.SCT_headerDetails.StatusMsg = SCT_Constants.ParamNull; logger.Debug("Method searchEmployee_BAL : ErrorCode = " + sct_Details.SCT_headerDetails.StatusFlag.ToString()); logger.Debug("Method searchEmployee_BAL : ErrorMessage = " + sct_Details.SCT_headerDetails.StatusMsg); logger.Error("Method : searchEmployee_BAL Stop"); return sct_Details; } SCT_DAL search_DAL = new SCT_DAL(); return (search_DAL.searchEmployee_DAL(Name_BAL, MgrId_BAL, Flag)); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - searchEmployee_BAL : " + dbEx.Message.ToString()); logger.Error("Method : searchEmployee_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - searchEmployee_BAL : " + ex.Message.ToString()); logger.Error("Method : searchEmployee_BAL Stop"); throw ex; } } //*************************************************************************************************** int searchParam(string Name_BAL, string MgrId_BAL, string Flag) { logger.Info("Method : searchParam Start"); logger.DebugFormat("Input parameter Name : {0} ", Name_BAL); logger.DebugFormat("Input parameter ManagerId : {0} ", MgrId_BAL); logger.DebugFormat("Input parameter Flag : {0} ", Flag); if (string.IsNullOrEmpty(Name_BAL)) { logger.Error("Search Criteria :Name has Null reference"); logger.Info("Method : searchParam Stop"); return 1; } if(string.IsNullOrEmpty(MgrId_BAL)) { logger.Error("Manager ID :MgrID has Null reference"); logger.Info("Method : searchParam Stop"); return 1; } if (string.IsNullOrEmpty(Flag)) { logger.Error("Search Type (0 - Manager Search and 1 - Employee Search) :Flag has Null reference"); logger.Info("Method : searchParam Stop"); return 1; } logger.Info("Method : searchParam Stop"); return 0; } //*************************************************************************************************** public SCT_PA getPersonnelArea_BAL() { try { logger.Info("Method : getPersonnelArea_BAL Start"); SCT_DAL search_DAL = new SCT_DAL(); return (search_DAL.getPersonnelArea_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getPersonnelArea_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getPersonnelArea_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getPersonnelArea_BAL : " + ex.Message.ToString()); logger.Error("Method : getPersonnelArea_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_RChange getReasonForChange_BAL() { try { logger.Info("Method : getReasonForChange_BAL Start"); SCT_DAL search_DAL = new SCT_DAL(); return (search_DAL.getReasonForChange_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getReasonForChange_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getReasonForChange_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getReasonForChange_BAL : " + ex.Message.ToString()); logger.Error("Method : getReasonForChange_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_PSA getPersonnelSubArea_BAL() { try { logger.Info("Method : getPersonnelSubArea_BAL Start"); SCT_DAL search_DAL = new SCT_DAL(); return (search_DAL.getPersonnelSubArea_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getPersonnelSubArea_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getPersonnelSubArea_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getPersonnelSubArea_BAL : " + ex.Message.ToString()); logger.Error("Method : getPersonnelSubArea_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_ORGUnit getOrganizationalUnit_BAL() { try { logger.Info("Method : getOrganizationalUnit_BAL Start"); SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getOrganizationalUnit_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getOrganizationalUnit_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getOrganizationalUnit_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getOrganizationalUnit_BAL : " + ex.Message.ToString()); logger.Error("Method : getOrganizationalUnit_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_CC getCostCenter_BAL() { try { logger.Info("Method : getCostCenter_BAL Start"); SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getCostCenter_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getCostCenter_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getCostCenter_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getCostCenter_BAL : " + ex.Message.ToString()); logger.Error("Method : getCostCenter_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_BU getBusinessUnit_BAL() { try { logger.Info("Method : getBusinessUnit_BAL Start"); SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getBusinessUnit_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getBusinessUnit_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getBusinessUnit_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getBusinessUnit_BAL : " + ex.Message.ToString()); logger.Error("Method : getBusinessUnit_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_SBU getStrategicBusinessUnit_BAL() { try { logger.Info("Method : getStrategicBusinessUnit_BAL Start"); SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getStrategicBusinessUnit_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getStrategicBusinessUnit_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getStrategicBusinessUnit_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getStrategicBusinessUnit_BAL : " + ex.Message.ToString()); logger.Error("Method : getStrategicBusinessUnit_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_Horizontal getHorizontal_BAL() { try { logger.Info("Method : getHorizontal_BAL Start"); SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getHorizontal_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getHorizontal_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getHorizontal_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getHorizontal_BAL : " + ex.Message.ToString()); logger.Error("Method : getHorizontal_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_BLoc getBaseLocation_BAL() { try { logger.Info("Method : getBaseLocation_BAL Start"); SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getBaseLocation_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getBaseLocation_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getBaseLocation_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getBaseLocation_BAL : " + ex.Message.ToString()); logger.Error("Method : getBaseLocation_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_CDeploy getCenterOfDeployment_BAL() { try { logger.Info("Method : getCenterOfDeployment_BAL Start"); SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getCenterOfDeployment_DAL()); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getCenterOfDeployment_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getCenterOfDeployment_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getCenterOfDeployment_BAL : " + ex.Message.ToString()); logger.Error("Method : getCenterOfDeployment_BAL Stop"); throw ex; } } //*************************************************************************************************** public SCT_Entity getSCEmployeeDetails_BAL(string empId_BAL, string mgrId_BAL) { try { logger.Info("Method : getSCEmployeeDetails_BAL Start"); if (string.IsNullOrEmpty(empId_BAL) || string.IsNullOrEmpty(mgrId_BAL)) { SCT_Entity sct_Error = new SCT_Entity(); sct_Error.StatusFlag = 21; sct_Error.StatusMsg = SCT_Constants.IdNull; logger.Debug("Method getSCEmployeeDetails_BAL : ErrorCode = " + sct_Error.StatusFlag.ToString()); logger.Debug("Method getSCEmployeeDetails_BAL : ErrorMessage = " + sct_Error.StatusMsg); logger.Error("Method : getSCEmployeeDetails_BAL Stop"); return sct_Error; } SCT_DAL get_DAL = new SCT_DAL(); return (get_DAL.getSCEmployeeDetails_DAL(empId_BAL,mgrId_BAL)); } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - getSCEmployeeDetails_BAL : " + dbEx.Message.ToString()); logger.Error("Method : getSCEmployeeDetails_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - getSCEmployeeDetails_BAL : " + ex.Message.ToString()); logger.Error("Method : getSCEmployeeDetails_BAL Stop"); throw ex; } } /// <summary> /// This Method validates the input parameters for the updatePurchaseRequest function /// </summary> /// <param name="entry_BAL"></param> /// <returns></returns> /// <history> /// Hari haran 08/05/2012 created /// </history> public SCT_UpdateOutputEntity updateSCEmployeeDetails_BAL(SCT_UpdateInputEntity entry_BAL) { try { logger.Info("Method : updateSCEmployeeDetails_BAL Start"); logger.Debug("Method : updateSCEmployeeDetails_BAL RequestId value : " + entry_BAL.EmpNo.ToString()); SCT_UpdateOutputEntity errRes = new SCT_UpdateOutputEntity(); errRes.StatusFlag = 1; errRes.Message = SCT_Constants.Error; int validate_sctParamFlag = 0; validate_sctParamFlag = validate_sctParam(entry_BAL); logger.Debug("SCT Input parameter validation flag value(success = 0/failure = 1) : " + validate_sctParamFlag.ToString()); if (validate_sctParamFlag == 1) { logger.Debug("Error in input parameter values"); logger.Debug("ErrorCode = " + errRes.StatusFlag.ToString()); logger.Debug("ErrorMessage = " + errRes.Message); logger.Error("Method : updateSCEmployeeDetails_BAL Stop"); return errRes; } else { SCT_DAL updateSCT_DAL = new SCT_DAL(); return (updateSCT_DAL.updateSCEmployeeDetails_DAL(entry_BAL)); } } catch (SqlException dbEx) { logger.Fatal("Exception At BAL - updateSCEmployeeDetails_BAL : " + dbEx.Message.ToString()); logger.Error("Method : updateSCEmployeeDetails_BAL Stop"); throw dbEx; } catch (Exception ex) { logger.Fatal("Exception At BAL - updateSCEmployeeDetails_BAL : " + ex.Message.ToString()); logger.Error("Method : updateSCEmployeeDetails_BAL Stop"); throw ex; } } int validate_sctParam(SCT_UpdateInputEntity entry_BAL) { logger.Info("Method : validate_sctParam Start"); logger.DebugFormat("Input Parameter entry_BAL : EmpNo value = {0} and WEF = {1}", entry_BAL.EmpNo, entry_BAL.WEF); if (string.IsNullOrEmpty(entry_BAL.EmpNo)) { logger.Error("EmpNo has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.WEF)) { logger.Error("WEF has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentBU)) { logger.Error("CurrentBU has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewBU)) { logger.Error("NewBU has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentSBU)) { logger.Error("CurrentSBU has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewSBU)) { logger.Error("NewSBU has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentHorizontal)) { logger.Error("CurrentHorizontal has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewHorizontal)) { logger.Error("NewHorizontal has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentOrg)) { logger.Error("CurrentOrg has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewOrg)) { logger.Error("NewOrg has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentCost)) { logger.Error("CurrentCost has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewCost)) { logger.Error("NewCost has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentPersonal)) { logger.Error("CurrentPersonal has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewPersonal)) { logger.Error("NewPersonal has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentSubArea)) { logger.Error("CurrentSubArea has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewSubArea)) { logger.Error("NewSubArea has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentGrade)) { logger.Error("CurrentGrade has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewGrade)) { logger.Error("NewGrade has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.SubmittedBy)) { logger.Error("SubmittedBy has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrBLocation)) { logger.Error("CurrBLocation has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewBLocation)) { logger.Error("NewBLocation has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrBLocation)) { logger.Error("CurrBLocation has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrCDeploy)) { logger.Error("CurrCDeploy has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewCDeploy)) { logger.Error("NewCDeploy has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.CurrentSuperId)) { logger.Error("CurrentSuperId has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (string.IsNullOrEmpty(entry_BAL.NewSuperId)) { logger.Error("NewSuperId has NULL reference"); logger.Info("Method : validate_sctParam Stop"); return 1; } if (entry_BAL.CurrentSuperId.Equals(entry_BAL.NewSuperId)) { logger.Error("Current Supervisor Id is same as New Supervisor Id"); logger.Info("Method : validate_sctParam Stop"); return 1; } logger.Info("Method : validate_sctParam Stop"); return 0; } } }
using SuperSocket.SocketBase.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Threading.Tasks; using SuperSocket.SocketBase; namespace SS.Service { public abstract class WrapReceiveFilterFactory : IReceiveFilterFactory<InstanceRequestInfo>,ISettingLogger { public WrapReceiveFilterFactory() { } public abstract IReceiveFilter<InstanceRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint); public abstract void SettingLogger(ILoggerReceiveable IRLogger); } }
using System; namespace iCopy.SERVICES.Exceptions { public class ModelStateException : Exception { public string Key { get; set; } public ModelStateException(string Key, string Message) : base(Message) { this.Key = Key; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using System.IO; namespace COMP476Proj { public class MovementAIComponent2D { #region Attributes #region Arrival Attributes /// <summary> /// Radius in which to slow down when arriving /// </summary> private float slowDownRadius; /// <summary> /// Radius in which the player has arrived /// </summary> private float arrivalRadius; /// <summary> /// NOT CURRENTLY USED /// Speed under which a player can continue moving /// </summary> private float thresholdSpeed; /// <summary> /// NOT CURRENTLY USED /// Distance under which a player will perform a certain action /// </summary> private float thresholdDistance; /// <summary> /// Time in which to arrive at the target /// </summary> private float timeToTarget; #endregion #region Allign Attributes /// <summary> /// Difference in angle at which to slow down rotation /// </summary> private float slowDownRadiusRotation; /// <summary> /// Difference in angle at which the orientation is correct /// </summary> private float arrivalRadiusRotation; #endregion #region Rotation Attributes /// <summary> /// Angle in which the player sees another player /// </summary> private float perceptionAngle; /// <summary> /// Constant by which the change of perception angle relative to speed can be adjusted /// </summary> private float perceptionConstant; #endregion #region Target Attributes /// <summary> /// Desired position /// </summary> private Vector2 targetPosition; /// <summary> /// Desired velocity /// </summary> private Vector2 targetVelocity; /// <summary> /// Desired orientation /// </summary> private float targetOrientation; /// <summary> /// Desired rotation /// </summary> private float targetRotation; #endregion #region Random Number Attributes /// <summary> /// Random number /// </summary> #endregion #endregion #region Properties public float SlowDownRadius { get { return slowDownRadius; } } public float ArrivalRadius { get { return arrivalRadius; } } #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> public MovementAIComponent2D() { slowDownRadius = 75; arrivalRadius = 20; slowDownRadiusRotation = MathHelper.ToRadians(45); arrivalRadiusRotation = MathHelper.ToRadians(1); thresholdSpeed = 3; thresholdDistance = 2; perceptionAngle = MathHelper.ToRadians(45); perceptionConstant = 0.5f; timeToTarget = 0.1f; targetPosition = Vector2.Zero; targetVelocity = Vector2.Zero; } /// <summary> /// Basic Construtor /// </summary> /// <param name="thresholdSpeed">Speed under which a player can continue moving</param> /// <param name="thresholdDistance">Distance under which a player will perform a certain action</param> /// <param name="perceptionAngle">Angle in which the player sees another player</param> /// <param name="perceptionConstant">Constant by which the change of perception angle relative to speed can be adjusted</param> /// <param name="slowDownRadius">Radius in which to slow down when arriving</param> /// <param name="arrivalRadius">Radius in which the player has arrived</param> /// <param name="position">Target position</param> /// <param name="velocity">Target velocity</param> /// <param name="timeToTarget">Time in which to arrive at the target</param> public MovementAIComponent2D(float thresholdSpeed, float thresholdDistance, float perceptionAngle, float perceptionConstant, float slowDownRadius, float arrivalRadius, Vector2 position, Vector2 velocity, float timeToTarget) { this.thresholdSpeed = thresholdSpeed; this.thresholdDistance = thresholdDistance; this.perceptionAngle = perceptionAngle; this.perceptionConstant = perceptionConstant; this.slowDownRadius = slowDownRadius; this.arrivalRadius = arrivalRadius; slowDownRadiusRotation = MathHelper.ToRadians(50); arrivalRadiusRotation = MathHelper.ToRadians(10); targetPosition = position; targetVelocity = velocity; this.timeToTarget = timeToTarget; } #endregion #region Private Methods /// <summary> /// Generates a roughly normally distributed random number around 0 /// </summary> /// <returns>Approximately normally distributed number around 0</returns> private double normallyDistributedRandomNumber() { double a = 2 * Game1.random.NextDouble() - 1; double b = 2 * Game1.random.NextDouble() - 1; return a * b; } /// <summary> /// Kinematic arrive to the target /// Code is based on the code in the AI book /// </summary> /// <param name="physics">Physics component of the target</param> private void kinematicArrive(ref PhysicsComponent2D physics) { Vector2 velocity = targetPosition - physics.Position; if (velocity.Length() < arrivalRadius) { return; } velocity /= timeToTarget; if (velocity.Length() > physics.MaxVelocity) { if(velocity.LengthSquared() > 0) velocity.Normalize(); velocity *= physics.MaxVelocity; } physics.SetTargetValues(false, velocity, velocity, null); } /// <summary> /// Steering arrive to the target /// Code is based on the code in the AI book /// </summary> /// <param name="physics">Physics component of the target</param> private void steeringArrive(ref PhysicsComponent2D physics) { Vector2 direction = targetPosition - physics.Position; float distance = direction.Length(); float speed; if (distance < arrivalRadius) { return; } if (distance > slowDownRadius) { speed = physics.MaxVelocity; } else { speed = physics.MaxVelocity * distance / slowDownRadius; } Vector2 velocity = direction; if(velocity.LengthSquared() > 0) velocity.Normalize(); velocity *= speed; Vector2 targetAcceleration = velocity - physics.Velocity; targetAcceleration /= timeToTarget; if (targetAcceleration.Length() > physics.MaxAcceleration) { if (targetAcceleration.LengthSquared() > 0) targetAcceleration.Normalize(); targetAcceleration *= physics.MaxAcceleration; } physics.SetTargetValues(false, velocity, null, targetAcceleration); } /// <summary> /// Align to the desired orientation /// Code is based on the code in the AI book /// </summary> /// <param name="physics">Physics component of the target</param> private void align(ref PhysicsComponent2D physics) { float rotation = MathHelper.WrapAngle(targetOrientation - physics.Orientation); float rotationSize = Math.Abs(rotation); if (rotationSize < arrivalRadiusRotation) { physics.SetTargetValues(targetOrientation, -Math.Sign(physics.Rotation) * physics.MaxAngularAcceleration); return; } if (rotationSize > slowDownRadiusRotation) { targetRotation = physics.MaxRotation; } else { targetRotation = physics.MaxRotation * rotationSize / slowDownRadiusRotation; } targetRotation *= rotation / rotationSize; float angular = (targetRotation - physics.Rotation) / timeToTarget; float angularAcceleration = Math.Abs(angular); if (angularAcceleration > physics.MaxAngularAcceleration) { angular /= angularAcceleration; angular *= physics.MaxAngularAcceleration; } physics.SetTargetValues(targetOrientation, angular); } /// <summary> /// Checks to see whether or not the target is in a cone of perception /// Perception is based on angle and velocity (as velocity increases, /// cone size decreases) /// </summary> /// <param name="physics">Physics component of the target</param> /// <returns>Whether or not the target can be seen</returns> private bool isInPerceptionZone(ref PhysicsComponent2D physics) { Vector2 direction = targetPosition - physics.Position; if (direction.Length() == 0) { return true; } float angle = (float)Math.Atan2(direction.X, direction.Y); return (Math.Abs(angle - physics.Orientation) < (perceptionAngle / (perceptionConstant * physics.Velocity.Length() + 1))); } #endregion #region Public Methods /// <summary> /// Sets the position to target /// </summary> /// <param name="targetPosition">Desired position</param> public void SetTarget(Vector2 targetPosition, NPC flockingEnt = null) { this.targetPosition = targetPosition; } /// <summary> /// Sets the position to target /// </summary> /// <param name="targetPosition">Desired position</param> public void SetTargetVelocity(Vector2 targetVelocity) { this.targetVelocity = targetVelocity; } /// <summary> /// Seek movement /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Seek(ref PhysicsComponent2D physics) { // Seek normally physics.SetTargetValues(false, targetPosition - physics.Position, null, null); } /// <summary> /// Arrive movement /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Arrive(ref PhysicsComponent2D physics) { // Call appropriate behaviour if (physics.IsSteering) { steeringArrive(ref physics); } else { kinematicArrive(ref physics); } } /// <summary> /// Pursue movement /// Code is based on the code in the AI book /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Pursue(ref PhysicsComponent2D physics) { if (targetVelocity.Length() == 0) { Seek(ref physics); return; } float maxPrediction = 0.5f; float prediction; Vector2 direction = targetPosition - physics.Position; float distance = direction.Length(); float speed = physics.Velocity.Length(); if (speed <= distance / maxPrediction) { prediction = maxPrediction; } else { prediction = distance / speed; } Vector2 targetPos = targetPosition; targetPos += targetVelocity * prediction; physics.SetTargetValues(false, targetPos - physics.Position, null, null); } /// <summary> /// Flee movement /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Flee(ref PhysicsComponent2D physics) { // Flee normally Vector2 toFlee = (physics.Position - targetPosition); physics.SetTargetValues(false, toFlee, null, null); } /// <summary> /// Evade movement /// Code is based on the code in the AI book /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Evade(ref PhysicsComponent2D physics) { if (targetVelocity.Length() == 0) { Flee(ref physics); return; } float maxPrediction = 0.1f; float prediction; Vector2 direction = targetPosition - physics.Position; float distance = direction.Length(); float speed = physics.Velocity.Length(); if (speed <= distance / maxPrediction) { prediction = maxPrediction; } else { prediction = distance / speed; } Vector2 targetPos = targetPosition; targetPos += targetVelocity * prediction; // Pursue normally targetPos = (targetPos - physics.Position); physics.SetTargetValues(false, targetPos, null, null); } /// <summary> /// Wander movement /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Wander(ref PhysicsComponent2D physics) { Vector2 direction; float angle; if (physics.Direction.Length() == 0) { float x, y; do { x = Game1.random.Next(-10, 11); } while (x == 0); do { y = Game1.random.Next(-10, 11); } while (y == 0); direction = new Vector2(x, y); if (direction.LengthSquared() > 0) direction.Normalize(); } else { do { angle = MathHelper.ToRadians(5 * (float)normallyDistributedRandomNumber()); Vector2 previousDirection = physics.Direction; direction.X = (float)Math.Cos(angle) * previousDirection.X - (float)Math.Sin(angle) * previousDirection.Y; direction.Y = (float)Math.Sin(angle) * previousDirection.X + (float)Math.Cos(angle) * previousDirection.Y; if (direction.LengthSquared() > 0) direction.Normalize(); } while (direction.Length() == 0); } // Seek normally physics.SetTargetValues(false, direction, null, null); } /// <summary> /// Stop movement /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Stop(ref PhysicsComponent2D physics) { physics.SetTargetValues(true, null, null, null); } /// <summary> /// Look where you're going, delegated to allign /// Code is based on the code in the AI book /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Look(ref PhysicsComponent2D physics) { if (physics.Velocity.Length() == 0) { return; } targetOrientation = (float)Math.Atan2(physics.Velocity.X, physics.Velocity.Y); align(ref physics); } /// <summary> /// Look at a point, delegated to allign /// Code is based on the code in the AI book /// </summary> /// <param name="physics">The physics component of the thinking character</param> public void Face(ref PhysicsComponent2D physics) { Vector2 direction = targetPosition - physics.Position; if (direction.Length() == 0) { return; } targetOrientation = (float)Math.Atan2(direction.X, direction.Y); align(ref physics); } /// <summary> /// Look away from a point, delegated to allign /// Code is based on the code in the AI book /// </summary> public void FaceAway(ref PhysicsComponent2D physics) { Vector2 direction = physics.Position - targetPosition; if (direction.Length() == 0) { return; } targetOrientation = (float)Math.Atan2(direction.X, direction.Y); align(ref physics); } #endregion } }
using ETModel; namespace ETHotfix { public static class ActorHelp { public static void SendActor(long actorId, IActorMessage message) { if (actorId == 0) { return; } ActorMessageSender actorSender = Game.Scene.GetComponent<ActorMessageSenderComponent>().Get(actorId); actorSender.Send(message); } } }
using System; using System.Runtime.CompilerServices; namespace Roaring { public partial class RoaringBitmap { public IRoaringBitmap Remove(uint value) { var bitmap = Clone(); bitmap.IRemove(value); return bitmap; } public void IRemove(uint value) { ushort key, cValue; Container.SplitValue(value, out key, out cValue); ref var containerInfo = ref GetOrCreateContainer(key, 1); switch (containerInfo.Type) { case ContainerType.Array: if (_hasDirectAccess) { ref var arrayBuffer = ref _arrayStore.GetContainer(containerInfo.Index); IRemoveArray(ref containerInfo, ref arrayBuffer, cValue); } else { var arrayBuffer = CreateArrayBuffer(); _arrayStore.ReadContainer(containerInfo.Index, arrayBuffer, containerInfo.Cardinality); IRemoveArray(ref containerInfo, ref arrayBuffer, cValue); _arrayStore.WriteContainer(containerInfo.Index, arrayBuffer, containerInfo.Cardinality, true); } //Debug.Assert(_arrayStore.GetContainer(cIndex)?.Distinct().Count() == _arrayStore.GetContainer(cIndex)?.Count()); break; case ContainerType.Bitmap: var bitmapBuffer = _bitmapStore.GetContainer(containerInfo.Index); System.Diagnostics.Debug.Assert(bitmapBuffer.Length == BitmapContainer.ArraySize); IRemoveBitmap(ref containerInfo, bitmapBuffer, cValue); break; } } public IRoaringBitmap Remove(params uint[] values) { var bitmap = Clone(); bitmap.IRemove(values); return bitmap; } public void IRemove(params uint[] values) { for (int i = 0; i < values.Length; i++) IRemove(values[i]); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void IRemoveArray(ref RoaringContainer container, ref ushort[] data, ushort value) { int loc = ArrayContainer.BinarySearchArray(data, 0, (int)container.Cardinality, value); if (loc < 0) return; //Does not exist if (loc != data.Length - 1) Buffer.BlockCopy(data, (loc + 1) * sizeof(ushort), data, loc * sizeof(ushort), (data.Length - loc - 1) * sizeof(ushort)); container.Cardinality--; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void IRemoveBitmap(ref RoaringContainer container, ulong[] data, ushort value) { int index = BitmapContainer.GetIndex(value); int length = data.Length; ulong before = data[index]; ulong after = before & ~(1UL << value); if (before != after) { data[index] = after; container.Cardinality--; if (container.Cardinality < ArrayContainer.MaxArraySize) { var buffer = CreateArrayBuffer(); ConvertBitmapToArray(data, buffer); var cIndex = _arrayStore.CreateContainer(container.Cardinality); _arrayStore.WriteContainer(cIndex, buffer, container.Cardinality, true); _bitmapStore.DeleteContainer(container.Index); container.Index = cIndex; container.Type = ContainerType.Array; } } } } }
namespace _3.MaximumElement { using System; using System.Collections.Generic; public class Startup { public static void Main(string[] args) { int quantity = int.Parse(Console.ReadLine()); Stack<int> stack = new Stack<int>(); Stack<int> maxNumberStack = new Stack<int>(); int maxNumber = int.MinValue; for (int i = 0; i < quantity; i++) { string[] input = Console.ReadLine().Split(' '); string command = input[0]; if(command == "1") { int number = int.Parse(input[1]); if(number > maxNumber) { maxNumber = number; maxNumberStack.Push(number); } stack.Push(number); } else if(command == "2") { int popNumber = stack.Pop(); int peekMaxNumber = maxNumberStack.Peek(); if(popNumber == peekMaxNumber) { maxNumberStack.Pop(); if(maxNumberStack.Count == 0) { maxNumber = int.MinValue; } else { maxNumber = maxNumberStack.Peek(); } } } else if(command == "3") { Console.WriteLine($"{maxNumberStack.Peek()}"); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Security.Cryptography; using System.Text; namespace Cryptography3DES { public partial class Decryption : System.Web.UI.Page { SqlCommand cmd = new SqlCommand(); SqlConnection con = new SqlConnection(); DataOperation db = new DataOperation(); protected void Page_Load(object sender, EventArgs e) { if (Session["Username1"] != null) { lblmsg.Text = "Welcome " + Session["Username1"].ToString() + " you have loged-in successfully"; // lblmsg.Text = "Welcome " + (string)(Session["Username"]) + " you have loged-in successfully"; con.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; con.Open(); string query = @"SELECT [ID] ,[Message] FROM [dbo].[DES1]"; GridView1.DataSource = db.GetDatatable(query); GridView1.DataBind(); } else { Response.Redirect("Portal Login.aspx"); } } protected void Button2_Click(object sender, EventArgs e) { string s = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; SqlConnection con = new SqlConnection(s); SqlCommand cmd = new SqlCommand("select * from DES1 where ID='" + TextBox4.Text + "'", con); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ID", TextBox4.Text); cmd.Connection = con; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { TextBox2.Text = dr["Message"].ToString(); } dr.Close(); con.Close(); } protected void Button3_Click(object sender, EventArgs e) { string key = "@@123"; MD5CryptoServiceProvider mdHash = new MD5CryptoServiceProvider(); byte[] keyArr = mdHash.ComputeHash(Encoding.UTF8.GetBytes(key)); mdHash.Clear(); byte[] cipherTxt = Convert.FromBase64String(TextBox2.Text); TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); des.Key = keyArr; des.Mode = CipherMode.ECB; des.Padding = PaddingMode.PKCS7; ICryptoTransform iTransform = des.CreateDecryptor(); byte[] res = iTransform.TransformFinalBlock(cipherTxt, 0, cipherTxt.Length); TextBox3.Text = Encoding.UTF8.GetString(res); } protected void Button4_Click(object sender, EventArgs e) { TextBox2.Text = string.Empty; TextBox3.Text = string.Empty; TextBox4.Text = string.Empty; } protected void Button5_Click(object sender, EventArgs e) { Session.Remove("Username1"); //Session.RemoveAll(); Response.Redirect("~/Portal Login.aspx"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; using TMPro; public class Video_Poker_Manager : MonoBehaviour { public Card_Manager thisdeck; public Player_Hand PHand; public Betting_Manager BM; public AudioSource MoneySound; public TextMeshProUGUI Winner_Text; public TextMeshProUGUI WinningMoneyText; int[] temphand = new int[5]; int[] TempHandSuite = new int[5]; bool jacksorbetter = false; bool threeofkind = false; bool fourofkind = false; bool FullHouse = false; bool RoyalFlush = false; bool StraightFlush = false; bool flush = false; bool straight = false; bool two_pair = false; public void Awake() { thisdeck = GameObject.Find("Card Manager").GetComponent<Card_Manager>(); PHand = GameObject.Find("Card Manager").GetComponent<Player_Hand>(); MoneySound = GetComponent<AudioSource>(); Winner_Text = GameObject.Find("Winning Text").GetComponent<TextMeshProUGUI>(); Winner_Text.enabled = false; BM = GetComponent<Betting_Manager>(); WinningMoneyText = GameObject.Find("Money Winning Text").GetComponent<TextMeshProUGUI>(); WinningMoneyText.enabled = false; } //Check each hand and set the flags public void CheckWinnings() { //Check each hand and set the flags ArraySort(); two_pair = TwoPairCheck(); MultipleCheck(); flush = FlushCheck(); straight = StraightCheck(); StraightFlush = StraightFlushCheck(); RoyalFlush = RoyalFlushCheck(); //Print out the winning information Outcome(); //Reset all flags so there ready for the next hand jacksorbetter = false; threeofkind = false; fourofkind = false; FullHouse = false; RoyalFlush = false; StraightFlush = false; flush = false; straight = false; two_pair = false; } public void ArraySort() { for (int i = 0; i < 5; i++) { // Make the Aces = 13 so its easier for the StraightCheck() functions if (PHand.hand[i].getValue() == 0) { temphand[i] = 13; TempHandSuite[i] = PHand.hand[i].GetSuite(); } else { temphand[i] = PHand.hand[i].getValue(); TempHandSuite[i] = PHand.hand[i].GetSuite(); } } Array.Sort(temphand); } public bool TwoPairCheck() { int paircount = 0; int tempcount = 1; for (int i = 0; i < temphand.Length - 1; i++) { if (temphand[i] == temphand[i + 1]) { tempcount++; if (tempcount == 2) { paircount++; } } tempcount = 1; } if (paircount == 2) { return true; } return false; } public void MultipleCheck() { int highestcount = 1; int highestnum = 0; int lowestcount = 1; int tempcount = 1; // Go through all the cards and get the Highest and lowest amount of the same cards // The max should be 3, while the lowest should be 2 indicating a full house for(int i = 0; i < temphand.Length -1 ; i++) { if (temphand[i] == temphand[i + 1]) { tempcount++; } else { tempcount = 1; } if (tempcount > highestcount) { highestcount = tempcount; highestnum = temphand[i]; } else if(tempcount > lowestcount) { lowestcount = tempcount; } } if (highestcount == 4) { fourofkind = true; } if (highestcount >= 3) { threeofkind = true; if (lowestcount == 2) { FullHouse = true; } } if(highestcount >= 2 && (highestnum >= 10 || highestnum == 0)) { jacksorbetter = true; } } //Check to see if the current spot in array + 1 is = to next spot in the array //Checks for consecutive numbers public bool StraightCheck() { for (int i = 0; i < temphand.Length - 1; i++) { if(temphand[i] + 1 != temphand[i + 1]) { return false; } } return true; } //Check to make sure array is full of same numbers indicating flush public bool FlushCheck() { int MainSuite = TempHandSuite[0]; for (int i = 1; i < TempHandSuite.Length; i++) { if(TempHandSuite[i] != MainSuite) { return false; } } return true; } public bool StraightFlushCheck() { return flush && straight; } public bool RoyalFlushCheck() { if (flush && straight && temphand[0] == 9) { return true; } return false; } // Writes out winning text for 2 seconds private IEnumerator Show_Winning_Message(string WinningMessage, string MoneyWon) { Winner_Text.SetText(WinningMessage); WinningMoneyText.SetText("$" + MoneyWon); Winner_Text.enabled = true; WinningMoneyText.enabled = true; yield return new WaitForSeconds(2.0f); Winner_Text.enabled = false; WinningMoneyText.enabled = false; } //Shows winning amount and message based on highest flag set public void Outcome() { float MoneyWon = 0; if (RoyalFlush) { MoneySound.Play(); MoneyWon = BM.WinningAmount(800f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Royal Flush!", MoneyWon.ToString("F2"))); } else if (StraightFlush) { MoneySound.Play(); MoneyWon = BM.WinningAmount(50f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Straight Flush!", MoneyWon.ToString("F2"))); } else if (fourofkind) { MoneySound.Play(); MoneyWon = BM.WinningAmount(25f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Four Of A Kind!", MoneyWon.ToString("F2"))); } else if (FullHouse) { MoneySound.Play(); MoneyWon = BM.WinningAmount(9f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Fullhouse!", MoneyWon.ToString("F2"))); } else if (flush) { MoneySound.Play(); MoneyWon = BM.WinningAmount(6f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Flush!", MoneyWon.ToString("F2"))); } else if (straight) { MoneySound.Play(); MoneyWon = BM.WinningAmount(4f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Straight!", MoneyWon.ToString("F2"))); } else if (threeofkind) { MoneySound.Play(); MoneyWon = BM.WinningAmount(3f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Three Of A Kind!", MoneyWon.ToString("F2"))); } else if (two_pair) { MoneySound.Play(); MoneyWon = BM.WinningAmount(2f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Two Pair!", MoneyWon.ToString("F2"))); } else if (jacksorbetter) { MoneySound.Play(); MoneyWon = BM.WinningAmount(1f); BM.UpdateMoney(MoneyWon); StartCoroutine(Show_Winning_Message("Pair of Jacks Or Better!", MoneyWon.ToString("F2"))); } else { MoneyWon = 0f; StartCoroutine(Show_Winning_Message("Lost :(", MoneyWon.ToString("F2"))); BM.PlayerMoney -= BM.MainBet; BM.PlayerMoneyText.text = "$" + BM.PlayerMoney.ToString("F2"); } } public void ExitGame() { #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif } }
using Microsoft.Owin.Security.OAuth; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using WebApiDAL.DataAccess; using WebApiDAL.Entity; using WebApiDAL.ServiceManager; namespace WebApi { public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider { private IAccount Acc; public MyAuthorizationServerProvider() { Acc = new AccountRepository(); } public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); // } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); Login lgn = new Login(); lgn.EmailId = context.UserName; lgn.Password = context.Password; var ErrMsg = ""; var usr = Acc.Login(lgn, out ErrMsg); if (usr != null) { identity.AddClaim(new Claim(ClaimTypes.Role, usr.Tbl_UserRole.Role)); identity.AddClaim(new Claim("email", usr.UserEmail)); identity.AddClaim(new Claim("PhoneNumber", usr.PhoneNumber)); identity.AddClaim(new Claim("UserID", usr.UserID.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, usr.UserID.ToString())); context.Validated(identity); } else { context.SetError("invalid_grant", "Provided Email and password is incorrect"); return; } //var identity = new ClaimsIdentity(context.Options.AuthenticationType); //Login lgn = new Login(); //lgn.EmailId = context.UserName; //lgn.Password = context.Password; //var ErrMsg = ""; //var usr = Acc.Login(lgn, out ErrMsg); //if (usr != null) //{ // identity.AddClaim(new Claim(ClaimTypes.Role, usr.Tbl_UserRole.Role)); // identity.AddClaim(new Claim("email", usr.UserEmail)); // identity.AddClaim(new Claim("PhoneNumber", usr.PhoneNumber)); // identity.AddClaim(new Claim("UserID", usr.UserID.ToString())); // identity.AddClaim(new Claim(ClaimTypes.Name, usr.PhoneNumber)); // context.Validated(identity); //} //else //{ // context.SetError("invalid_grant", "Provided Email and password is incorrect"); // return; //} } } }
using UnityEngine; using System.Collections; public class NetSegment : PhysicsObject { // Use this for initialization float m_size; public NetController m_parentNet; protected override void Start() { m_size = GetComponent<BoxCollider2D>().size.x; } // Update is called once per frame void Update() { } protected override void FixedUpdate() { if (rigidbody2D.velocity.y > 0) { rigidbody2D.AddForce(new Vector2(0, -rigidbody2D.velocity.y)); } } public Vector2 GetLeftPoint() { m_size = GetComponent<BoxCollider2D>().size.x; float sizeX = m_size * Mathf.Cos(transform.rotation.eulerAngles.z * Mathf.Deg2Rad) / 2; float sizeY = m_size * Mathf.Sin(transform.rotation.eulerAngles.z * Mathf.Deg2Rad) / 2; Vector3 max = new Vector3(sizeX, sizeY); return transform.position - max; } public Vector2 GetRightPoint() { m_size = GetComponent<BoxCollider2D>().size.x; float sizeX = m_size * Mathf.Cos(transform.rotation.eulerAngles.z * Mathf.Deg2Rad) / 2; float sizeY = m_size * Mathf.Sin(transform.rotation.eulerAngles.z * Mathf.Deg2Rad) / 2; Vector3 max = new Vector3(sizeX, sizeY); return transform.position + max; } public override int DestructionPrice { get { return 0; } } protected override void OnDestroy() { Destroy(m_parentNet.gameObject); base.OnDestroy(); } protected override void OnCollisionEnter2D(Collision2D collision) { m_parentNet.AddTarget(collision.collider.gameObject); } protected override void OnCollisionExit2D(Collision2D collision) { m_parentNet.RemoveTarget(collision.collider.gameObject); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QualificationExaming.Services { using Services; using Dapper; using IServices; using MySql.Data.MySqlClient; using System.Configuration; using Entity; public class CollectionService : ICollectionService { /// <summary> /// 获取收藏题目 /// </summary> /// <param name="openID"></param> /// <returns></returns> public List<Question> GetCollectionQuestions(string openID) { using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString)) { var questionlist = conn.Query<Question>("select q.* from question q join collection c on q.QuestionID=c.QuestionID join `user` u on u.UserID=c.UserID where u.OpenID='" + openID + "'", null); if (questionlist != null) { return questionlist.ToList(); } return null; } } /// <summary> /// 根据用户openID和题目ID删除收藏 /// </summary> /// <param name="erroid"></param> /// <returns></returns> public int DeleteCollection(int questionID, string openID) { using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString)) { DynamicParameters parameters = new DynamicParameters(); parameters.Add("p_questionID", questionID); parameters.Add("p_openID", openID); var result = conn.Execute("proc_DeleteCollection", parameters, commandType: System.Data.CommandType.StoredProcedure); return result; } } /// <summary> /// 添加收藏 /// </summary> /// <param name="e"></param> /// <returns></returns> /// 用户id /// 题目id public int AddCollection(string openID, int questionID) { using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString)) { DynamicParameters parameters = new DynamicParameters(); parameters.Add("p_openID", openID); parameters.Add("p_questionID", questionID); var result = conn.Execute("proc_AddCollection", parameters, commandType: System.Data.CommandType.StoredProcedure); return result; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Net.Http; using System.Net.Http.Headers; namespace SweepFile.Models { public class CallFundcode { public string fundcode {get;set;} public string date_off {get;set;} } class httpAPI { /* static HttpClient client = new HttpClient(); static async Task<CallFundcode> GetProductAsync() { CallFundcode product = null; HttpResponseMessage response = await client.GetAsync("http://api.hbc.in.th/api/fund/"); if (response.IsSuccessStatusCode) { product = await response.Content.ReadAsAsync<CallFundcode>(); } return product; } static void Main() { RunAsync().GetAwaiter().GetResult(); } static async Task RunAsync() { HttpClient client = new HttpClient(); // Update port # in the following line. client.BaseAddress = new Uri("http://api.hbc.in.th/api/fund/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); try { // Create a new product CallFundcode product = new CallFundcode { fundcode = "Gizmo", date_off = "Widgets" }; // Get the product HttpResponseMessage response = await client.GetAsync("http://api.hbc.in.th/api/fund/"); if (response.IsSuccessStatusCode) { product = await response.Content.ReadAsAsync<CallFundcode>(); } } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); }*/ } }
namespace ServiceBase.Mvc.Theming { /// <summary> /// Theme information for current request. /// </summary> public class ThemeInfoResult { /// <summary> /// Theme name for current request. /// </summary> public string ThemeName { get; set; } } }
using System; using UnityEngine; namespace RO { public class UIPlayTweenExtension : UIPlayTween { public bool IsInit; public void Play(bool forward) { if (!this.IsInit) { GameObject gameObject = (!(this.tweenTarget == null)) ? this.tweenTarget : base.get_gameObject(); UITweener[] array = (!this.includeChildren) ? gameObject.GetComponents<UITweener>() : gameObject.GetComponentsInChildren<UITweener>(); int num = (!forward) ? 0 : 1; UITweener[] array2 = array; for (int i = 0; i < array2.Length; i++) { UITweener uITweener = array2[i]; uITweener.Sample((float)num, true); } } else { base.Play(forward); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; using TMPro; public class Crossword : MonoBehaviour { public TMP_InputField searchInput; private bool hasLoaded = false; public GameObject originalText; public TextMeshProUGUI extraWords; public TextMeshProUGUI infoText; private TextMeshProUGUI[][] texts; public bool useWords; public int size; public void CreateCrossword() { string text = searchInput.text; Verse v = Bible.GetVerseFromReference(text); if (useWords) { Verse ver = new Verse(); ver.verse = text; v = ver; } if (v != null) { //remove punctuation string verse = v.verse.ToLower(); string newVerse = ""; string allowable = " qwertyuiopasdfghjklzxcvbnm"; for (int i = 0; i < verse.Length; i++) { if (allowable.IndexOf(verse[i].ToString()) == -1) { //punctuaction } else { newVerse += verse[i].ToString(); } } if (!hasLoaded) { hasLoaded = true; LoadInBoard(); } string[] words = newVerse.Split(' '); GenerateCrossword(words); } } public void LoadInBoard() { texts = new TextMeshProUGUI[size][]; float offset = (size * 1.35f); for (int i = 0; i < size; i++) { texts[i] = new TextMeshProUGUI[size]; for (int k = 0; k < size; k++) { GameObject g = Instantiate(originalText, originalText.GetComponent<RectTransform>().anchoredPosition, Quaternion.identity); g.transform.SetParent(originalText.transform.parent, false); g.transform.localScale = Vector3.one; texts[i][k] = g.GetComponent<TextMeshProUGUI>(); Vector3 tempPos = g.GetComponent<RectTransform>().anchoredPosition; tempPos.x += i * offset; tempPos.y -= k * offset; g.GetComponent<RectTransform>().anchoredPosition = tempPos; } } Destroy(originalText); } public void ToggleUseWords() { useWords = !useWords; Refresh(); } public void Refresh() { if (useWords) { infoText.text = "Generate a crossword by typing words separated by spaces. "; } else { infoText.text = "Generate a crossword by a verse. ex: Esther 8:9"; } } public void Setup() { Refresh(); if (searchInput.text == "") { if (!useWords) { searchInput.text = "Esther 8:9"; CreateCrossword(); } } } public void GenerateCrossword(string[] words) { //takes in an array of words //and outputs a crossword in this format //string[] //"-h--" //"-a--" //"plan" //"-f--" //sort words longest to shortest Array.Sort(words, (y, x) => x.Length.CompareTo(y.Length)); string[] wordsBackup = (string[]) words.Clone(); //score tracking CrosswordClass best = new CrosswordClass(); int bestScore = -10000; string[] bestWords = null; //k decides how many crosswords to generate and compare scores. The crossword with the highest score is displayed for (int k = 0; k < 10; k++) { //we have words, now generate crossword CrosswordClass cross = new CrosswordClass(); cross.Init(size); words = (string[]) wordsBackup.Clone(); //add first word if (CoinFlip()) { cross.AddWord((int)(size / 2), (int)(size / 2 - words[0].Length / 2), words[0], true); } else { cross.AddWord((int)(size / 2 - words[0].Length / 2), (int)(size / 2), words[0], false); } words = words.Except(new string[]{words[0]}).ToArray(); //now go through each word and add it to an open spot, 3 times for (int count = 0; count < 5; count++) { for (int i = 0; i < words.Length; i++) { Location loc = cross.FindSpotForWord(words[i]); if (loc != null) { if (!cross.AddWord(loc.x, loc.y, words[i], loc.isVertical)) { print(words[i] + " could not fit into the crossword"); } else { //sucess words = words.Except(new string[]{words[i]}).ToArray(); i--; } } } } //score this crossword int score = 0; score -= words.Length * 250; //extra words decrease score score += ScoreCrossword(cross); if (score > bestScore) { bestScore = score; best = cross; bestWords = words; } } //finalize by displaying results for (int i = 0; i < size; i++) { for (int k = 0; k < size; k++) { texts[i][k].text = " "; if (best.data[i][k] != '-') texts[i][k].text = best.data[i][k].ToString().ToUpper(); } } //and display extra words string extra = ""; for (int i = 0; i < bestWords.Length; i++) { extra += bestWords[i] + "\n"; } extraWords.text = extra; if (extra == "") extraWords.text = "no extra words"; //PrintCrossword(cross); } public void PrintCrossword(CrosswordClass c) { string s = ""; for (int i = 0; i < c.data.Length; i++) { for (int k = 0; k < c.data.Length; k++) { s += c.data[i][k]; } s += "\n"; } print(s); } public bool CoinFlip() { bool b = UnityEngine.Random.Range(0, 2) == 1; //print(b); return b; } public int ScoreCrossword(CrosswordClass c) { int score = 0; int minX = size + 1; int minY = size + 1; int maxX = -1; int maxY = -1; for (int i = 1; i < c.data.Length - 1; i++) { for (int k = 1; k < c.data.Length - 1; k++) { //check for these patterns // O OOO // OOO O O // O OOO //the more there are, the better the score if (c.data[i - 1][k] != '-' && c.data[i + 1][k] != '-') { if (c.data[i][k - 1] != '-' && c.data[i][k + 1] != '-') { //one found, first one detailed above score += 50; if (c.data[i - 1][k - 1] != '-' && c.data[i + 1][k + 1] != '-') { if (c.data[i + 1][k - 1] != '-' && c.data[i - 1][k + 1] != '-') { //one found, second one score += 150; } } } } } } //calculate max x and y and min x and y for (int i = 0; i < c.data.Length; i++) { for (int k = 0; k < c.data.Length; k++) { if (c.data[i][k] != '-') { if (i > maxX) maxX = i; if (i < minX) minX = i; if (k > maxY) maxY = k; if (k < minY) minY = k; } } } int sizeX = maxX - minX; int sizeY = maxY - minY; //the ideal size ratio is 1:1 score += (int)(Mathf.Min(((float)sizeX / sizeY), ((float)sizeY / sizeX)) * 1000); return score; } } public class CrosswordClass { public string[] data; public void Init(int size) { //a size 2 would make data equal ["--", "--"] data = new string[size]; string s = ""; int i = 0; for (i = 0; i < size; i++) { s += "-"; } for (i = 0; i < size; i++) { data[i] = s; } } public bool AddWord(int x, int y, string word, bool isVertical) { //adds a word but stops and returns false if it does not fit //first make a buffer of the data string[] buffer = new string[data.Length]; for (int i = 0; i < data.Length; i++) { string s = ""; for (int k = 0; k < data.Length; k++) { s += data[i][k]; } buffer[i] = s; } for (int i = 0; i < word.Length; i++) { if (isVertical) { if (OutOfBounds(y + i)) return false; ReplaceLetter(buffer, x, y + i, word[i]); } else { if (OutOfBounds(x + i)) return false; ReplaceLetter(buffer, x + i, y, word[i]); } } data = buffer; return true; } public void ReplaceLetter(string[] localData, int x, int y, char letter) { //given data, a position, and a letter, it replaces that letter localData[x] = localData[x].Substring(0, y) + letter.ToString() + localData[x].Substring(y + 1); } public bool OutOfBounds(int i) { //input a number, this returns true if it is out of the size of the crossword. return i < 0 || i >= data.Length; } public Location FindSpotForWord(string word) { //given a word, returns a location object that represents a spot that the word can go into, or null if there are none //algorithm: //find letters on the board that match letters in the word //find valid intersections of these letters //predict where it would go //check each letter to make sure it is empty/already the right letter //select a random one from the list of ones that work and return it //step 1: find letters on the board that match letters in the word List<Location>[] common = new List<Location>[word.Length]; //this is an array of location lists //a list for each letter //each location in a list is an occurance of that letter. for (int i = 0; i < word.Length; i++) { common[i] = new List<Location>(); //each letter for (int k = 0; k < data.Length; k++) { for (int j = 0; j < data.Length; j++) { //each position: check if it matches letter and add it to common if (word[i] == data[k][j]) { Location loc = new Location(); loc.x = k; loc.y = j; common[i].Add(loc); } } } } //step 2: for each possible intersection, determine if it works List<Location> possible = new List<Location>(); for (int i = 0; i < common.Length; i++) { //each letter of the original word for (int k = 0; k < common[i].Count; k++) { //each intersection bool worksVertical = true; //innocent until proven guilty bool worksHorizontal = true; char c; for (int j = 0; j < word.Length; j++) { //each letter of the word as we attempt to fill the word in int offset = j - i; //how far from the intersection each letter should be //each letter of the word if (worksVertical) { if (!OutOfBounds(common[i][k].y + offset)) { c = data[common[i][k].x][common[i][k].y + offset]; //check if this works (vertically) if (c != '-' && c != word[j]) { worksVertical = false; } //now check if the spots right and left to each spot are empty if (offset != 0 && c != word[j]) //make sure not to check for this at the intersection { if (!OutOfBounds(common[i][k].x - 1)) { c = data[common[i][k].x - 1][common[i][k].y + offset]; //check if this works (left of vertical spot) if (c != '-') { worksVertical = false; } } if (!OutOfBounds(common[i][k].x + 1)) { c = data[common[i][k].x + 1][common[i][k].y + offset]; //check if this works (right of vertical spot) if (c != '-') { worksVertical = false; } } } } else { worksVertical = false; } } if (worksHorizontal) { if (!OutOfBounds(common[i][k].x + offset)) { c = data[common[i][k].x + offset][common[i][k].y]; //check if this works (left) if (c != '-' && c != word[j]) { worksHorizontal = false; } //now check if the spots above and below to each spot are empty if (offset != 0 && c != word[j]) { if (!OutOfBounds(common[i][k].y - 1)) { c = data[common[i][k].x + offset][common[i][k].y - 1]; //check if this works (left of vertical spot) if (c != '-') { worksHorizontal = false; } } if (!OutOfBounds(common[i][k].y + 1)) { c = data[common[i][k].x + offset][common[i][k].y + 1]; //check if this works (right of vertical spot) if (c != '-') { worksHorizontal = false; } } } } else { worksHorizontal = false; } } } //now check the spots to the left and right of a horizontal word //above and below a vertical word if (worksHorizontal) { if (!OutOfBounds(common[i][k].x - i - 1)) { c = data[common[i][k].x - i - 1][common[i][k].y]; if (c != '-') { worksHorizontal = false; } } if (!OutOfBounds(common[i][k].x - i + word.Length)) { c = data[common[i][k].x - i + word.Length][common[i][k].y]; if (c != '-') { worksHorizontal = false; } } } if (worksVertical) { if (!OutOfBounds(common[i][k].y - i - 1)) { c = data[common[i][k].x][common[i][k].y - i - 1]; if (c != '-') { worksVertical = false; } } if (!OutOfBounds(common[i][k].y - i + word.Length)) { c = data[common[i][k].x][common[i][k].y - i + word.Length]; if (c != '-') { worksVertical = false; } } } //we have finished calculations for this intersection //if the intersection worked either horizontally or vertically, then note it if (worksHorizontal) { Location l = new Location(); l.x = common[i][k].x - i; l.y = common[i][k].y; l.isVertical = false; possible.Add(l); } if (worksVertical) { Location l = new Location(); l.x = common[i][k].x; l.y = common[i][k].y - i; //minus i so the word ends up with matching letters at the intersection l.isVertical = true; possible.Add(l); } } } //step 3: select a random intersection that works and return it int r = UnityEngine.Random.Range(0, possible.Count); if (possible.Count == 0) return null; return possible[r]; } } public class Location { public int x; public int y; public bool isVertical; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using dnlib.DotNet; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NLog; using SharpILMixins.Processor.Utils; using SharpILMixins.Processor.Workspace.Generator; using SharpILMixins.Processor.Workspace.Processor.Actions.Impl; using SharpILMixins.Processor.Workspace.Processor.Actions.Impl.Inject.Impl; using SharpILMixins.Processor.Workspace.Processor.Scaffolding; using SharpILMixins.Processor.Workspace.Processor.Scaffolding.Redirects; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpILMixins.Processor.Workspace.Processor { public class MixinProcessor { public MixinProcessor(MixinWorkspace workspace) { Workspace = workspace; CopyScaffoldingHandler = new CopyScaffoldingHandler(workspace); } public Logger Logger { get; } = LoggerUtils.LogFactory.GetLogger(nameof(MixinProcessor)); public MixinWorkspace Workspace { get; } public CopyScaffoldingHandler CopyScaffoldingHandler { get; set; } public RedirectManager RedirectManager => CopyScaffoldingHandler.RedirectManager; public void Process(List<MixinRelation> mixinRelations, MixinTargetModule targetModule) { DumpRequestedTargets(mixinRelations, Workspace.Settings.DumpTargets); if (Workspace.Settings.IsGenerateOnly) { GenerateHelperCode(mixinRelations, targetModule); return; } CopyScaffoldingHandler.CopyNonMixinClasses(Workspace.MixinModule, targetModule.ModuleDef); foreach (var mixinRelation in mixinRelations) { Logger.Info($"Starting to process mixin {mixinRelation.MixinType.Name}"); if (mixinRelation.IsAccessor) { Logger.Info( $"Mixin {mixinRelation.MixinType.Name} is an accessor for {mixinRelation.TargetType.Name}."); RedirectManager.RegisterTypeRedirect(mixinRelation.MixinType, mixinRelation.TargetType); continue; } CopyScaffoldingHandler.ProcessType(mixinRelation.TargetType, mixinRelation.MixinType); foreach (var action in mixinRelation.MixinActions.OrderBy(a => a.Priority)) { action.LocateTargetMethod(); Logger.Debug($"Starting to proccess action for \"{action.MixinMethod.FullName}\""); try { action.CheckIsValid(); } catch (Exception e) { throw new MixinApplyException( $"Method \"{action.TargetMethod}\" is not a valid target for \"{action.MixinMethod}\"", e); } var processor = BaseMixinActionProcessorManager.GetProcessor(action.MixinAttribute.GetType(), Workspace); processor.ProcessAction(action, action.MixinAttribute); if (action.TargetMethod.Body != null) { action.TargetMethod.Body.UpdateInstructionOffsets(); FixPdbStateIfNeeded(action.TargetMethod); RedirectManager.ProcessRedirects(action.TargetMethod, action.TargetMethod.Body); } Logger.Debug($"Finished to proccess action for \"{action.MixinMethod.FullName}\""); } Logger.Info($"Finished to process mixin {mixinRelation.MixinType.Name}"); } } private static void FixPdbStateIfNeeded(MethodDef method) { var body = method.Body; if (body == null || !body.HasPdbMethod) return; var pdbMethod = body.PdbMethod; var pdbMethodScope = pdbMethod.Scope; if (pdbMethodScope == null) return; //Fix start if (!body.Instructions.Contains(pdbMethodScope.Start)) pdbMethodScope.Start = body.Instructions.FirstOrDefault(i => i.SequencePoint != null); //Fix start if (!body.Instructions.Contains(pdbMethodScope.End)) pdbMethodScope.End = body.Instructions.FirstOrDefault(i => i.SequencePoint != null); } private void GenerateHelperCode(List<MixinRelation> mixinRelations, MixinTargetModule targetModule) { List<ClassDeclarationSyntax> declarationSyntaxes = new List<ClassDeclarationSyntax>(); foreach (var mixinRelation in mixinRelations) { Logger.Info($"Starting to process mixin {mixinRelation.MixinType.Name}"); var classDeclarationSyntax = new GeneratorMixinRelation(mixinRelation).ToSyntax(); if (classDeclarationSyntax != null) declarationSyntaxes.Add(classDeclarationSyntax); Logger.Info($"Finished to process mixin {mixinRelation.MixinType.Name}"); } var namespaceDeclarationSyntax = NamespaceDeclaration( IdentifierName(Workspace.Configuration.BaseNamespace ?? "SharpILMixins")) .WithNamespaceKeyword( Token(SyntaxKind.NamespaceKeyword)) .WithMembers(new SyntaxList<MemberDeclarationSyntax>(declarationSyntaxes)); var code = namespaceDeclarationSyntax.NormalizeWhitespace().ToFullString(); File.WriteAllText(Path.Combine(Workspace.Settings.OutputPath, "GeneratedTargets.cs"), code); } private void DumpRequestedTargets(List<MixinRelation> mixinRelations, DumpTargetType dumpTargets) { foreach (var relation in mixinRelations.DistinctBy(r => r.MixinType.FullName)) { if (!ShouldDump(relation, dumpTargets)) continue; var targetType = relation.TargetType; Logger.Info($"Target dump for \"{targetType.FullName}\":"); Logger.Info("Methods:"); foreach (var method in targetType.Methods) { Logger.Info($">> {method.FullName}"); if (method.Body != null) { DumpInvokeTargets(method, dumpTargets); DumpFieldTargets(method, dumpTargets); } } Logger.Info(""); } } private void DumpInvokeTargets(MethodDef method, DumpTargetType dumpTargets) { if (dumpTargets.HasFlagFast(DumpTargetType.Invoke)) { Logger.Info(""); Logger.Info("Invoke targets:"); var invokeCalls = method.Body.Instructions .Where(i => InvokeInjectionProcessor.IsCallOpCode(i.OpCode)) .Select(i => i.Operand) .OfType<IMethodDefOrRef>() .Select(i => i.FullName).Distinct().ToList(); invokeCalls.ForEach(c => Logger.Info($">>> {c}")); } } private void DumpFieldTargets(MethodDef method, DumpTargetType dumpTargets) { if (dumpTargets.HasFlagFast(DumpTargetType.Invoke)) { Logger.Info(""); Logger.Info("Field targets:"); var fieldCalls = method.Body.Instructions .Where(i => FieldInjectionProcessor.IsFieldOpCode(i.OpCode)) .Select(i => i.Operand) .OfType<IField>() .Select(i => i.FullName).Distinct().ToList(); fieldCalls.ForEach(c => Logger.Info($">>> {c}")); } } private bool ShouldDump(MixinRelation relation, DumpTargetType dumpTargets) { return dumpTargets != DumpTargetType.None; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace EdubranApi.Models { public class StudentDTO { public int student_number { get; set; } public string first_name { get; set; } public string middle_name { get; set; } public string last_name { get; set; } public string profile_pic { get; set; } public string wall_paper { get; set; } public string category { get; set; } public string gender { get; set; } /// <summary> /// name of the university or techknikon /// </summary> public string instituiton { get; set; } /// <summary> /// academic level, 1 means first year, 2 means second year etc /// </summary> public int level { get; set; } //public ICollection<Skill> student_skills { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.DataStudio.Diagnostics { interface ILogListener { void Write(TraceEventType eventType, ComponentID componentId, DateTime timeStamp, IDictionary<string, string> properties, string format, params object[] args); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mobile { public class Display { private int displaySize; private int numberOfColors; public Display(int displaySize = 0, int numberOfColors = 0) { this.displaySize = displaySize; this.numberOfColors = numberOfColors; } public int DisplaySize { get { return displaySize;} set { if (value <= 0) { throw new ArgumentOutOfRangeException("The display size must be a positive number"); } else { value = this.displaySize; } ;} } public int NumberOfColors { get { return numberOfColors; } set { if (value <= 0) { throw new ArgumentOutOfRangeException("The number of the colors must be a positive number"); } else { value = this.numberOfColors; } ; } } } }
using HINVenture.Shared.Data; using HINVenture.Shared.Models.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HINVenture.Shared.Models { public class CustomerRepository : IUserRepository<CustomerUser> { private readonly ApplicationDbContext _db; public CustomerRepository(ApplicationDbContext db) { this._db = db; } public Task Create(CustomerUser p) { throw new NotImplementedException(); } public async Task<CustomerUser> Get(string id) { return await _db.CustomerUsers.FindAsync(id); } public IQueryable<CustomerUser> GetAll() { throw new NotImplementedException(); } public Task Remove(CustomerUser entity) { throw new NotImplementedException(); } public Task Update(CustomerUser entity) { throw new NotImplementedException(); } } }
using Domen; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DBBroker { public class Broker { SqlConnection connection; SqlTransaction transaction; public Broker() { connection = new SqlConnection(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SeminarskiRadLekovi;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); } public int Update(IEntity entity) { SqlCommand sqlCommand = new SqlCommand("", connection, transaction); sqlCommand.CommandText = $"update {entity.TableName} set {entity.UpdateValue} {entity.SelectWhere}"; return sqlCommand.ExecuteNonQuery(); } public int GetNewId(IEntity entity) { SqlCommand sqlCommand = new SqlCommand("", connection, transaction); sqlCommand.CommandText = $"select max({entity.Id}) from {entity.TableName}"; dynamic result = sqlCommand.ExecuteScalar(); if (result is DBNull) { return 1; } return (int)result + 1; } public int Delete(IEntity entity) { SqlCommand sqlCommand = new SqlCommand("", connection, transaction); sqlCommand.CommandText = $"delete from {entity.TableName} {entity.SelectWhere}"; return sqlCommand.ExecuteNonQuery(); } public int Insert(IEntity entity) { SqlCommand command = new SqlCommand("", connection, transaction); command.CommandText = $"insert into {entity.TableName} values ({entity.InsertValues})"; return command.ExecuteNonQuery(); } public List<IEntity> Select(IEntity entity) { SqlCommand command = new SqlCommand("", connection, transaction); command.CommandText = $"select * from {entity.TableName} {entity.AliasName} {entity.JoinTable} {entity.JoinCondition} {entity.SelectWhere}"; SqlDataReader reader = command.ExecuteReader(); List<IEntity> entities = entity.ReturnReaderResult(reader); reader.Close(); return entities; } public void OpenConnection() { connection.Open(); } public void CloseConnection() { connection.Close(); } public void BeginTransaction() { transaction = connection.BeginTransaction(); } public void Commit() { transaction.Commit(); } public void RollBack() { transaction.Rollback(); } } }
using UnityEngine; using System.Collections; public class SwitchPanels : MonoBehaviour { const string ACTIVATE = "activate"; const string DE_ACTIVATE = "deactivate"; public void changePanel(string str){ changePanelStatic (str); } public static void changePanelStatic(string str){ char[] panelSplits = { ',' }; char[] instructionsSplits = { ':' }; string[] panels = str.Split (panelSplits); for (int i = 0; i < panels.Length; i++) { string[] panelInstruction = panels [i].Split (instructionsSplits); Debug.Log ("tutorial obj name: " + panelInstruction [0]); GameObject panel = (GameObject) StartGame.findInactive (panelInstruction [0], "vMenu")[0]; if (panelInstruction [1].CompareTo (ACTIVATE) == 0) { Debug.Log ("activate"); panel.SetActive (true); } else { Debug.Log ("deactivate"); panel.SetActive (false); } } } }
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; namespace WindowsFormsApplication1 { public partial class Form1 : Form { string path; //шлях до файлу string name; System.Xml.XmlReader xmlReader; // XmlReader для читання текстового файлу string quest; // змінна для питання string[] answer = new string[4]; // масив для відповідей (радіобаттонів) string n, g, k, d;// змінні для текст боксів string pic; // шлях до картинки int m, s; // змінні для таймеру int right; // номер правильного варіанту відповіді int choosequ; // номер вибраного студентом варіанту відповіді int sumrig; // кількість правильних відповідей int sumque; // загальна кількість питань int mode; // стан програми: // 0 - початок роботи авторизація; // 1 - тестування; // 2 - кінець public Form1(string[] args) { InitializeComponent(); label2.Visible = false; //непотрібні на початку роботи елементи переведені в невидимий режим label3.Visible = false; label4.Visible = false; radioButton1.Visible = false; radioButton2.Visible = false; radioButton3.Visible = false; radioButton4.Visible = false; pictureBox1.Visible = false; if (args.Length > 0)// вказуємо xml файл як параметр команди запуска { if (args[0].IndexOf(":") == -1) // вказано тільки ім'я файлу { path = Application.StartupPath + "\\"; name = args[0]; } else { // вказаний шлях path = args[0].Substring(0,args[0].LastIndexOf("C:\\Users\\Yaroslav\\Desktop\\Новая папка (2)\\MyTest\\MyTest\\bin\\Debug") +1); name = args[0].Substring(args[0].LastIndexOf("questions.xml")+1); } xmlReader = new System.Xml.XmlTextReader(path + name); // отримуємо доступ к xml документу xmlReader.Read(); mode = 0; // режим програми sumrig = 0; this.showHead(); // завантажуємо заголовок this.showDescription(); // та опис } } // функція відображення назви тесту private void showHead() { do xmlReader.Read(); // шукаємо <head> while(xmlReader.Name != "head"); xmlReader.Read(); // читаємо заголовок this.Text = xmlReader.Value; // виводимо назву в заголовок xmlReader.Read(); // виходимо з <head> } // функція для обробки питань private void showDescription() { do // шукаємо <description> xmlReader.Read(); while(xmlReader.Name != "description"); xmlReader.Read(); // читаємо опис теста label1.Text = xmlReader.Value;// виводимо опис тесту xmlReader.Read(); // виходимо з <description> do xmlReader.Read(); // шукаємо запитання по тегу <qw> while (xmlReader.Name != "qw"); xmlReader.Read(); // вмходимо з <qw> } // читаємо питання private Boolean getQw() { xmlReader.Read(); // шуаємо <q> if (xmlReader.Name == "q") { quest = xmlReader.GetAttribute("text"); //присвоюємо змінним елементи( питання, картинку) pic = xmlReader.GetAttribute("src"); xmlReader.Read(); // потрапляємо в простір з відповідями int i = 0; while (xmlReader.Name != "q") { xmlReader.Read(); // зчитуємо елементи q <q> if (xmlReader.Name == "a") // шукаємо за тегом варіанти відповідей { if (xmlReader.GetAttribute("answer") == "yes") // запам'ятовуємо правильну відповідь right = i; xmlReader.Read(); // зчитуємо варіанти відповідей в масив if (i < 4) answer[i] = xmlReader.Value; xmlReader.Read(); // виходимо з <a> i++; } } xmlReader.Read(); // виходимо з <q> return true; } // на випадок якщо тег не є тегом питання <q> else return false; } private void showQw() // відображаємо питання та відповідь { label1.Text = quest; // виводимо питання if (pic.Length != 0)// відображення картинок { pictureBox1.Image = new Bitmap(pic); pictureBox1.Visible = true; radioButton1.Top = pictureBox1.Bottom + 16; } else { if (pictureBox1.Visible) pictureBox1.Visible = false; radioButton1.Top = label1.Bottom; } // відображаємо в кнопках варіанти відповідей radioButton1.Text = answer[0]; radioButton2.Top = radioButton1.Top + 24; radioButton2.Text = answer[1]; radioButton3.Top = radioButton2.Top + 24; radioButton3.Text = answer[2]; radioButton4.Top = radioButton3.Top + 24; radioButton4.Text = answer[3]; radioButton5.Checked = true; button1.Enabled = false; } private void radioButton1_Click(object sender, EventArgs e) // функція бля обробки натиску на кнопки відповідей { if ((RadioButton)sender == radioButton1) choosequ = 0; if ((RadioButton)sender == radioButton2) choosequ = 1; if ((RadioButton)sender == radioButton3) choosequ = 2; if ((RadioButton)sender == radioButton4) choosequ = 3; button1.Enabled = true; } private void timer1_Tick(object sender, EventArgs e) //таймер { s = s - 1; if (s == -1)//кінець хвилини { m = m - 1; s = 59; } if (m == 0 && s == 0)//кінець часу { timer1.Stop(); MessageBox.Show("Час вийшов!"); label2.Visible = false; label3.Visible = false; label4.Visible = false; radioButton1.Visible = false; radioButton2.Visible = false; radioButton3.Visible = false; radioButton4.Visible = false; pictureBox1.Visible = false; if (sumrig == 12) d = "Відмінно "; else if (sumrig <= 11 && sumrig >= 10) d = "Дуже добре"; else if (sumrig <= 9 && sumrig >= 7) d = "Добре"; else if (sumrig <= 6 && sumrig >= 5) d = "Задовільно"; else if (sumrig <= 4) d = "Незадовільно"; label1.Text = "Тестування закінчено.\n" + "Студент " + k.ToString() + " " + "курсу " + " " + "групи " + g.ToString() + " " + n.ToString() + ".\n" + "Правильно відповів на" + " " + sumrig.ToString() + " " + "з" + " " + sumque.ToString() + " " + "питань.\n " + "Ваш рівень знань: " + " " + d.ToString(); } label2.Text = Convert.ToString(m + " :");//відображення часу в програмі label3.Text = Convert.ToString(s); } private void button1_Click_1(object sender, EventArgs e) // натиск по кнопці ОК { switch (mode) { case 0: // режим початку роботи n = textBox1N.Text; // присваюємо змінним значення з тестбоксів g = textBox2G.Text; k = textBox3K.Text; m = 4; // хвилини та секунди таймера s = 0; timer1.Start(); label2.Visible = true; label3.Visible = true; label4.Visible = true; label5N.Visible = false; label6G.Visible = false; label7K.Visible = false; textBox1N.Visible = false; textBox2G.Visible = false; textBox3K.Visible = false; radioButton1.Visible = true; radioButton2.Visible = true; radioButton3.Visible = true; radioButton4.Visible = true; this.getQw(); this.showQw(); mode = 1; button1.Enabled = false; radioButton5.Checked = true; break; case 1: sumque++; // лічильник кількості питань if (choosequ == right) sumrig++; // перевірка на правильність відповіді if (this.getQw()) this.showQw(); else // якщо питань більше немає { timer1.Stop(); label2.Visible = false; label3.Visible = false; label4.Visible = false; label5N.Visible = false; label6G.Visible = false; label7K.Visible = false; textBox1N.Visible = false; textBox2G.Visible = false; textBox3K.Visible = false; radioButton1.Visible = false; radioButton2.Visible = false; radioButton3.Visible = false; radioButton4.Visible = false; pictureBox1.Visible = false; if (sumrig == sumque) d = "Відмінно "; else if (sumrig<=sumque-1 && sumrig>= sumque -2) d = "Дуже добре"; else if (sumrig<=sumque-3 && sumrig>=sumque-5) d = "Добре"; else if (sumrig <= sumque -6 && sumrig >= sumque - 7) d = "Задовільно"; else if (sumrig <= sumque - 8 ) d = "Незадовільно"; label1.Text = "Тестування закінчено.\n" + "Студент " + k.ToString() +" "+ "курсу " + " " + "групи "+ g.ToString() + " " + n.ToString() + ".\n" + "Правильно відповів на" + " " + sumrig.ToString() + " " + "з" + " " + sumque.ToString() + " " + "питань.\n "+ "Ваш рівень знань: "+" "+d.ToString(); // следующий щелчок на кнопке Ok // закроет окно программы mode = 2; } break; case 2: // завершение работы программы this.Close(); // закрыть окно break; } } } }
using System.Collections; using System.Collections.Generic; using Unity.Jobs.LowLevel.Unsafe; using UnityEngine; public class CollisionEntrance : MonoBehaviour { public int MaxObjCntPerNode; public int MaxDepth; public int XSize; public int YSize; public Vector2 BoxWidthRange; public Vector2 BoxHeightRange; public int BoxCnt; public bool FixedInput; private QTree qTree; private Player Player; public void Start() { Player = GeneratePlayer(); qTree = new QTree(FixedInput ? LoadBoxes() : GenerateBoxs(), new Bound(0, 0, XSize, YSize), MaxObjCntPerNode, MaxDepth); //qTree.InsertObj(Player); } private List<Obstacle> GenerateBoxs() { List<Obstacle> _obsList = new List<Obstacle>(); GameObject _collidorCubePrefab = Resources.Load<GameObject>("Prefabs/Cube"); int _minX = 0 - XSize / 2; int _maxX = 0 + XSize / 2; int _minY = 0 - YSize / 2; int _maxY = 0 + YSize / 2; GameObject _goRoot = GameObject.Find("ColliderBoxs"); for (int i = 0; i < BoxCnt; i++) { int _newX = Random.Range(_minX, _maxX); int _newY = Random.Range(_minY, _maxY); int _newWidth = Random.Range((int)BoxWidthRange.x, (int)BoxWidthRange.y); int _newHeight = Random.Range((int)BoxHeightRange.x, (int)BoxHeightRange.y); GameObject _go = Instantiate<GameObject>(_collidorCubePrefab, new Vector3(_newX, 0, _newY), Quaternion.identity, _goRoot.transform); _go.transform.localScale = new Vector3(_newWidth, 1, _newHeight); Obstacle _newObj = new Obstacle(_go, new Bound(_newX, _newY, _newWidth, _newHeight)); _obsList.Add(_newObj); } return _obsList; } private List<Obstacle> LoadBoxes() { Transform[] _trs = GameObject.Find("Fixed").GetComponentsInChildren<Transform>(); List<Obstacle> _list = new List<Obstacle>(); for(int i = 1;i<_trs.Length;i++) _list.Add(new Obstacle(_trs[i].gameObject)); return _list; } private Player GeneratePlayer() { GameObject _collidorCubePrefab = Resources.Load<GameObject>("Prefabs/Player"); GameObject _go = Instantiate<GameObject>(_collidorCubePrefab, new Vector3(0, 0, 0), Quaternion.identity); _go.transform.localScale = new Vector3(1, 1, 1); Player _newPlayer = new Player(_go); return _newPlayer; } public void FixedUpdate() { Bullet.BulletsUpdate(qTree); Obstacle.FixedUpdateObs(qTree); } private void Update() { Obj.UpdateBound(); Player.PlayerUpdate(); } public void OnDrawGizmos() { if (qTree != null) { qTree.RenderTree(); //Obstacle.OnDrawGizmosObstacle(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LSP._2_after { public class NissanLeaf:Car { public void ChargeBattery(ChargePercent chargePercent) { //... } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Accounting.Entity { public class Factory { public Factory() { } #region Fields private int intFactoryID = 0; private string strFactoryName = ""; private string strAddress = ""; private int intCustomerID = 0; #endregion #region Properties public int FactoryID { get { return intFactoryID; } set { intFactoryID = value; } } public string FactoryName { get { return strFactoryName; } set { strFactoryName = value; } } public string Address { get { return strAddress; } set { strAddress = value; } } public int CustomerID { get { return intCustomerID; } set { intCustomerID = value; } } #endregion } }
using System; using System.Collections; namespace HashTableExample { class Program { static void Main(string[] args) { Hashtable hs = new Hashtable(); hs.Add(1, "Eins"); hs.Add(2, "Zwei"); hs.Add(3, "Drei"); foreach (DictionaryEntry entry in hs) { Console.WriteLine($"Entry with key {entry.Key} has value {entry.Value}"); } Console.ReadLine(); } } }
namespace YAGNIBicycleAfter { public interface IBicycle { int Wheels { get; } int Seat { get; } string Body { get; } int Breaks { get; } string Chain { get; } string Steering { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Cinemachine; namespace Pitstop { public class OpenTheGate : MonoBehaviour { public bool testBridgeReparation = false; [Header("Bridge parts")] [SerializeField] GameObject brokenBridge = default; [SerializeField] GameObject workingBridge = default; [SerializeField] Animator repairingBridge = default; [Header("Virtual cameras")] [SerializeField] GameObject vCamPlayer = default; [SerializeField] GameObject vCamBridge = default; private void Update() { if (testBridgeReparation) { BridgeReparation(); testBridgeReparation = false; } } public void BridgeReparation() { vCamBridge.SetActive(true); vCamPlayer.SetActive(false); repairingBridge.SetTrigger("RepairBridge"); workingBridge.SetActive(true); brokenBridge.SetActive(false); } public void BridgeIsRepaired() { vCamPlayer.SetActive(true); vCamBridge.SetActive(false); } } }
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 System.Configuration; namespace HotelManagement { public partial class InvoiceAdding : Form { public InvoiceAdding() { InitializeComponent(); } private void loadCombobox(SqlConnection conn) { string query = "SELECT maDP FROM DatPhong"; SqlDataAdapter da = new SqlDataAdapter(query, conn); DataSet ds = new DataSet(); da.Fill(ds, "maDP"); comboBox1.DisplayMember = "maDP"; comboBox1.DataSource = ds.Tables["maDP"]; } private void loadTable() { string strConn = ConfigurationManager.ConnectionStrings["Demo"].ToString(); SqlConnection conn = new SqlConnection(strConn); using (conn) { try { conn.Open(); //chon tat ca cot trong HoaDon String query = "SELECT * FROM HoaDon"; SqlCommand cmd = new SqlCommand(query, conn); DataTable dt = new DataTable(); SqlDataReader rd = cmd.ExecuteReader(); //dat ten cac cot dt.Columns.Add("Mã hóa đơn", typeof(String)); dt.Columns.Add("Ngày thanh toán", typeof(String)); dt.Columns.Add("Tổng tiền", typeof(String)); dt.Columns.Add("Mã đặt phòng", typeof(String)); DataRow row = null; //đọc dữ liệu them vao tung cot tuong ung while (rd.Read()) { row = dt.NewRow(); row["Mã hóa đơn"] = rd["maHD"]; row["Ngày thanh toán"] = rd["ngayThanhToan"]; row["Tổng tiền"] = rd["tongTien"]; row["Mã đặt phòng"] = rd["maDP"]; dt.Rows.Add(row); } rd.Close(); conn.Close(); danhsachhoadon.DataSource = dt; //chinh do rong cac cot danhsachhoadon.Columns[0].Width = 150; danhsachhoadon.Columns[1].Width = 200; danhsachhoadon.Columns[2].Width = 150; danhsachhoadon.Columns[3].Width = 150; } catch (Exception ex) { MessageBox.Show("Error!"); } } } private void ngaythanhtoanlb_Click(object sender, EventArgs e) { } private void ngaythanhtoandt_ValueChanged(object sender, EventArgs e) { } private void mahdtb_TextChanged(object sender, EventArgs e) { } private void ThemHoaDon_Option_Click(object sender, EventArgs e) { try { string strConn = ConfigurationManager.ConnectionStrings["Demo"].ToString(); SqlConnection conn = new SqlConnection(strConn); //ket noi database SqlDataReader rd = null; //ket noi command den procedure muon xai SqlCommand cmd = new SqlCommand("SP_CreateBill", conn); cmd.CommandType = CommandType.StoredProcedure; //them bien maDP cho procedure theo combobox cmd.Parameters.Add(new SqlParameter("@maDP", Int32.Parse(comboBox1.Text))); conn.Open(); //thuc thi rd = cmd.ExecuteReader(); //load lai bang loadTable(); conn.Close(); } catch (Exception ex) { throw ex; } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void InvoiceAdding_Load(object sender, EventArgs e) { string strConn = ConfigurationManager.ConnectionStrings["Demo"].ToString(); SqlConnection conn = new SqlConnection(strConn); using (conn) { try { conn.Open(); loadCombobox(conn); loadTable(); conn.Close(); } catch (Exception ex) { MessageBox.Show("Error!"); } } } private void danhsachhoadon_CurrentCellChanged(object sender, EventArgs e) { } private void danhsachhoadon_SelectionChanged(object sender, EventArgs e) { } private void SuaHoaDon_Option_Click(object sender, EventArgs e) { string strConn = ConfigurationManager.ConnectionStrings["Demo"].ToString(); SqlConnection conn = new SqlConnection(strConn); using (conn) { try { //query de update String query = "UPDATE HoaDon SET ngayThanhToan=@ngayThanhToan, tongTien=@tongTien where maDP=@maDP "; //mo ket noi conn.Open(); SqlCommand cmd = new SqlCommand(query, conn); cmd.Parameters.AddWithValue("@maDP", comboBox1.Text); cmd.Parameters.AddWithValue("@maHD", mahdtb.Text); //doi ra ngay DateTime ngaythanhtoan = DateTime.Parse(ngaythanhtoandt.Text); cmd.Parameters.AddWithValue("@ngayThanhToan", ngaythanhtoan); cmd.Parameters.AddWithValue("@tongTien", tongtientb.Text); cmd.ExecuteNonQuery(); MessageBox.Show("Updated"); conn.Close(); //Reset lai bang sau khi update loadTable(); } catch (Exception ex) { throw ex; MessageBox.Show("Error!"); } } } private void XoaHoaDon_Option_Click(object sender, EventArgs e) { string strConn = ConfigurationManager.ConnectionStrings["Demo"].ToString(); SqlConnection conn = new SqlConnection(strConn); using (conn) { try { //query de delete String query = "DELETE FROM HoaDon WHERE maDP=@maDP"; //mo ket noi conn.Open(); SqlCommand cmd = new SqlCommand(query, conn); // nhan gia tri MaDP tu Combobox cmd.Parameters.AddWithValue("@maDP", Int32.Parse(comboBox1.Text)); cmd.ExecuteNonQuery(); MessageBox.Show("Deleted"); conn.Close(); //Reset lai bang sau khi update loadTable(); } catch (Exception ex) { throw ex; MessageBox.Show("Error!"); } } } private void danhsachhoadon_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { //Chon cac dong cua bang theo click chuot DataGridViewRow row = this.danhsachhoadon.Rows[e.RowIndex]; mahdtb.Text = row.Cells[0].Value.ToString(); ngaythanhtoandt.Text = row.Cells[1].Value.ToString(); tongtientb.Text = row.Cells[2].Value.ToString(); comboBox1.Text = row.Cells[3].Value.ToString(); } } private void QuayLaisv_Option_Click(object sender, EventArgs e) { Option_sv option = new Option_sv(); option.Show(); this.Hide(); } } }
using System.Collections.Generic; using System; [Serializable] public class CapturaSecoes { public String resultadoTrajetoria; public float tempoEmFase; public String motivoDerrota; public List<String> trajetoria = new List<string>(); }
using System; namespace MCCForms { public interface ISecurity { string GetGeneratedDatabasePincode(string plainPincode); string GetValueFromKeyChain(string entryKey); bool SaveValueToKeyChain (string entryKey, string entryValue); bool DeleteValueFromKeyChain (string entryKey); } }
using OpenGov.Models; using System; using System.Threading.Tasks; namespace OpenGov.TaskManagers { public interface ITaskManager { Task<Uri> AddTask(Meeting meeting); } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; using System.IO; using DotNetNuke.Entities.Users; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Tokens; using Newtonsoft.Json; namespace DotNetNuke.UI.Modules.Html5 { public class ModuleLocalizationDto { [JsonProperty("key")] public string Key { get; set; } [JsonProperty("localresourcefile")] public string LocalResourceFile { get; set; } } public class ModuleLocalizationPropertyAccess : JsonPropertyAccess<ModuleLocalizationDto> { private readonly ModuleInstanceContext _moduleContext; private readonly string _html5File; public ModuleLocalizationPropertyAccess(ModuleInstanceContext moduleContext, string html5File) { _html5File = html5File; _moduleContext = moduleContext; } protected override string ProcessToken(ModuleLocalizationDto model, UserInfo accessingUser, Scope accessLevel) { string returnValue = string.Empty; string resourceFile = model.LocalResourceFile; if (String.IsNullOrEmpty(resourceFile)) { var fileName = Path.GetFileName(_html5File); var path = _html5File.Replace(fileName, ""); resourceFile = Path.Combine(path, Localization.LocalResourceDirectory + "/", Path.ChangeExtension(fileName, "resx")); } if (!String.IsNullOrEmpty(model.Key)) { returnValue = Localization.GetString(model.Key, resourceFile); } return returnValue; } } }