text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Arch.Data.Test.OtherTest { public class RightManager { //public delegate void RightAddedHandler(); public event EventHandler<RightAddedEventArgs> OnRightAdded; public virtual void AddRight() { Console.WriteLine("add right from RightManager"); RightAddedEventArgs args = new RightAddedEventArgs("code0"); OnRightAdded(this,args); } public virtual void RemoveRight() { Console.WriteLine("remove right from RightManager"); } public virtual void UpdateRight() { Console.WriteLine("update right from RightManager"); } } public class RightAddedEventArgs : EventArgs { public readonly string RightCode; public RightAddedEventArgs(string rightCode) { RightCode = rightCode; } } }
using UnityEngine; using System; using System.IO; using System.Collections.Generic; class player { private float playerMoney = 0; private string playerColor; private Dictionary<string,int> playerItems = new Dictionary<string,int>(); private List<string> friendList = new List<string>(); public player(string colorIn){ playerColor = colorIn; } public void changeItem(string itemName, int itemNumber, bool sell, float transMoney){ if (!sell){ if (playerMoney - transMoney >= 0) if (playerItems.ContainsKey(itemName)){ playerItems[itemName] += itemNumber; playerMoney -= transMoney; } else{ playerItems[itemName] = itemNumber; playerMoney -= transMoney; } else { Debug.LogError("not enough money"); } } else{ if (playerItems.ContainsKey(itemName)){ if (playerItems[itemName] < itemNumber){ Debug.LogError("not enough items to sell"); } else{ playerItems[itemName] -= itemNumber; playerMoney += transMoney; } } else{ Debug.LogError("no such item"); } if (playerItems[itemName]==0){ playerItems.Remove(itemName); } } } public int getNumber(string itemName){ return playerItems[itemName]; } public string getColor(){ return playerColor; } } class Test{ static void Main(){ player player1 = new player("red"); player1.changeItem("aaaaa",12, false, 100); player1.changeItem("aaaaa",-11, true, 200); Console.Write(player1.getNumber("aaaaa")); } }
namespace ChatTest.App.Models { public class UserModel : UserGetModel { public string ConnectionId { get; set; } public string Token { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Optymalizacja_wykorzystania_pamieci.Diagnostics { class Engine_Info { public int number_of_threads { get; set; } public long real_time { get; set; } public double process_time { get; set; } public Engine_Info(int number_of_threads, long real_time, double process_time) { this.number_of_threads = number_of_threads; this.real_time = real_time; this.process_time = process_time; } } }
namespace gView.GraphicsEngine { public struct CanvasSizeF { public CanvasSizeF(float width, float height) { this.Width = width; this.Height = height; } public float Width { get; set; } public float Height { get; set; } } }
using System; using Whathecode.System.Diagnostics; using Xunit; namespace Whathecode.Tests.System.Diagnostics { public class RunTimeTest { [Fact] public void FromTest() { Action test = () => { }; // Single run. StatisticsStopwatch.Measurement oneRun = RunTime.From( test ); Assert.True( oneRun.MeasurementCount == 1 ); // Multiple runs. const int runs = 10; StatisticsStopwatch.Measurement multipleRuns = RunTime.From( "Multiple runs", test, runs ); Assert.True( multipleRuns.MeasurementCount == runs ); } } }
using System.Windows; namespace SC.WPFSamples { /// <summary> /// Interaction logic for TriggerDemo.xaml /// </summary> public partial class TriggerDemo : Window { public TriggerDemo() { InitializeComponent(); } private void OnPropertyTrigger(object sender, RoutedEventArgs e) { new PropertyTriggerWindow().Show(); } private void OnMultiTrigger(object sender, RoutedEventArgs e) { new MultiTriggerWindow().Show(); } private void OnDataTrigger(object sender, RoutedEventArgs e) { new DataTriggerWindow().Show(); } } }
using System.Collections.Generic; namespace EPI.Recursion { /// <summary> /// Find the list of all strings that have k pairs of matched parenthesis /// </summary> /// <example> /// k=1, return {"()"} /// k=2, returns { "(())", "()()" } /// k=3, returns { "((()))", "(()())", "(())()", "()(())", "()()()" } /// </example> public static class EnumerateStringsOfBalancedParens { public static List<string> ListAllMatchedParens(int k) { List<string> result = new List<string>(); string currentString = string.Empty; MatchedParensHelper(2 * k, 0, currentString, result); return result; } private static void MatchedParensHelper(int remainingChars, int leftParensCount, string currentString, List<string> result) { // base case: add current string to result when current index matches k if (remainingChars == 0) { result.Add(currentString); } else { if (leftParensCount < remainingChars) { MatchedParensHelper(remainingChars - 1, leftParensCount + 1, currentString + "(", result); } if (leftParensCount > 0) { MatchedParensHelper(remainingChars - 1, leftParensCount - 1, currentString + ")", result); } } } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; namespace DomainEventsTest { public class TestHelper { public ServiceProvider ServiceProvider { get; } public TestHelper() { var services = new ServiceCollection(); ServiceProvider = services.BuildServiceProvider(); } } }
using UnityEngine; public class ContentController : MonoBehaviour { public RectTransform Content; public RectTransform ContentTalisman; public RectTransform ContentSigil; }
using Arda.Common.ViewModels.Main; using System.Collections.Generic; namespace Arda.Common.Interfaces.Kanban { public interface ITechnologyRepository { // Return a list of all technologies. IEnumerable<TechnologyViewModel> GetAllTechnologies(); } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Pacman { public static class RenderHelper { private static Vector3 up = new Vector3(0, 0, 1); private static Vector3 renderFogColor = new Vector3(0, 0, 0); /// <summary>Render the model without any effects.</summary> /// <param name="model">The model to render.</param> /// <param name="world">The world matrix defining location and rotation of the model.</param> /// <param name="camera">The current camera.</param> public static void BasicRender(Model model, Matrix world, Camera camera) { model.Draw(world, camera.View, camera.Projection); } /// <summary>Render the model without any effects.</summary> /// <param name="model">The model to render.</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="rotation">The rotation the model has in relation to the world axis.</param> /// <param name="camera">The current camera.</param> public static void BasicRender(Model model, Vector3 position, float rotation, Camera camera) { BasicRender(model, Matrix.CreateWorld(position, new Vector3((float)Math.Cos(rotation), (float)Math.Sin(rotation), 0), up), camera); } /// <summary>Render the model without any effects.</summary> /// <param name="model">The model to render.</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="forward">The vector describing forward for the model.</param> /// <param name="camera">The current camera.</param> public static void BasicRender(Model model, Vector3 position, Vector3 forward, Camera camera) { BasicRender(model, Matrix.CreateWorld(position, forward, up), camera); } /// <summary>Render the model with only basic effects.</summary> /// <param name="model">The model to render.</param> /// <param name="world">The world matrix defining location and rotation of the model.</param> /// <param name="camera">The current camera.</param> public static void RenderBasicEffect(Model model, Matrix world, Camera camera) { // Copy any parent transforms. Matrix[] transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms); // Draw the meshes of the model foreach (ModelMesh mesh in model.Meshes) { // Set the mesh orientation and get view from the camera foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.World = transforms[mesh.ParentBone.Index] * world; effect.View = camera.View; effect.Projection = camera.Projection; } // Draw the mesh, using the effects set above. mesh.Draw(); } } /// <summary>Render the model with only basic effects.</summary> /// <param name="model">The model to render.</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="rotation">The rotation the model has in relation to the world axis.</param> /// <param name="camera">The current camera.</param> public static void RenderBasicEffect(Model model, Vector3 position, float rotation, Camera camera) { RenderBasicEffect(model, Matrix.CreateWorld(position, new Vector3((float)Math.Cos(rotation), (float)Math.Sin(rotation), 0), up), camera); } /// <summary>Render the model with only basic effects.</summary> /// <param name="model">The model to render.</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="forward">The vector describing forward for the model.</param> /// <param name="camera">The current camera.</param> public static void RenderBasicEffect(Model model, Vector3 position, Vector3 forward, Camera camera) { RenderBasicEffect(model, Matrix.CreateWorld(position, forward, up), camera); } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="world">The world matrix defining location and rotation of the model.</param> /// <param name="camera">The current camera.</param> public static void RenderFogEffect(Model model, Matrix world, Camera camera) { // Copy any parent transforms. Matrix[] transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms); // Draw the meshes of the model foreach (ModelMesh mesh in model.Meshes) { // Set the mesh orientation and get view from the camera foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.FogStart = 2000; effect.FogEnd = 2500; effect.FogColor = renderFogColor; effect.FogEnabled = true; effect.World = transforms[mesh.ParentBone.Index] * world; effect.View = camera.View; effect.Projection = camera.Projection; } // Draw the mesh, using the effects set above. mesh.Draw(); } } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="rotation">The rotation the model has in relation to the world axis.</param> /// <param name="camera">The current camera.</param> public static void RenderFogEffect(Model model, Vector3 position, float rotation, Camera camera) { RenderFogEffect(model, Matrix.CreateWorld(position, new Vector3((float)Math.Cos(rotation), (float)Math.Sin(rotation), 0), up), camera); } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="forward">The vector describing forward for the model.</param> /// <param name="camera">The current camera.</param> public static void RenderFogEffect(Model model, Vector3 position, Vector3 forward, Camera camera) { RenderFogEffect(model, Matrix.CreateWorld(position, forward, up), camera); } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="alpha">The level of tranparency to use for the model (0 to 1).</param> /// <param name="world">The world matrix defining location and rotation of the model.</param> /// <param name="camera">The current camera.</param> public static void RenderSemiTransparent(Model model, float alpha, Matrix world, Camera camera) { // Copy any parent transforms. Matrix[] transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms); // Draw the meshes of the model foreach (ModelMesh mesh in model.Meshes) { // Set the mesh orientation and get view from the camera foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.Alpha = alpha; effect.World = transforms[mesh.ParentBone.Index] * world; effect.View = camera.View; effect.Projection = camera.Projection; } // Draw the mesh, using the effects set above. mesh.Draw(); } } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="alpha">The level of tranparency to use for the model (0 to 1).</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="rotation">The rotation the model has in relation to the world axis.</param> /// <param name="camera">The current camera.</param> public static void RenderSemiTransparent(Model model, float alpha, Vector3 position, float rotation, Camera camera) { RenderSemiTransparent(model, alpha, Matrix.CreateWorld(position, new Vector3((float)Math.Cos(rotation), (float)Math.Sin(rotation), 0), up), camera); } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="alpha">The level of tranparency to use for the model (0 to 1).</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="forward">The vector describing forward for the model.</param> /// <param name="camera">The current camera.</param> public static void RenderSemiTransparent(Model model, float alpha, Vector3 position, Vector3 forward, Camera camera) { RenderSemiTransparent(model, alpha, Matrix.CreateWorld(position, forward, up), camera); } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="alpha">The level of tranparency to use for the model (0 to 1).</param> /// <param name="world">The world matrix defining location and rotation of the model.</param> /// <param name="camera">The current camera.</param> public static void RenderSemiTransparentFog(Model model, float alpha, Matrix world, Camera camera) { // Copy any parent transforms. Matrix[] transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms); // Draw the meshes of the model foreach (ModelMesh mesh in model.Meshes) { // Set the mesh orientation and get view from the camera foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.FogStart = 2000; effect.FogEnd = 2500; effect.FogColor = renderFogColor; effect.FogEnabled = true; effect.Alpha = alpha; effect.World = transforms[mesh.ParentBone.Index] * world; effect.View = camera.View; effect.Projection = camera.Projection; } // Draw the mesh, using the effects set above. mesh.Draw(); } } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="alpha">The level of tranparency to use for the model (0 to 1).</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="rotation">The rotation the model has in relation to the world axis.</param> /// <param name="camera">The current camera.</param> public static void RenderSemiTransparentFog(Model model, float alpha, Vector3 position, float rotation, Camera camera) { RenderSemiTransparentFog(model, alpha, Matrix.CreateWorld(position, new Vector3((float)Math.Cos(rotation), (float)Math.Sin(rotation), 0), up), camera); } /// <summary>Render the model with distance fog enabled.</summary> /// <param name="model">The model to render.</param> /// <param name="alpha">The level of tranparency to use for the model (0 to 1).</param> /// <param name="position">The position the model should be rendered at.</param> /// <param name="forward">The vector describing forward for the model.</param> /// <param name="camera">The current camera.</param> public static void RenderSemiTransparentFog(Model model, float alpha, Vector3 position, Vector3 forward, Camera camera) { RenderSemiTransparentFog(model, alpha, Matrix.CreateWorld(position, forward, up), camera); } } }
using System; using EQS.AccessControl.Application.ViewModels.Input; using EQS.AccessControl.Application.ViewModels.Output; using EQS.AccessControl.Application.ViewModels.Output.Base; namespace EQS.AccessControl.Application.Interfaces { public interface ILoginAppService : IDisposable { ResponseModelBase<LoginOutput> Login(CredentialInput credential); } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DMS.Admin.Images { public partial class HospitalMaster : System.Web.UI.Page { Transaction tran = new Transaction(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.BindData(); } } private void BindData() { List<HospitalModel> model = tran.GetHospitalDetailsAll(); gvHospitals.DataSource = model; gvHospitals.DataBind(); } protected void EditCustomer(object sender, GridViewEditEventArgs e) { gvHospitals.EditIndex = e.NewEditIndex; BindData(); } protected void CancelEdit(object sender, GridViewCancelEditEventArgs e) { gvHospitals.EditIndex = -1; BindData(); } protected void RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && gvHospitals.EditIndex == e.Row.RowIndex) { DropDownList ddlCities = (DropDownList)e.Row.FindControl("ddlState"); TextBox txtName = (TextBox)e.Row.FindControl("txtName"); ddlCities.Items.FindByValue((e.Row.FindControl("lblState") as Label).Text).Selected = true; txtName.Text = (e.Row.FindControl("lblName") as Label).Text; } } protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e) { int index = Convert.ToInt32(e.RowIndex); int id = Convert.ToInt32(((Label)gvHospitals.Rows[index].Cells[0].FindControl("lblId")).Text); tran.RemoveHospital(id); Response.Redirect(Request.Url.AbsoluteUri); } protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e) { string state = (gvHospitals.Rows[e.RowIndex].FindControl("ddlState") as DropDownList).SelectedItem.Value; string HosName = (gvHospitals.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim(); string HosId = gvHospitals.DataKeys[e.RowIndex].Value.ToString(); string strConnString = ConfigurationManager.ConnectionStrings["EHealthCareConnectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(strConnString)) { string query = "update HospitaMaster set State = @state,Hospital_Name=@HosName where Hospital_Id = @HosId"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; cmd.Parameters.AddWithValue("@state", state); cmd.Parameters.AddWithValue("@HosId", HosId); cmd.Parameters.AddWithValue("@HosName", HosName); con.Open(); cmd.ExecuteNonQuery(); con.Close(); Response.Redirect(Request.Url.AbsoluteUri); } } } protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) { } protected void btnAdd_Click(object sender, EventArgs e) { HospitalModel model = new HospitalModel(); model.hosname = txtHosName.Text.Trim(); model.hosstate = ddlHosState.SelectedValue; model.hoscountry = ddlCountry.SelectedValue; tran.AddHospital(model); Response.Redirect(Request.Url.AbsoluteUri); } } }
using EngineLibrary.Game; using EngineLibrary.Scripts; using EngineLibrary.Utils; using GameLibrary.Components; using SharpDX; using SharpDX.DirectInput; using System.Collections.Generic; namespace GameLibrary.Scripts.Game { /// <summary> /// Класс поведения лука /// </summary> public class BowShoot : KeyboardListenerScript { private PlayerComponent _playerComponent; private VisibleComponent _visibleComponent; private Dictionary<ArrowType, CopyableGameObject> _arrowTemplates; private Vector3 _originalPosition; private int _currentArrowIndex = 0; private float _visibilityDuration; private float _processCoef; private float _process = 0.0f; private float _maxProcess = 1.0f; /// <summary> /// Конструктор класса /// </summary> /// <param name="processDuration">Зависимость процесса натяжения</param> /// <param name="visibilityDuration">Время видимости</param> public BowShoot(float processDuration = 5.0f, float visibilityDuration = 1.0f) { _arrowTemplates = new Dictionary<ArrowType, CopyableGameObject>(); _processCoef = 1.0f / processDuration * 10.0f; _visibilityDuration = visibilityDuration; Actions.Add(Key.R, (delta) => { if (!_visibleComponent.IsHidden) { ChangeArrow(); } }); } /// <summary> /// Добавление дублируемого образца стрел /// </summary> /// <param name="type">Тип стрелы</param> /// <param name="arrowTemplate">Образец</param> public void AddArrowTemplate(ArrowType type, CopyableGameObject arrowTemplate) { _arrowTemplates.Add(type, arrowTemplate); } /// <summary> /// Инициализация класса /// </summary> public override void Init() { _originalPosition = GameObject.Position; _visibleComponent = GameObject.GetComponent<VisibleComponent>(); } /// <summary> /// Обновления поведения после нажатий клавиш /// </summary> /// <param name="delta">Время между кдарами</param> protected override void AfterKeyProcess(float delta) { if (_visibleComponent.IsHidden) return; if (_playerComponent == null) _playerComponent = GameObject.Parent.GetComponent<PlayerComponent>(); if (!_playerComponent.IsHasArrows((ArrowType)_currentArrowIndex)) { GameObject.IsHidden = true; return; } UpdateShootingProcess(delta); } /// <summary> /// Обновление процесса натяжения /// </summary> /// <param name="delta">Время между кадрами</param> private void UpdateShootingProcess(float delta) { var inputController = InputController.GetInstance(); // если в этом кадре была нажата ЛКМ if (inputController.MouseButtons[0]) { // изменяем натяжение _process += delta; if (_process >= _maxProcess) { _process = _maxProcess; } // двигаем объект стрелы на луке var dest = new Vector3(0, 0, -_process / _processCoef); GameObject.MoveTo(_originalPosition + dest); // изменяем состояние прицеливания _playerComponent.IsAiming = true; } else { // если стрелу в прошлых кадрах НАТЯГИВАЛИ if (_process != 0) { GameObject.MoveTo(_originalPosition); _visibleComponent.MakeInvisible(_visibilityDuration); Shoot(); _process = 0; } // изменяем состояние прицеливания _playerComponent.IsAiming = false; } } /// <summary> /// Смена стрел /// </summary> private void ChangeArrow() { _visibleComponent.MakeInvisible(_visibilityDuration); var arrows = GameObject.Children; _currentArrowIndex++; if (_currentArrowIndex >= arrows.Count) _currentArrowIndex = 0; for(int i = 0; i < arrows.Count; i++) { arrows[i].IsHidden = _currentArrowIndex != i; } } /// <summary> /// Создаем стрелу /// </summary> private void Shoot() { // получаем копию из образца var arrow = _arrowTemplates[(ArrowType)_currentArrowIndex].Copy(); // настраиваем объект arrow.GetComponent<ArrowComponent>().FiringForceCoef = _process; GameObject.Scene.AddGameObject(arrow); arrow.MoveTo(GameObject.Position); arrow.IsHidden = false; _playerComponent.RemoveArrow((ArrowType)_currentArrowIndex); } } /// <summary> /// Тип стрелы /// </summary> public enum ArrowType { /// <summary> /// Обычная стрела /// </summary> Standart = 0, /// <summary> /// Стрелы с ядом /// </summary> Poison, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraMove : MonoBehaviour { private Transform _player; private Vector3 _vec; // Start is called before the first frame update void Start() { _player = GameObject.Find("Player").transform; //读取玩家位置 _vec = _player.position - transform.position; //计算偏移量 } // Update is called once per frame void Update() { transform.position = _player.position - _vec; //用玩家位置减去偏移量 } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace LucrareDeDisertatie.Models { public class Utilizator { [Key, Column(Order = 1)] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int idUtilizator { get; set; } [Required(ErrorMessage = "Camp obligatoriu.")] [StringLength(50, MinimumLength = 2)] public string Nume { get; set; } [Required] [StringLength(50, MinimumLength = 2)] public string Prenume { get; set; } [Required] [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")] public string Email { get; set; } [Required] [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$")] public string Parola { get; set; } [NotMapped] [Required] [System.ComponentModel.DataAnnotations.Compare("Parola")] public string VerificareParola { get; set; } public string NumeComeplt() { return this.Nume + " " + this.Prenume; } } }
using Alabo.Cloud.Shop.SuccessfulCases.Domains.Entities; using Alabo.Domains.Entities; using Alabo.Domains.Services; using MongoDB.Bson; namespace Alabo.Cloud.Shop.SuccessfulCases.Domains.Services { public interface ICasesService : IService<Cases, ObjectId> { Cases GetCourseView(object id); ServiceResult AddOrUpdate(Cases view); } }
namespace PizzaBox.Domain.PizzaLib.Abstracts { interface IPizzaRepositoryAdd<T> { void PizzaBoxAdd(T record); } }
using Microsoft.CSharp.RuntimeBinder; using Mojang.Minecraft; using Mojang.Minecraft.Protocol; using Mojang.Minecraft.Protocol.Providers; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace TestConsole { partial class TestClient : PlayerClient { private const int FIRST_ITEM = 1; private const char SPACE = ' '; private const char SPLITTER = SPACE; public TestClient(string serverAddress, ushort serverPort, string username) : base(serverAddress, serverPort, username) { } public TestClient(Socks5TcpConnectProvider socksConnect, string username) : base(socksConnect, username) { } protected override void OnEntityEquipped(int entityId, EquipmentSlot slot, Slot item) { if (slot == EquipmentSlot.Held) { Console.WriteLine(item); } base.OnEntityEquipped(entityId, slot, item); } bool _FirstChat = true; protected override void OnChatted(Chat jsonData, ChatPosition chatPosition) { //jsonData: {"translate":"chat.type.text","with":[{"clickEvent":{"action":"suggest_command","value":"/msg SiNian "},"text":"SiNian"},"hi"]} //jsonData: {"translate":"chat.type.text","with":[{"clickEvent":{"action":"suggest_command","value":"/msg SiNian "},"text":"SiNian"},"hello"]} /* try { var sender = jsonData.Root.with[0].text; var message = jsonData.Root.with[1] as string; Console.WriteLine(message); if (sender == "SiNian") { var instruction = message.Split(SPLITTER); try { var result = InvokeCommand(instruction.First(), instruction.Skip(FIRST_ITEM).ToArray()); if (result != null) { Chat(result.ToString()).Wait(); } } catch (ArgumentException e) { Chat(e.Message).Wait(); } } } catch (RuntimeBinderException) { } */ if (_FirstChat) { _FirstChat = false; ChangeState(StateAction.RequestStats).Wait(); } try { var sb = new StringBuilder(); foreach (var messageSegment in Array.ConvertAll(jsonData.Root.extra, new Converter<dynamic, string>(o => o is string ? o : o.text))) sb.Append(messageSegment); var message = sb.ToString(); Console.WriteLine(message); if (message.Contains("注册")) Chat("/reg sinian sinian").Wait(); else if(message.Contains("登录") || message.Contains("登陆")) Chat("/login sinian sinian").Wait(); var playerMessageComponentRegex = new Regex(@"^(?:\[(?#place)(.*?)\])?<(?#sender)(.*?)> (?:(?#reciever)(\w*?)\.)?(?#message)(.*)$"); if (playerMessageComponentRegex.IsMatch(message)) { var match = playerMessageComponentRegex.Match(message); var sender = match.Groups[2].ToString(); var reciever = match.Groups[3].ToString(); var playerMessage = match.Groups[4].ToString(); if (!(string.IsNullOrEmpty(reciever) || reciever == Username)) return; if (sender == "imgcre") { var instruction = playerMessage.Split(SPLITTER); try { var result = InvokeCommand(instruction.First(), instruction.Skip(FIRST_ITEM).ToArray()); if (result != null) { Chat(result.ToString()).Wait(); } } catch (ArgumentException e) { Chat(e.Message).Wait(); } } } } catch(RuntimeBinderException) { } } } }
using Backend.Model; using Microsoft.EntityFrameworkCore; using PatientService.Model; using PatientService.Repository; using System; using System.Collections.Generic; using Xunit; namespace PatientServiceTests.IntegrationTests { public class PatientServiceTests { private PatientService.Service.PatientService SetupRepositoryAndService() { DataSeeder dataSeeder = new DataSeeder(); DbContextOptionsBuilder<MyDbContext> builder = new DbContextOptionsBuilder<MyDbContext>(); ; DbContextOptions<MyDbContext> options; MyDbContext context; builder.UseInMemoryDatabase(Guid.NewGuid().ToString()); options = builder.Options; context = new MyDbContext(options); dataSeeder.SeedAll(context); var patientRepo = new PatientRepository(context); return new PatientService.Service.PatientService(patientRepo); } [Fact] public void SuccessGetTherapiesForExamination() { PatientService.Service.PatientService patientService = SetupRepositoryAndService(); IEnumerable<Therapy> therapies = patientService.GetTherapiesForExamination("1309998775018", -86); Assert.Empty(therapies); } [Fact] public void SuccessGetExamination() { PatientService.Service.PatientService patientService = SetupRepositoryAndService(); Assert.Throws<InvalidOperationException>(() => patientService.GetExamination("1309998775018", -86)); } } }
using ImagoCore.Enums; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; namespace ImagoCore.Tests.Enums { public class ImagoEnumerationTests { private readonly ITestOutputHelper output; public ImagoEnumerationTests(ITestOutputHelper output) { this.output = output; } [Fact] public void ImagoAttributEnumerationInitializes_NoNumberDoubled() { List<ImagoAttribut> liste = new List<ImagoAttribut>(Enumeration.GetAll<ImagoAttribut>()); output.WriteLine("Teste Enum Attribute Value : Name"); AssertEnumerationForDuplicates(liste); } [Fact] public void ImagoFertigkeitEnumerationInitializes_NoNumberDoubled() { List<ImagoFertigkeit> liste = new List<ImagoFertigkeit>(Enumeration.GetAll<ImagoFertigkeit>()); output.WriteLine("Teste Enum Fertigkeiten Value : Name"); AssertEnumerationForDuplicates(liste); } [Fact] public void ImagoFertigkeitsKategorieEnumerationInitializes_NoNumberDoubled() { List<ImagoFertigkeitsKategorie> liste = new List<ImagoFertigkeitsKategorie>(Enumeration.GetAll<ImagoFertigkeitsKategorie>()); output.WriteLine("Teste Enum Fertigkeitskategorien Value : Name"); AssertEnumerationForDuplicates(liste); } [Fact] public void ImagoKoerperTeilEnumerationInitializes_NoNumberDoubled() { List<ImagoKoerperTeil> liste = new List<ImagoKoerperTeil>(Enumeration.GetAll<ImagoKoerperTeil>()); output.WriteLine("Teste Enum Körperteile Value : Name"); AssertEnumerationForDuplicates(liste); } [Fact] public void ImagoNichtSteigerbareFertigkeitenEnumerationInitializes_NoNumberDoubled() { List<ImagoNichtSteigerbareFertigkeit> liste = new List<ImagoNichtSteigerbareFertigkeit>(Enumeration.GetAll<ImagoNichtSteigerbareFertigkeit>()); output.WriteLine("Teste Enum Nichtsteigerbare Fertigkeiten Value : Name"); AssertEnumerationForDuplicates(liste); } [Fact] public void ImagoKoerperTeileEnumerationInitializes_NoNumberDoubled() { List<ImagoKoerperTeil> liste = new List<ImagoKoerperTeil>(Enumeration.GetAll<ImagoKoerperTeil>()); output.WriteLine("Teste Enum Körperteile Value : Name"); AssertEnumerationForDuplicates(liste); } [Fact] public void ImagoRasseEnumerationInitializes_NoNumberDoubled() { List<ImagoRasse> liste = new List<ImagoRasse>(Enumeration.GetAll<ImagoRasse>()); output.WriteLine("Teste Enum Rassen Value : Name"); AssertEnumerationForDuplicates(liste); } [Fact] public void ImagoKoerperTeilZustaendeInitializes_NoNumberDoubled() { List<ImagoKoerperTeil> liste = new List<ImagoKoerperTeil>(Enumeration.GetAll<ImagoKoerperTeil>()); output.WriteLine("Teste Enum Körperteilzustände Value : Name"); AssertEnumerationForDuplicates(liste); } private void AssertEnumerationForDuplicates<T>(List<T> input) where T : Enumeration { var temp = new List<T>(input); temp.Sort((a, b) => a.Value.CompareTo(b.Value)); bool hit = false; for (int i = 0; i < temp.Count(); i++) { output.WriteLine("{0:00}: {1}", i, temp[i].ToString()); if (i != 0) { if (temp[i - 1].Value == temp[i].Value) { hit = true; break; } } } Assert.False(hit); } } //public class EnumerationInitializeTestData: IEnumerable<object[]> //{ // public IEnumerator<object[]> GetEnumerator() // { // yield return // } // IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArizaTakipYazılımSistemi.Model { class Personel { public int personel_id { get; set; } public string adi { get; set; } public string soyadi { get; set; } public int bolum_id { get; set; } public int unvan_id { get; set; } public bool yetki { get; set; } public string username { get; set; } public string password { get; set; } } }
using Assets.Common.Extensions; using UnityEngine; namespace Assets.src.models { public struct TileInfo { public TileInfo(Vector3 center) { index.x = (int) center.x; index.y = (int) center.z; centerPosition = new Vector3(index.x + 0.5f, 0, index.y + 0.5f); } public TileInfo(Point p) { index = p; centerPosition = new Vector3(index.x + 0.5f, 0, index.y + 0.5f); } public Point index; public Vector3 centerPosition; } }
using System; using System.Collections.Generic; namespace DrivingSchool_Api { public partial class BookingPackage { public BookingPackage() { Booking = new HashSet<Booking>(); PackageInclusionsAssc = new HashSet<PackageInclusionsAssc>(); } public int BkpId { get; set; } public int BookingTypeId { get; set; } public string BkpName { get; set; } public string PackageDescription { get; set; } public decimal PackagePrice { get; set; } public virtual BookingType BookingType { get; set; } public virtual ICollection<Booking> Booking { get; set; } public virtual ICollection<PackageInclusionsAssc> PackageInclusionsAssc { get; set; } } }
using Bank.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Bank { public partial class AppealList : Form { DBWorker db; public int selectedId = 0; bool closeToClick; List<int> ids; public AppealList(int clientId, bool closeToClick) { InitializeComponent(); db = new DBWorker(); if(!db.Connect()) { MessageBox.Show("Не удалось подключиться к бд"); this.Close(); return; } ids = new List<int>(); this.closeToClick = closeToClick; try { List<ViewAppeal> appeals = db.GetAppealsByClientId(clientId); foreach (ViewAppeal appeal in appeals) { appealListTable.Rows.Add(appeal.toArray()); ids.Insert(appealListTable.Rows.GetLastRow(DataGridViewElementStates.Visible), appeal.Id); } } catch(Exception e) { MessageBox.Show(e.Message); this.Close(); } } private void appealListTable_CellContentClick(object sender, DataGridViewCellEventArgs e) { selectedId = ids[e.RowIndex]; if (closeToClick) this.Close(); } } }
using Shipwreck.TypeScriptModels.Declarations; namespace Shipwreck.TypeScriptModels { public static class TypeBuilder { public static ArrayType MakeArrayType(this ITypeReference type) => new ArrayType(type); public static UnionType UnionWith(this ITypeReference type, ITypeReference other) { var ut = new UnionType(); ut.ElementTypes.Add(type); ut.ElementTypes.Add(other); return ut; } } }
using System.Linq; using Efa.Application.Interfaces; using Efa.Application.ViewModels; using Efa.Domain.Interfaces.Services; using Efa.Infra.Data.Context; namespace Efa.Application.AppService { public class DashAppService : AppServiceBase<EfaContext>, IDashAppService { private readonly IAlunoService _alunoService; private readonly ITurmaService _turmaService; private readonly IProfessorService _professorService; private readonly IContatoPessoaAppService _contatoService; public DashAppService(IAlunoService alunoService, ITurmaService turmaService, IProfessorService professorService, IContatoPessoaAppService contatoService) { _alunoService = alunoService; _turmaService = turmaService; _professorService = professorService; _contatoService = contatoService; } public DashViewModel Dash() { BeginTransaction(); var viewModel = new DashViewModel() { TotalAlunos = _alunoService.GetAll(0,5).Count(), TotalProfessores = _professorService.GetAll(0,5).Count(), TotalTurmas = _turmaService.GetAll(0,5).Count(), TotalContatos = _contatoService.GetAll(0,5).Count() }; return viewModel; } public void Dispose() { _alunoService.Dispose(); _professorService.Dispose(); _turmaService.Dispose(); _contatoService.Dispose(); } } }
using Chess.v4.Models; using Chess.v4.Models.Enums; using System.Collections.Generic; namespace Chess.v4.Engine.Interfaces { public interface ICheckmateService { bool IsCheckMate(GameState gameState, Color white, IEnumerable<AttackedSquare> whiteKingAttacks); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abhs.Model.ViewModel { public class StudentModelCondition { public int schoolId { get; set; } public int classId { get; set; } /// <summary> /// 注册开始时间 /// </summary> public string regBeginDate { get; set; } /// <summary> /// 注册结束时间 /// </summary> public string regEndDate { get; set; } /// <summary> /// 到期开始时间 /// </summary> public string finishBeginDate { get; set; } /// <summary> /// 到期结束时间 /// </summary> public string finishEndDate { get; set; } /// <summary> /// 搜索关键字 /// </summary> public string key { get; set; } /// <summary> /// 年级 /// </summary> public string grade { get; set; } /// <summary> /// 性别 /// </summary> public string sex { get; set; } /// <summary> /// 来源 /// </summary> public string source { get; set; } /// <summary> /// 状态 /// </summary> public string status { get; set; } /// <summary> /// 是否分配 /// </summary> public int isAllot { get; set; } = 1; public int page { get; set; } public int limit { get; set; } } public class StudentsCondition { public int schoolId { get; set; } public int classId { get; set; } //是否包含本班级 public int isClass { get; set; } /// <summary> /// 搜索关键字 /// </summary> public string key { get; set; } /// <summary> /// 年级 /// </summary> public int grade { get; set; } /// <summary> /// 性别 /// </summary> public int sex { get; set; } /// <summary> /// 等级 /// </summary> public int level { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chic_Move : MonoBehaviour { public Animator Chicken; public GameObject chicken; Vector3[] posi = new Vector3[4]; int posi_index = 0; int x, y; int a = 1; int plag = 0; void Awake() { Chicken = GetComponent<Animator>(); chicken = GameObject.Find("Chicken"); } // Update is called once per frame void Start() { Invoke("Chicken_Move", 2.4f); x = Cow_Move.instance.x; y = Cow_Move.instance.y; Cow_Move.instance.point[1] = chicken.transform.position; Cow_Move.instance.point_y[1] = chicken.transform.position; } void Update() { Invoke("Move_Init", 2.0f); Invoke("Move_Finish", 6.7f); } public void Chicken_Move() { if (Chicken == null) { Debug.Log("Chicken State Error!"); } } private void Moving() { float step = 5f * Time.deltaTime; Vector3 current = transform.position; //현재 위치 좌표 if (x == a) { Chicken.Play("jump"); if (plag == 0) { //x -> y로 이동할때 posi[0] = Cow_Move.instance.point[x]; Cow_Move.instance.point[x].z += 8f; posi[1] = Cow_Move.instance.point[x]; Cow_Move.instance.point[y].z += 8f; posi[2] = Cow_Move.instance.point[y]; Cow_Move.instance.point[y].z -= 8f; posi[3] = Cow_Move.instance.point[y]; plag = 1; } transform.LookAt(posi[posi_index]); transform.position = Vector3.MoveTowards(current, posi[posi_index], step); if (Vector3.Distance(current, posi[posi_index]) == 0f) { posi_index++; } } else if (y == a) { Chicken.Play("jump"); if (plag == 0) { //y -> x로 이동할때 posi[0] = Cow_Move.instance.point_y[y]; Cow_Move.instance.point_y[y].z += 8f; posi[1] = Cow_Move.instance.point_y[y]; Cow_Move.instance.point_y[x].z += 8f; posi[2] = Cow_Move.instance.point_y[x]; Cow_Move.instance.point_y[x].z -= 8f; posi[3] = Cow_Move.instance.point_y[x]; plag = 1; } transform.LookAt(posi[posi_index]); transform.position = Vector3.MoveTowards(current, posi[posi_index], step); if (Vector3.Distance(current, posi[posi_index]) == 0f) { posi_index++; } } } public void Move_Init() { if (posi_index < 4) { Moving(); } } public void Move_Finish() { if (transform.rotation.y == 0) { return; } if (transform.rotation.y >= 0 && transform.rotation.y <= 180) { if (x == a) { Chicken.Play("jump"); transform.Rotate(0, -10, 0); } else if (y == a) { Chicken.Play("jump"); transform.Rotate(0, 10, 0); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class PickableItem : MonoBehaviour, ISerializationCallbackReceiver { [Header("Item")] public ItemObject item; public void OnAfterDeserialize() { } public void OnBeforeSerialize() { #if UNITY_EDITOR GetComponentInChildren<SpriteRenderer>().sprite = item.sprite; EditorUtility.SetDirty(GetComponentInChildren<SpriteRenderer>()); #endif } }
using System; using System.Linq; namespace _03._Battle_Manager { class Program { static void Main() { string lines; while ((lines = Console.ReadLine()) != "Results") { string[] command = lines.Split(":", StringSplitOptions.RemoveEmptyEntries); if (command[0] == "Add") { string name = command[1]; int health = int.Parse(command[2]); int energy = int.Parse(command[3]); BattleList.AddPerson(name, health, energy); } else if (command[0] == "Attack") { string attackerName = command[1]; string defenderName = command[2]; int damage = int.Parse(command[3]); BattleList.Attack(attackerName, defenderName, damage); } else if (command[0] == "Delete") { string username = command[1]; if (command[1] != "All") { BattleList.Delete(username); } else { BattleList.DeleteAll(username); } } } Console.WriteLine($"People count: {BattleList.Battles.Count}"); foreach (var person in BattleList.Battles.OrderByDescending(x => x.Health).ThenBy(x => x.Name)) { Console.WriteLine($"{person.Name} - {person.Health} - {person.Energy}"); } } } }
/* * CREATED BY HM */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BangazonWorkforceSapphireElephants.Models { public class Computer { public int Id { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] public DateTime PurchaseDate { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] public DateTime? DecomissionDate { get; set; } [Required] public string Make { get; set; } [Required] public string Manufacturer { get; set; } public Employee Employee { get; set; } } }
using Newtonsoft.Json; namespace Repositories.Entities { public class ExchangeTableRate { [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("code")] public string Code { get; set; } [JsonProperty("mid")] public double Mid { get; set; } } }
using DaScript.Lib.Data.Infrastructure; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Appointments.DAL.Models { public class UserAddress : TrackedEntityBase, IEntityBase<string> { /// <summary> /// UserName /// </summary> [ForeignKey("Person")] public string Id { get; set; } /// <summary> /// Address first line /// </summary> public string Address1 { get; set; } /// <summary> /// Address second line /// </summary> public string Address2 { get; set; } /// <summary> /// City /// </summary> public string City { get; set; } /// <summary> /// Zip Code /// </summary> public string Zipcode { get; set; } /// <summary> /// State of the Country /// </summary> public string State { get; set; } /// <summary> /// Country /// </summary> public string Country { get; set; } #region links /// <summary> /// Person identifier asking for an <see cref="UserAddress"/> /// </summary> [ForeignKey("Person")] public virtual long PersonId { get; set; } /// <summary> /// Link to User Information /// </summary> public virtual Person Person { get; set; } #endregion } }
using Microsoft.AspNetCore.Mvc; namespace Demo //be sure to use your own project's namespace! { public class HomeController : Controller //remember inheritance?? { // Requests // Views Index [HttpGet] //type of request [Route("")] // localost:5000/ public ViewResult Index() { return View(); } // Views - Home [HttpGet("home")] //type of request & route localhost:5000/home public ViewResult Home() { ViewBag.Example = "From the ViewBag!"; return View(); } // Redirect [HttpGet("redirect")] public RedirectToActionResult RedoIndex() { return RedirectToAction("Index"); } // Redirect to Route with params [HttpGet("redirect/users")] public RedirectToActionResult RedoUsers() { // or user var param = new { name= "kevin" } return RedirectToAction("Users", new { name = "Kevin", age = 40 }); } // Using Route Params [HttpGet("users/{name}/{age}")] public string Users(string name, int age) { return $"Hello {name}, you are {age} years old."; } // Redirect to Method in OtherController [HttpGet("other")] public RedirectToActionResult Method() { return RedirectToAction("Another", "Other"); } // Return JSON Result [HttpGet("user1")] public JsonResult User1() { var response = new { first_name = "Kevin", last_name = "Camp", email = "kcamp4632@yahoo.com", age = 40 }; return Json(response); } // IActionResult [HttpGet("request/{type}")] public IActionResult Depends(string type) { var result = new { type = "JSON" }; if (type == "redirect") { return RedirectToAction("Index"); } else if (type == "json") { return Json(result); } return View(); } // POST Request [HttpPost("submission")] // POST to localhost:5000/submission public string FormSubmission(string formInput) { return formInput; } } }
using System.Drawing; public static class Define { public static void define(Player[] player, Npc[] npc, Map[] map) { Player.current_player = 0;//默认角色 //设置角色属性 player[0] = new Player(); player[0].bitmap = new Bitmap(@"role/r1.png"); player[0].bitmap.SetResolution(96, 96); player[0].is_active = 1; player[1] = new Player(); player[1].bitmap = new Bitmap(@"role/r2.png"); player[1].bitmap.SetResolution(96, 96); player[1].is_active = 1; player[2] = new Player(); player[2].bitmap = new Bitmap(@"role/r2.png"); player[2].bitmap.SetResolution(96, 96); player[2].is_active = 1; //map define map[0] = new Map(); map[0].bitmap_path = "map/map1.jpg"; map[0].shade_path = "map/map1_shade.png"; map[0].block_path = "map/map1_block.png"; map[0].music = "music/1.mp3"; map[1] = new Map(); map[1].bitmap_path = "map/map2.jpg"; map[1].shade_path = "map/map2_shade.png"; map[1].block_path = "map/map2_block.png"; map[1].music = "music/3.mp3"; //npc define npc[0] = new Npc(); npc[0].map = 0; npc[0].x = 200; npc[0].y = 600; npc[0].bitmap_path = "role/npc1.png"; npc[1] = new Npc(); npc[1].map = 0; npc[1].x = 800; npc[1].y = 600; npc[1].bitmap_path = "role/npc2.png"; npc[2] = new Npc(); npc[2].map = 0; npc[2].x = 450; npc[2].y = 150; npc[2].region_x = 100; npc[2].region_y = 100; npc[2].collision_type = Npc.Collosion_type.ENTER; npc[3] = new Npc(); npc[3].map = 1; npc[3].x = 100; npc[3].y = 150; npc[3].region_x = 40; npc[3].region_y = 40; npc[3].collision_type = Npc.Collosion_type.ENTER; npc[4] = new Npc(); npc[4].map = 0; npc[4].x = 500; npc[4].y = 200; npc[4].bitmap_path = "role/npc3.png"; npc[4].collision_type = Npc.Collosion_type.KEY; Animation npc4anm1 = new Animation(); npc4anm1.bitmap_path = "role/anm1.png"; npc4anm1.row = 2; npc4anm1.col = 2; npc4anm1.max_frame = 3; npc4anm1.anm_rate = 4; npc[4].anm = new Animation[1]; npc[4].anm[0] = npc4anm1; npc[5] = new Npc(); npc[5].map = 1; npc[5].x = 500; npc[5].y = 500; npc[5].bitmap_path = "role/npc4.png"; npc[5].collision_type = Npc.Collosion_type.KEY; npc[5].npc_type = Npc.Npc_type.CHARACTER; npc[5].idle_walk_direction = Comm.Direction.LEFT; npc[5].idle_walk_time = 50; npc[6] = new Npc(); npc[6].map = 0; npc[6].x = 800; npc[6].y = 1000; npc[6].region_x = 50; npc[6].region_y = 60; npc[6].x_offset = -15; npc[6].y_offset = -15; npc[6].mc_xoffset = 0; npc[6].mc_yoffset = 0; npc[6].mc_w = 90; npc[6].mc_h = 50; npc[6].bitmap_path = "role/npc_shoe.png"; npc[6].collision_type = Npc.Collosion_type.KEY; npc[7] = new Npc(); npc[7].map = 0; npc[7].x = 500; npc[7].y = 600; npc[7].bitmap_path = "role/npc2.png"; //角色人物面板头像 player[0].status_bitmap = new Bitmap(@"item/face1.png"); player[0].status_bitmap.SetResolution(96,96); player[1].status_bitmap = new Bitmap(@"item/face2.png"); player[1].status_bitmap.SetResolution(96, 96); // player[1].equip_att = 3; //player[1].equip_def = 4; player[2].status_bitmap = new Bitmap(@"item/face3.png"); player[2].status_bitmap.SetResolution(96, 96); //item Item.item=new Item[6]; Item.item[0] = new Item(); Item.item[0].set("红药水","恢复少量hp","item/item1.png",1,30,0,0,0,0); Item.item[0].cost = 30; Item.item[0].use_event += new Item.Use_event(Item.add_hp); Item.item[1] = new Item(); Item.item[1].set("蓝药水", "恢复少量mp", "item/item2.png", 1, 30, 0, 0, 0, 0); Item.item[1].use_event += new Item.Use_event(Item.add_mp); Item.item[2] = new Item(); Item.item[2].set("短剑", "一把假的", "item/item3.png", 1, 1, 10, 0, 0, 5); Item.item[2].use_event += new Item.Use_event(Item.equip); Item.item[3] = new Item(); Item.item[3].set("斧头", "666的斧头", "item/item4.png", 1, 1, 3, 0, 0, 50); Item.item[3].use_event += new Item.Use_event(Item.equip); Item.item[4] = new Item(); Item.item[4].set("盾", "666的盾,没有人可以来来来\n他", "item/item5.png", 1, 2, 0, 20, 5, 0); Item.item[4].use_event += new Item.Use_event(Item.equip); Item.item[5] = new Item(); Item.item[5].set("九阴真经", "一本的懂的书", "item/item6.png", 0, 30, 0, 0, 0, 0); Item.item[5].use_event += new Item.Use_event(Item.lpybook); Item.add_item(0,3); Item.add_item(1,3); Item.add_item(2, 2); Item.add_item(3, 1); Item.add_item(4, 1); // Item.add_item(5,1); //skill Skill.skill=new Skill[2]; Skill.skill[0] = new Skill(); Skill.skill[0].set("治疗术","恢复少量hp\nmp:20","item/skill1.png",20,20,0,0,0,0); Skill.skill[0].use_event += new Skill.Use_event(Skill.add_hp); Skill.skill[1] = new Skill(); Skill.skill[1].set("黑洞术", "攻击技能,将敌人吸入漩涡hp\nmp:20", "item/skill2.png", 20, 20, 0, 0, 0, 0); Skill.skill[1].use_event += new Skill.Use_event(Skill.low_hp); Skill.learn_skill(0,0,1); Skill.learn_skill(0, 1, 1); Skill.learn_skill(1, 0, 1); Skill.learn_skill(2,1,1); //定义战斗 Animation anm_att = new Animation(); //攻击动画,6帧 anm_att.bitmap_path = "fight/anm_att.png"; anm_att.row = 3; anm_att.col = 2; anm_att.max_frame = 6; anm_att.anm_rate = 1; Animation anm_item = new Animation(); //使用物品动画,3帧 anm_item.bitmap_path = "fight/anm_item.png"; anm_item.row = 3; anm_item.col = 1; anm_item.max_frame = 3; anm_item.anm_rate = 1; Animation anm_skill = new Animation(); //使用技能动画,4帧 anm_skill.bitmap_path = "fight/anm_skill.png"; anm_skill.row = 2; anm_skill.col = 2; anm_skill.max_frame = 4; anm_skill.anm_rate = 1; player[0].fset("主角","fight/p1.png",-120,-120,"fight/fm_face1.png",anm_att,anm_item,anm_skill); player[1].fset("辅助", "fight/p2.png", -120, -120, "fight/fm_face2.png", anm_att, anm_item, anm_skill); player[2].fset("辅助2", "fight/p3.png", -120, -120, "fight/fm_face3.png", anm_att, anm_item, anm_skill); //敌人设置 Enemy.enemy=new Enemy[2]; Enemy.enemy[0]=new Enemy(); Enemy.enemy[0].set("老虎","fight/enemy.png",-160,-120,100,200,10,15,10,anm_att,anm_skill,new int[]{-1,-1,-1,-1,-1}); Enemy.enemy[1] = new Enemy(); Enemy.enemy[1].set("鞋精","fight/enemy2.png",-160,-120,300,40,10,15,10,anm_att,anm_skill,new int[]{-1,-1,1,1,1}); //fight_item Animation anm_item0 = new Animation();//血药 anm_item0.bitmap_path = "fight/anm_heal.png"; anm_item0.row = 8; anm_item0.col = 1; anm_item0.max_frame = 4; anm_item0.anm_rate = 1; Item.item[0].fset(anm_item0,-50,20); Animation anm_item2 = new Animation(); //短剑 anm_item2.bitmap_path = "fight/anm_sword.png"; anm_item2.row = 4; anm_item2.col = 1; anm_item2.max_frame = 4; anm_item2.anm_rate = 1; Item.item[2].fset(anm_item2, 50, 20); //fight_skill Animation anm_skill0 = new Animation(); //治疗术 anm_skill0.bitmap_path = "fight/anm_heal.png"; anm_skill0.row = 4; anm_skill0.col = 1; anm_skill0.max_frame = 4; anm_skill0.anm_rate = 1; Skill.skill[0].fset(anm_skill0,-50,10); Animation anm_skill1 = new Animation();//黑暗术 anm_skill1.bitmap_path = "fight/anm_drak.png"; anm_skill1.row = 4; anm_skill1.col = 1; anm_skill1.max_frame = 4; anm_skill1.anm_rate = 1; Skill.skill[1].fset(anm_skill1, 60, 10); //定义任务 //Task Task.task=new Task[100]; //地图1 Task.task[0] = new Task(); Task.task[0].set(2, new Task.Task_event(Task.change_map), 1, 725, 250, 2); //地图2 Task.task[1] = new Task(); Task.task[1].set(3,new Task.Task_event(Task.change_map),0, 30, 500, 3); //陌生人见面 Task.task[2] = new Task(); Task.task[2].set(7,new Task.Task_event(Story.meet),0,0,Task.VARTYPE.ANY,0,1,Task.VARRESULT.ASSIGN); //陌生人催促 Task.task[3] = new Task(); Task.task[3].set(7,new Task.Task_event(Story.aftermeet),0,1,Task.VARTYPE.EQUAL,0,0,Task.VARRESULT.NOTHING); //陌生人给予奖励 Task.task[4] = new Task(); Task.task[4].set(7,new Task.Task_event(Story.reward),0,2,Task.VARTYPE.EQUAL,0,3,Task.VARRESULT.ASSIGN); //给予奖励之后 Task.task[5] = new Task(); Task.task[5].set(7,new Task.Task_event(Story.afterreward),0,3,Task.VARTYPE.EQUAL,0,0,Task.VARRESULT.NOTHING); //鞋子默认 Task.task[6] = new Task(); Task.task[6].set(6,new Task.Task_event(Story.shoe),0,0,Task.VARTYPE.ANY,0,0,Task.VARRESULT.NOTHING); //鞋子战斗 Task.task[7] = new Task(); Task.task[7].set(6,new Task.Task_event(Story.shoefight),0,1,Task.VARTYPE.EQUAL,0,0,Task.VARRESULT.NOTHING); //保存游戏 Task.task[8] = new Task(); Task.task[8].set(1,new Task.Task_event(Story.save)); //商店 Shop.show(new int[] {0,1,2,3,-1,-1,-1}); //商人所卖物品 Task.task[9] = new Task(); Task.task[9].set(0, new Task.Task_event(Story.shop)); //npc动画 Task.task[10] = new Task(); Task.task[10].set(4, new Task.Task_event(Story.play_anm)); //tip Task.task[11] = new Task(); Task.task[11].set(5, new Task.Task_event(Story.tip)); } }
using Datos; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Negocio { public class Ciudad{ public int idCiudad { get; set; } public string nombreCiudad { get; set; } public Boolean ciudadHabilitada { get; set; } //Metodo para agregar una nueva ciudad public int AgregarCiudad(Ciudad ciudad) { DatosSistema datos = new DatosSistema(); string [] parametros= {"@operacion", "@idCiudad", "@nombreCiudad", "@ciudadHabilitada"}; return datos.Ejecutar("[INFONIONIOS].spCiudadIA", parametros,"I", ciudad.idCiudad, ciudad.nombreCiudad, ciudad.ciudadHabilitada); } //Metodo para actualizar una ciudad public int ActualizarCiudad(Ciudad ciudad){ DatosSistema datos = new DatosSistema(); string[] parametros = {"@operacion", "@idCiudad", "@nombreCiudad", "@ciudadHabilitada"}; return datos.Ejecutar("[INFONIONIOS].spCiudadIA", parametros, "A", ciudad.idCiudad, ciudad.nombreCiudad, ciudad.ciudadHabilitada); } //Metodo para obtener todas las ciudades public DataTable obtenerCiudades() { string[] parametros={"@operacion","@nombreCiudad"}; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].spCiudadSE", parametros,"Y", "a"); } public List<Ciudad> obtenerListaCiudades() { List<Ciudad> ciudades = new List<Ciudad>(); DataTable dt = this.obtenerCiudades(); foreach (DataRow row in dt.Rows) { Ciudad c = new Ciudad(); c.idCiudad = Int32.Parse(row["CIUDAD_ID"].ToString()); c.nombreCiudad = row["CIUDAD_NOMBRE"].ToString(); c.ciudadHabilitada = Boolean.Parse(row["CIUDAD_HABILITADA"].ToString()); ciudades.Add(c); } return ciudades; } public int eliminarCiudad(string nombreCiudad) { DatosSistema datos = new DatosSistema(); string[] parametros = { "@operacion", "@nombreCiudad" }; return datos.Ejecutar("[INFONIONIOS].spCiudadSE", parametros, "E", nombreCiudad); } public Ciudad obtenerCiudad(Ciudad c) { DatosSistema datos = new DatosSistema(); Ciudad ciudad = new Ciudad(); var dt = new DataTable(); string[] parametros = {"@operacion","@nombreCiudad"}; dt = datos.getDatosTabla("[INFONIONIOS].spCiudadSE", parametros, "S", c.nombreCiudad); foreach (DataRow fila in dt.Rows) { ciudad.nombreCiudad = fila["nombre"].ToString(); } return ciudad; } public DataTable filtrarCiudades(object filtro1, object filtro2) { string[] parametros={"@filtro1","@filtro2"}; if (String.IsNullOrEmpty(Convert.ToString(filtro2))) { filtro2 = System.DBNull.Value; } else if (String.IsNullOrEmpty(Convert.ToString(filtro1))) { filtro1 = System.DBNull.Value; } DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].spFiltroDinamico", parametros, filtro1, filtro2); } public DataTable obtenerTodasDGV() { string[] parametros = { }; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].[spObtenerCiudadesParaDGV]", parametros); } public DataTable obtenerFiltroDGV(string nombre, bool soloH) { string[] parametros = { "@nombre", "@soloH" }; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].[spObtenerCiudadesFiltroDGV]", parametros, "%" + nombre + "%", (soloH)?1:0); } public Ciudad obtenerCiudadPorNombre(string n) { string[] parametros = { "@nombre" }; DatosSistema datos = new DatosSistema(); DataTable dt = datos.getDatosTabla("[INFONIONIOS].[spObtenerCiudadPorNombre]", parametros, n); Ciudad c = new Ciudad(); if (dt.Rows.Count > 0) { c.idCiudad = Int32.Parse(dt.Rows[0]["CIUDAD_ID"].ToString()); c.nombreCiudad = dt.Rows[0]["CIUDAD_NOMBRE"].ToString(); c.ciudadHabilitada = Boolean.Parse(dt.Rows[0]["CIUDAD_HABILITADA"].ToString()); } else { return null; } return c; } public bool estaEnAlgunaRuta(Ciudad cSeleccionada) { string[] parametros = { "@idCiudad" }; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].[spObtenerRutasDeCiudad]", parametros, cSeleccionada.idCiudad).Rows.Count > 0; } public void inhabilitarCiudad(Ciudad cSeleccionada) { string[] parametros = { "@idCiudad" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spInhabilitarCiudad]", parametros, cSeleccionada.idCiudad); } } }
namespace gView.Framework.Symbology { public interface ILegendGroup { int LegendItemCount { get; } ILegendItem LegendItem(int index); void SetSymbol(ILegendItem item, ISymbol symbol); } }
using System; using System.Globalization; using System.IO; namespace FlippoMatchViewer { public struct Disqualification { public readonly bool disqualified; public readonly int move; public readonly String reason; public static Disqualification GetNone() { return new Disqualification(false, -1, null); } public Disqualification(String[] args, StreamReader file) { if(args.Length != 2) throw new Exception("Incorrect number of arguments for Disqualification"); disqualified = true; move = int.Parse(args[0], CultureInfo.InvariantCulture); int lines = int.Parse(args[1], CultureInfo.InvariantCulture); reason = ""; for(int l = 0; l < lines; l++) { reason += file.ReadLine(); } } public Disqualification(bool disqualified, int move, String reason) { this.disqualified = disqualified; this.move = move; this.reason = reason; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using DelftTools.Functions; using DelftTools.Functions.Filters; using DelftTools.Functions.Generic; using DelftTools.TestUtils; using DelftTools.Units; using DelftTools.Utils; using GeoAPI.Extensions.Coverages; using GeoAPI.Extensions.Networks; using GisSharpBlog.NetTopologySuite.Geometries; using log4net; using NetTopologySuite.Extensions.Coverages; using NetTopologySuite.Extensions.Networks; using NUnit.Framework; using SharpMap; using SharpMap.Converters.WellKnownText; using SharpMap.Data.Providers; using SharpMap.Layers; using SharpMapTestUtils; using Point=GisSharpBlog.NetTopologySuite.Geometries.Point; namespace NetTopologySuite.Extensions.Tests.Coverages { [TestFixture] public class NetworkCoverageTest { private static readonly ILog log = LogManager.GetLogger(typeof(NetworkCoverageTest)); [TestFixtureSetUp] public void TestFixtureSetUp() { LogHelper.ConfigureLogging(); } [TestFixtureTearDown] public void TestFixtureTearDown() { LogHelper.ResetLogging(); } [Test] [NUnit.Framework.Category(TestCategory.Performance)] [NUnit.Framework.Category(TestCategory.WorkInProgress)] // slow public void AddingTimeSlicesShouldBeFastUsingMemoryStore() { var random = new Random(); //50 branches var network = RouteHelperTest.GetSnakeNetwork(false, 50); //10 offsets var offsets = new[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }; //500 locations var locations = from o in offsets from b in network.Branches select new NetworkLocation(b, o); var values = (from o in locations select (double)random.Next(100) / 10).ToList(); //setup the coverage with fixed size locations var networkCoverage = new NetworkCoverage() { IsTimeDependent = true, Network = network }; networkCoverage.Locations.FixedSize = 500; networkCoverage.Locations.SetValues(locations.OrderBy(l => l)); var startTime = new DateTime(2000, 1, 1); // add 10000 slices in time.. var times = from i in Enumerable.Range(1, 1000) select startTime.AddDays(i); int outputTimeStepIndex = 0; //write like a flowmodel .. TestHelper.AssertIsFasterThan(1700, () => { foreach (var t in times) { //high performance writing. Using indexes instead of values. var locationsIndexFilter = new VariableIndexRangeFilter(networkCoverage.Locations, 0, networkCoverage.Locations. FixedSize - 1); //current timestep starts at 1 and is increased before outputvalues are set now..hence -2 to get a 0 for the 1st //int timeIndex = currentTimeStep - 1; var timeIndexFilter = new VariableIndexRangeFilter(networkCoverage.Time, outputTimeStepIndex); networkCoverage.Time.AddValues(new[] { t }); networkCoverage.SetValues(values, new[] { locationsIndexFilter, timeIndexFilter }); outputTimeStepIndex++; } }); } [Test] public void ShouldNotBeAbleToAddTheSameLocationTwice() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage("test", false) { Network = network }; var l1 = new NetworkLocation(network.Branches[0], 10.0d); var l2 = new NetworkLocation(network.Branches[0], 10.0d); networkCoverage.Components[0][l1] = 1.0d; networkCoverage.Components[0][l2] = 3.0d; Assert.AreEqual(1,networkCoverage.Locations.Values.Count); } [Test] public void WriteSlicesUsingTimeFilterShouldBeTheSameAsUsingIndexFilter() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage("test", true) { Network = network }; var locations = new[] { new NetworkLocation(network.Branches[0], 0.0), new NetworkLocation(network.Branches[0], 100.0), new NetworkLocation(network.Branches[1], 100.0) }; networkCoverage.SetLocations(locations); networkCoverage.Locations.FixedSize = locations.Length; var networkCoverage2 = new NetworkCoverage("test", true) { Network = network }; networkCoverage2.SetLocations(locations); networkCoverage2.Locations.FixedSize = locations.Length; // set 1000 values using time filters in coverage 1 and 2 var startTime = new DateTime(2000, 1, 1); for (int i = 0; i < 1000; i++) { IEnumerable<double> values = new[] { 1.0, 2.0, 3.0 }.Select(d => d * i); DateTime currentTime = startTime.AddMinutes(i); //set values for coverage 1 using value filter networkCoverage.Time.AddValues(new[] { currentTime }); var timeValueFilter = new VariableValueFilter<DateTime>(networkCoverage.Time, currentTime); networkCoverage.SetValues(values, timeValueFilter); //set values for coverage 2 using index filter networkCoverage2.Time.AddValues(new[] { currentTime }); var timeIndexFilter = new VariableIndexRangeFilter(networkCoverage2.Time, i); networkCoverage2.SetValues(values, timeIndexFilter); } Assert.AreEqual(networkCoverage.Components[0].Values, networkCoverage2.Components[0].Values); } [Test] public void CreateForExistingNetwork() { var network = CreateNetwork(); INetworkCoverage networkCoverage = new NetworkCoverage { Network = network }; // set values networkCoverage[new NetworkLocation(network.Branches[0], 0.0)] = 0.1; networkCoverage[new NetworkLocation(network.Branches[0], 100.0)] = 0.2; networkCoverage[new NetworkLocation(network.Branches[1], 0.0)] = 0.3; //check the last set was OK Assert.AreEqual(new NetworkLocation(network.Branches[1], 0.0), networkCoverage.Locations.Values[2]); networkCoverage[new NetworkLocation(network.Branches[1], 50.0)] = 0.4; networkCoverage[new NetworkLocation(network.Branches[1], 200.0)] = 0.5; // asserts Assert.AreEqual(typeof(double), networkCoverage.Components[0].ValueType); Assert.AreEqual(typeof(INetworkLocation), networkCoverage.Arguments[0].ValueType); Assert.AreEqual(5, networkCoverage.Components[0].Values.Count); // Assert.AreEqual(2, networkCoverage.Locations.Components.Count, "networkLocation = (branch, grid), 2 components"); Assert.AreEqual(0, networkCoverage.Locations.Arguments.Count, "networkLocation = (branch, grid), has no arguments"); //Networklocation is value type :) Assert.AreEqual(0.5, networkCoverage[new NetworkLocation(network.Branches[1], 200.0)]); // logging log.Debug("Network coverage values:"); var networkLocations = networkCoverage.Arguments[0].Values; var values = networkCoverage.Components[0].Values; for (var i = 0; i < networkCoverage.Components[0].Values.Count; i++) { var networkLocation = (INetworkLocation)networkLocations[i]; log.DebugFormat("NetworkCoverage[location = ({0} - {1,6:F})] = {2}", networkLocation.Branch, networkLocation.Offset, values[i]); // ... trying to change formatting } } private static INetwork CreateNetwork() { return RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(300, 0)); } [Test] public void SplitDividesCoverageAmongBranches() { //a network with a single branch var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0)); } [Test] public void DefaultValueTest() { var network = CreateNetwork(); INetworkCoverage networkCoverage = new NetworkCoverage { Network = network, DefaultValue = 0.33 }; INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 0.0); // no network location set in networkCoverage expect the default value to return Assert.AreEqual(0.33, networkCoverage.Evaluate(nl11)); } [Test] public void DefaultValueTestValidTime() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage("test", true) { Network = network, DefaultValue = 0.33 }; var dateTime = DateTime.Now; networkCoverage[dateTime, new NetworkLocation(network.Branches[0], 50.0)] = 0.1; networkCoverage.Locations.ExtrapolationType = ExtrapolationType.Constant; // ask value form other branch; default value is expected INetworkLocation nl11 = new NetworkLocation(network.Branches[1], 0.0); // no network location set in networkCoverage expect the default value to return Assert.AreEqual(0.33, networkCoverage.Evaluate(dateTime, nl11)); } [Test] [ExpectedException(typeof(ArgumentException))] public void DefaultValueTestInvalidTime() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage("test", true) { Network = network, DefaultValue = 0.33 }; INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 0.0); // no network location set in networkCoverage expect the default value to return Assert.AreEqual(0.33, networkCoverage.Evaluate(DateTime.Now, nl11)); } [Test] public void InterpolationNoTime() { var network = CreateNetwork(); INetworkCoverage networkCoverage = new NetworkCoverage { Network = network }; // test for defaultvalue // set values INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 0.0); INetworkLocation nl12 = new NetworkLocation(network.Branches[0], 100.0); INetworkLocation nl13 = new NetworkLocation(network.Branches[1], 100.0); networkCoverage[nl11] = 0.1; networkCoverage[nl12] = 0.2; networkCoverage[nl13] = 0.3; // test the exact networklocation Assert.AreEqual(0.1, networkCoverage.Evaluate(nl11)); Assert.AreEqual(0.2, networkCoverage.Evaluate(nl12)); Assert.AreEqual(0.3, networkCoverage.Evaluate(nl13)); INetworkLocation nl21 = new NetworkLocation(network.Branches[0], 0.0); INetworkLocation nl22 = new NetworkLocation(network.Branches[0], 100.0); INetworkLocation nl23 = new NetworkLocation(network.Branches[1], 0.0); INetworkLocation nl24 = new NetworkLocation(network.Branches[1], 200.0); // test for networklocations at same location but other instances // branch and offset nl21 equals nl11 Assert.AreEqual(0.1, networkCoverage.Evaluate(nl21)); // branch and offset nl22 equals nl12 Assert.AreEqual(0.2, networkCoverage.Evaluate(nl22)); // test for value at new location with constant interpolation (1 values available at branch) // expect value of nl13 to be set for complete branches[1] Assert.AreEqual(0.3, networkCoverage.Evaluate(nl23)); Assert.AreEqual(0.3, networkCoverage.Evaluate(nl24)); // test for interpolation INetworkLocation nl1 = new NetworkLocation(network.Branches[0], 50.0); Assert.AreEqual(0.15, networkCoverage.Evaluate(nl1), 1e-6); } [Test] public void ExtraPolationNoTime() { var network = CreateNetwork(); INetworkCoverage networkCoverage = new NetworkCoverage { Network = network }; // test for defaultvalue // set two values INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 5.0); INetworkLocation nl12 = new NetworkLocation(network.Branches[0], 10.0); networkCoverage[nl11] = 0.1; networkCoverage[nl12] = 0.1; //extrapolation Assert.AreEqual(0.1, networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 20.0))); } [Test] public void InterpolationTime() { var network = CreateNetwork(); var dateTime = DateTime.Now; var networkCoverage = new NetworkCoverage("test", true) { Network = network }; // test for defaultvalue // set values INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 0.0); INetworkLocation nl12 = new NetworkLocation(network.Branches[0], 100.0); INetworkLocation nl13 = new NetworkLocation(network.Branches[1], 100.0); networkCoverage[dateTime, nl11] = 0.1; networkCoverage[dateTime, nl12] = 0.2; networkCoverage[dateTime, nl13] = 0.3; // test the exact networklocation Assert.AreEqual(0.1, networkCoverage.Evaluate(dateTime, nl11)); Assert.AreEqual(0.2, networkCoverage.Evaluate(dateTime, nl12)); Assert.AreEqual(0.3, networkCoverage.Evaluate(dateTime, nl13)); INetworkLocation nl21 = new NetworkLocation(network.Branches[0], 0.0); INetworkLocation nl22 = new NetworkLocation(network.Branches[0], 100.0); INetworkLocation nl23 = new NetworkLocation(network.Branches[1], 0.0); INetworkLocation nl24 = new NetworkLocation(network.Branches[1], 200.0); // test for networklocations at same location but other instances // branch and offset nl21 equals nl11 Assert.AreEqual(0.1, networkCoverage.Evaluate(dateTime, nl21)); // branch and offset nl22 equals nl12 Assert.AreEqual(0.2, networkCoverage.Evaluate(dateTime, nl22)); // test for value at new location with constant interpolation (1 values available at branch) // expect value of nl13 to be set for complete branches[1] Assert.AreEqual(0.3, networkCoverage.Evaluate(dateTime, nl23)); Assert.AreEqual(0.3, networkCoverage.Evaluate(dateTime, nl24)); // test for interpolation INetworkLocation nl1 = new NetworkLocation(network.Branches[0], 50.0); Assert.AreEqual(0.15, networkCoverage.Evaluate(dateTime, nl1), 1e-6); } [Test] public void AnotherInterpolationTime() { var network = CreateNetwork(); var dateTime = DateTime.Now; var networkCoverage = new NetworkCoverage("test", true) { Network = network }; networkCoverage[dateTime, new NetworkLocation(network.Branches[0], 10.0)] = 0.1; networkCoverage[dateTime, new NetworkLocation(network.Branches[0], 90.0)] = 0.9; // at the exact locations Assert.AreEqual(0.1, networkCoverage.Evaluate(dateTime, new NetworkLocation(network.Branches[0], 10.0)), 1e-6); Assert.AreEqual(0.9, networkCoverage.Evaluate(dateTime, new NetworkLocation(network.Branches[0], 90.0)), 1e-6); // at start and end outside the locations Assert.AreEqual(0.10, networkCoverage.Evaluate(dateTime, new NetworkLocation(network.Branches[0], 5.0)), 1e-6); Assert.AreEqual(0.90, networkCoverage.Evaluate(dateTime, new NetworkLocation(network.Branches[0], 95.0)), 1e-6); // in between the 2 locations Assert.AreEqual(0.35, networkCoverage.Evaluate(dateTime, new NetworkLocation(network.Branches[0], 35.0)), 1e-6); } [Test] public void AnotherInterpolationNoTime() { var network = CreateNetwork(); INetworkCoverage networkCoverage = new NetworkCoverage { Network = network }; networkCoverage[new NetworkLocation(network.Branches[0], 10.0)] = 0.1; networkCoverage[new NetworkLocation(network.Branches[0], 90.0)] = 0.9; networkCoverage.Locations.ExtrapolationType = ExtrapolationType.Constant; networkCoverage.Locations.InterpolationType = InterpolationType.Linear; // at the exact locations Assert.AreEqual(0.1, networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 10.0))); Assert.AreEqual(0.9, networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 90.0))); // at start and end outside the locations Assert.AreEqual(0.10, networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 5.0))); Assert.AreEqual(0.90, networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 95.0)), 1e-6); // in between the 2 locations Assert.AreEqual(0.35, networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 35.0)), 1e-6); } [Test] public void GetTimeSeriesForCoverageOnLocation() { var network = CreateNetwork(); //set up a coverage on one location for three moments INetworkCoverage networkCoverage = new NetworkCoverage { Network = network, IsTimeDependent = true }; var networkLocation = new NetworkLocation(network.Branches[0], 0); for (var i = 1; i < 4; i++) { networkCoverage[new DateTime(2000, 1, i), networkLocation] = (double)i; } //filter the function for the networkLocation IFunction filteredCoverage = networkCoverage.GetTimeSeries(networkLocation); Assert.AreEqual(3, filteredCoverage.Components[0].Values.Count); Assert.AreEqual(1, filteredCoverage.Arguments.Count); Assert.AreEqual(filteredCoverage.Arguments[0].Values, networkCoverage.Time.Values); } [Test] public void GetTimeSeriesForCoverageOnCoordinate() { var network = CreateNetwork(); //set up a coverage on one location for three moments INetworkCoverage networkCoverage = new NetworkCoverage { Network = network, IsTimeDependent = true }; var networkLocation = new NetworkLocation(network.Branches[0], 0); for (int i = 1; i < 4; i++) { networkCoverage[new DateTime(2000, 1, i), networkLocation] = (double)i; } //filter the function for the networkLocation IFunction filteredCoverage = networkCoverage.GetTimeSeries(networkLocation.Geometry.Coordinate); Assert.AreEqual(3, filteredCoverage.Components[0].Values.Count); Assert.AreEqual(1, filteredCoverage.Arguments.Count); Assert.AreEqual(filteredCoverage.Arguments[0].Values, networkCoverage.Time.Values); } [Test] public void GenerageSegmentsWhenLocationsAreAdded() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage { Network = network }; networkCoverage[new NetworkLocation(network.Branches[0], 10.0)] = 0.1; networkCoverage[new NetworkLocation(network.Branches[0], 50.0)] = 0.5; networkCoverage[new NetworkLocation(network.Branches[0], 90.0)] = 0.9; Assert.AreEqual(3, networkCoverage.Segments.Values.Count); } [Test] public void GenerateSegmentPerLocation() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentPerLocation }; networkCoverage[new NetworkLocation(network.Branches[0], 10.0)] = 0.1; networkCoverage[new NetworkLocation(network.Branches[0], 50.0)] = 0.5; networkCoverage[new NetworkLocation(network.Branches[0], 90.0)] = 0.9; Assert.AreEqual(3, networkCoverage.Segments.Values.Count); // [--10--------------50-------------------------------90---] // [----------][-----------------------][-------------------] // 0 30 70 100 Assert.AreEqual(0, networkCoverage.Segments.Values[0].Offset, 1.0e-6); Assert.AreEqual(30, networkCoverage.Segments.Values[0].EndOffset, 1.0e-6); Assert.AreEqual(30, networkCoverage.Segments.Values[1].Offset, 1.0e-6); Assert.AreEqual(70, networkCoverage.Segments.Values[1].EndOffset, 1.0e-6); Assert.AreEqual(70, networkCoverage.Segments.Values[2].Offset, 1.0e-6); Assert.AreEqual(100, networkCoverage.Segments.Values[2].EndOffset, 1.0e-6); } [Test] public void GenerateSegmentPerLocationOrderModified() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentPerLocation }; var valueAt10 = new NetworkLocation(network.Branches[0], 1.0); var valueAt90 = new NetworkLocation(network.Branches[0], 2.0); var valueAt50 = new NetworkLocation(network.Branches[0], 3.0); networkCoverage[valueAt10] = 0.1; networkCoverage[valueAt90] = 0.9; networkCoverage[valueAt50] = 0.5; // change offset and check result are identical to above test GenerateSegmentPerLocation valueAt50.Offset = 50; valueAt90.Offset = 90; valueAt10.Offset = 10; Assert.AreEqual(3, networkCoverage.Segments.Values.Count); // [--10--------------50-------------------------------90---] // [----------][-----------------------][-------------------] // 0 30 70 100 Assert.AreEqual(0, networkCoverage.Segments.Values[0].Offset, 1.0e-6); Assert.AreEqual(30, networkCoverage.Segments.Values[0].EndOffset, 1.0e-6); Assert.AreEqual(30, networkCoverage.Segments.Values[1].Offset, 1.0e-6); Assert.AreEqual(70, networkCoverage.Segments.Values[1].EndOffset, 1.0e-6); Assert.AreEqual(70, networkCoverage.Segments.Values[2].Offset, 1.0e-6); Assert.AreEqual(100, networkCoverage.Segments.Values[2].EndOffset, 1.0e-6); } [Test] public void ChangeOffsetOfNeworkLocationShouldChangeNetworkLocationOrder() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentPerLocation }; var valueAt10 = new NetworkLocation(network.Branches[0], 10.0); var valueAt20 = new NetworkLocation(network.Branches[0], 20.0); var valueAt30 = new NetworkLocation(network.Branches[0], 30.0); var valueAt40 = new NetworkLocation(network.Branches[0], 40.0); networkCoverage[valueAt10] = 0.1; networkCoverage[valueAt20] = 0.2; networkCoverage[valueAt30] = 0.3; networkCoverage[valueAt40] = 0.4; valueAt20.Offset = 35; Assert.AreEqual(valueAt10, networkCoverage.Locations.Values[0]); Assert.AreEqual(valueAt30, networkCoverage.Locations.Values[1]); Assert.AreEqual(valueAt20, networkCoverage.Locations.Values[2]); Assert.AreEqual(valueAt40, networkCoverage.Locations.Values[3]); } [Test] public void GenerateSegmentBetweenLocations() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.RouteBetweenLocations }; networkCoverage[new NetworkLocation(network.Branches[0], 10.0)] = 0.0; networkCoverage[new NetworkLocation(network.Branches[0], 50.0)] = 50.0; networkCoverage[new NetworkLocation(network.Branches[0], 90.0)] = 90.0; Assert.AreEqual(2, networkCoverage.Segments.Values.Count); var firstSegment = networkCoverage.Segments.Values.First(); Assert.AreEqual(10.0, firstSegment.Offset); Assert.AreEqual(40.0, firstSegment.Length); var lastSegment = networkCoverage.Segments.Values.Last(); Assert.AreEqual(50.0, lastSegment.Offset); Assert.AreEqual(40.0, lastSegment.Length); } /// <summary> /// o--------------------o----------------------------------o /// s1 s2 s3 s4 /// [------------][--][--][---------] /// /// 10 90 100 10 90 /// </summary> [Test] [NUnit.Framework.Category(TestCategory.WindowsForms)] public void GenerateSegmentsForNetworkCoverageOnTwoBranches() { var network = CreateNetwork(); var networkCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.RouteBetweenLocations }; networkCoverage[new NetworkLocation(network.Branches[0], 10.0)] = 0.0; networkCoverage[new NetworkLocation(network.Branches[0], 90.0)] = 90.0; networkCoverage[new NetworkLocation(network.Branches[1], 10.0)] = 110.0; networkCoverage[new NetworkLocation(network.Branches[1], 90.0)] = 190.0; Assert.AreEqual(4, networkCoverage.Segments.Values.Count); var segments = networkCoverage.Segments.Values; Assert.AreEqual(network.Branches[0], segments[0].Branch); Assert.AreEqual(10.0, segments[0].Offset); Assert.AreEqual(80.0, segments[0].Length); Assert.AreEqual(network.Branches[0], segments[1].Branch); Assert.AreEqual(90.0, segments[1].Offset); Assert.AreEqual(10.0, segments[1].Length, 1e-6); Assert.AreEqual(network.Branches[1], segments[2].Branch); Assert.AreEqual(0.0, segments[2].Offset); Assert.AreEqual(10.0, segments[2].Length); Assert.AreEqual(network.Branches[1], segments[3].Branch); Assert.AreEqual(10.0, segments[3].Offset); Assert.AreEqual(80.0, segments[3].Length); var networkCoverageLayer = new NetworkCoverageGroupLayer { NetworkCoverage = networkCoverage }; var map = new Map(new Size(1000, 1000)); map.Layers.Add(networkCoverageLayer); NetworkCoverageLayerHelper.SetupRouteNetworkCoverageLayerTheme(networkCoverageLayer, null); // add branch/node layers var branchLayer = new VectorLayer { DataSource = new FeatureCollection { Features = (IList)network.Branches } }; map.Layers.Add(branchLayer); var nodeLayer = new VectorLayer { DataSource = new FeatureCollection { Features = (IList)network.Nodes } }; map.Layers.Add(nodeLayer); MapTestHelper.Show(map); } [Test] public void FilterCoverageDoesNotReturnCoverageWhenReduced() { NetworkCoverage coverage = new NetworkCoverage(); coverage.IsTimeDependent = true; //fix the coverage on a location so we have a funtion with only one argument...time. var filtered = coverage.Filter(new VariableReduceFilter(coverage.Locations)); Assert.IsFalse(filtered is INetworkCoverage); } [Test] public void CloneNetworkCoverage() { var network = CreateNetwork(); INetworkCoverage networkCoverage = new NetworkCoverage { Network = network }; // set values networkCoverage[new NetworkLocation(network.Branches[0], 0.0)] = 0.1; networkCoverage[new NetworkLocation(network.Branches[0], 100.0)] = 0.2; networkCoverage[new NetworkLocation(network.Branches[1], 0.0)] = 0.3; networkCoverage[new NetworkLocation(network.Branches[1], 50.0)] = 0.4; networkCoverage[new NetworkLocation(network.Branches[1], 200.0)] = 0.5; networkCoverage.Locations.Unit = new Unit("networklocation","b/o"); INetworkCoverage clone = (INetworkCoverage)networkCoverage.Clone(); Assert.AreEqual(5, clone.Locations.Values.Count); Assert.AreNotSame(clone.Locations.Values[0], networkCoverage.Locations.Values[0]); Assert.AreNotSame(networkCoverage.Locations.Unit,clone.Locations.Unit); Assert.AreEqual(networkCoverage.Locations.Unit.Name, clone.Locations.Unit.Name); } /* todo make independent on networkeditorplugin or move it to a good place [Test] [Category(TestCategory.WindowsForms)] public void EditRoute() { var network = new HydroNetwork(); var mapControl = new MapControl(); var networkMapLayer = HydroNetworkEditorHelper.CreateMapLayerForHydroNetwork(network); mapControl.Map.Layers.Add(networkMapLayer); HydroNetworkEditorHelper.InitializeNetworkEditor(null, mapControl); // add 2 branches networkMapLayer.ChannelLayer.DataSource.Add(GeometryFromWKT.Parse("LINESTRING (0 0, 100 0)")); networkMapLayer.ChannelLayer.DataSource.Add(GeometryFromWKT.Parse("LINESTRING (100 0, 200 0)")); networkMapLayer.ChannelLayer.DataSource.Add(GeometryFromWKT.Parse("LINESTRING (200 0, 300 0)")); networkMapLayer.ChannelLayer.DataSource.Add(GeometryFromWKT.Parse("LINESTRING (200 0, 200 100)")); network.Branches[0].Name = "branch1"; network.Branches[1].Name = "branch2"; network.Branches[2].Name = "branch3"; network.Branches[3].Name = "branch4"; network.Branches[0].Length = 100; network.Branches[1].Length = 100; network.Branches[2].Length = 100; network.Branches[3].Length = 100; network.Nodes[0].Name = "node1"; network.Nodes[1].Name = "node2"; network.Nodes[2].Name = "node3"; network.Nodes[3].Name = "node4"; network.Nodes[4].Name = "node5"; // add network coverage layer var routeCoverage = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.RouteBetweenLocations }; routeCoverage[new NetworkLocation(network.Branches[0], 10.0)] = 0.0; routeCoverage[new NetworkLocation(network.Branches[0], 90.0)] = 90.0; routeCoverage[new NetworkLocation(network.Branches[1], 90.0)] = 190.0; var networkCoverageLayer = new NetworkCoverageLayer { NetworkCoverage = routeCoverage }; NetworkCoverageLayerHelper.SetupRouteNetworkCoverageLayerTheme(networkCoverageLayer, null); mapControl.Map.Layers.Insert(0, networkCoverageLayer); // add label layers var nodeLabelLayer = new LabelLayer("Nodes") { DataSource = networkMapLayer.NodeLayer.DataSource, LabelColumn = "Name" }; nodeLabelLayer.Style.VerticalAlignment = LabelStyle.VerticalAlignmentEnum.Top; mapControl.Map.Layers.Insert(0, nodeLabelLayer); var branchLabelLayer = new LabelLayer("Branches") { DataSource = networkMapLayer.ChannelLayer.DataSource, LabelColumn = "Name" }; mapControl.Map.Layers.Insert(0, branchLabelLayer); // show all controls var toolsListBox = new ListBox { DataSource = mapControl.Tools, DisplayMember = "Name"}; toolsListBox.SelectedIndexChanged += delegate { mapControl.ActivateTool((IMapTool) toolsListBox.SelectedItem); }; WindowsFormsTestHelper.ShowModal(new List<Control> { toolsListBox, mapControl }, true); } */ [Test] public void EvaluateWithLinearInterpolation() { // create network var network = new Network(); var node1 = new Node("node1"); var node2 = new Node("node2"); network.Nodes.Add(node1); network.Nodes.Add(node2); var branch1 = new Branch("branch1", node1, node2, 100.0) { Geometry = GeometryFromWKT.Parse("LINESTRING (0 0, 100 0)") }; network.Branches.Add(branch1); // create network coverage INetworkCoverage networkCoverage = new NetworkCoverage { Network = network }; networkCoverage.Locations.InterpolationType = InterpolationType.Linear; networkCoverage[new NetworkLocation(network.Branches[0], 0.0)] = 0.0; networkCoverage[new NetworkLocation(network.Branches[0], 100.0)] = 10.0; // evaluate var value = networkCoverage.Evaluate<double>(50.0, 0.0); value.Should().Be.EqualTo(5); // linear interpolation } [Test] public void EvaluateWithConstantInterpolation() { // create network var network = new Network(); var node1 = new Node("node1"); var node2 = new Node("node2"); network.Nodes.Add(node1); network.Nodes.Add(node2); var branch1 = new Branch("branch1", node1, node2, 100.0) { Geometry = GeometryFromWKT.Parse("LINESTRING (0 0, 100 0)") }; network.Branches.Add(branch1); // create network coverage INetworkCoverage networkCoverage = new NetworkCoverage { Network = network }; networkCoverage.Locations.InterpolationType = InterpolationType.Constant; networkCoverage[new NetworkLocation(network.Branches[0], 0.0)] = 0.0; networkCoverage[new NetworkLocation(network.Branches[0], 100.0)] = 10.0; // evaluate var value = networkCoverage.Evaluate<double>(60.0, 0.0); value.Should().Be.EqualTo(10.0); // constant interpolation } [Test] public void EvaluateCoordinateOnTimeFilteredCoverage() { // create network var network = new Network(); var node1 = new Node("node1"); var node2 = new Node("node2"); network.Nodes.Add(node1); network.Nodes.Add(node2); var branch1 = new Branch("branch1", node1, node2, 100.0) { Geometry = GeometryFromWKT.Parse("LINESTRING (0 0, 100 0)") }; network.Branches.Add(branch1); // create network coverage INetworkCoverage networkCoverage = new NetworkCoverage("",true) { Network = network }; var time0 = new DateTime(2000); networkCoverage[time0, new NetworkLocation(network.Branches[0], 0.0)] = 5.0; networkCoverage[time0, new NetworkLocation(network.Branches[0], 100.0)] = 10.0; networkCoverage[new DateTime(2001), new NetworkLocation(network.Branches[0], 0.0)] = 20.0; networkCoverage[new DateTime(2001), new NetworkLocation(network.Branches[0], 100.0)] = 30.0; networkCoverage = (INetworkCoverage) networkCoverage.FilterTime(time0); // evaluate var value = networkCoverage.Evaluate(new Coordinate(1, 0)); value.Should().Be.EqualTo(5.0*1.01); // constant interpolation } [Test] public void SegmentsForTimeFilteredCoverage() { var network = CreateNetwork(); var dateTime = DateTime.Now; var networkCoverage = new NetworkCoverage("test", true) { Network = network }; // test for defaultvalue // set values for only one t. INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 0.0); INetworkLocation nl12 = new NetworkLocation(network.Branches[0], 100.0); INetworkLocation nl13 = new NetworkLocation(network.Branches[1], 100.0); networkCoverage[dateTime, nl11] = 0.1; networkCoverage[dateTime, nl12] = 0.2; networkCoverage[dateTime, nl13] = 0.3; //action! filter on t1 var filtered = (INetworkCoverage)networkCoverage.FilterTime(dateTime); //segments should not be affected Assert.AreEqual(networkCoverage.Segments.Values.Count, filtered.Segments.Values.Count); } [Test] public void GeometryForCoverage() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 200)); var networkCoverage = new NetworkCoverage { Network = network }; // test for defaultvalue // set values for only one t. INetworkLocation networkLocation1 = new NetworkLocation(network.Branches[0], 50.0); INetworkLocation networkLocation2 = new NetworkLocation(network.Branches[1], 50.0); networkCoverage[networkLocation1] = 0.1; networkCoverage[networkLocation2] = 0.2; //envelope is based on network locations now Assert.AreEqual(new GeometryCollection(new[] { networkLocation1.Geometry, networkLocation2.Geometry }), networkCoverage.Geometry); } [Test] public void GeometryForTimeFilteredCoverage() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 200)); var dateTime = DateTime.Now; var networkCoverage = new NetworkCoverage("test", true) { Network = network }; // test for defaultvalue // set values for only one t. INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 0.0); INetworkLocation nl12 = new NetworkLocation(network.Branches[0], 100.0); INetworkLocation nl13 = new NetworkLocation(network.Branches[1], 100.0); networkCoverage[dateTime, nl11] = 0.1; networkCoverage[dateTime, nl12] = 0.2; networkCoverage[dateTime, nl13] = 0.3; //action! filter on t1 var filtered = networkCoverage.FilterTime(dateTime); //segments should not be affected Assert.AreEqual(networkCoverage.Geometry.EnvelopeInternal, filtered.Geometry.EnvelopeInternal); } [Test] public void AllTimeValuesForFilteredCoverage() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 200)); var networkCoverage = new NetworkCoverage("test", true) { Network = network }; // test for defaultvalue //set values for 2 times var times = new[] { 1, 2 }.Select(i => new DateTime(2000, 1, i)).ToList(); foreach (var time in times) { INetworkLocation nl11 = new NetworkLocation(network.Branches[0], 0.0); networkCoverage[time, nl11] = 0.3; } var filteredCoverage = networkCoverage.FilterTime(times[0]); Assert.AreEqual(times, filteredCoverage.Time.AllValues); } [Test] public void DoesNotBubbleEventsFromNetwork() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 200)); var networkCoverage = new NetworkCoverage("test", true) { Network = network }; (networkCoverage as INotifyPropertyChanged).PropertyChanged += (s, e) => { Assert.Fail("No Bubbling please!"); }; network.Nodes[0].Name = "kees"; } [Test] public void NetworkCoverageLocationsAreUpdatedWhenBranchGeometryChanges() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0)); var networkCoverage = new NetworkCoverage { Network = network }; //define a point halfway the branch IBranch firstBranch = network.Branches[0]; networkCoverage[new NetworkLocation(firstBranch, 50)] = 2.0; //make sure we are 'initialized' (CODE SMELL SNIFF UGH) Assert.AreEqual(1, networkCoverage.Locations.Values.Count); //change the branch geometry firstBranch.Length = 200; firstBranch.Geometry = new LineString(new[] { new Coordinate(0, 0), new Coordinate(200, 0) }); //assert the coverage scaled along..so the point should now be at 100 Assert.AreEqual(100, networkCoverage.Locations.Values[0].Offset); } [Test] public void NetworkCoverageUpdatesWhenBranchIsDeleted() { //network 2 branches var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 100)); var networkCoverage = new NetworkCoverage { Network = network }; //set values on the second branch IBranch secondBranch = network.Branches[1]; networkCoverage[new NetworkLocation(secondBranch, 1)] = 10.0; //remove the branch network.Branches.Remove(secondBranch); //check the coverage updated Assert.AreEqual(0, networkCoverage.Locations.Values.Count); } [Test] public void CloneNetworkCoverageWithTwoComponents() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 100)); var f = new NetworkCoverage { Network = network }; f.Components.Add(new Variable<string>("s")); var firstBranch = network.Branches[0]; f[new NetworkLocation(firstBranch, 50)] = new object[] { 2.0, "test" }; var fClone = f.Clone(); Assert.AreEqual(f.Components[0].Values[0], ((Function)fClone).Components[0].Values[0]); Assert.AreEqual(f.Components[1].Values[0], ((Function)fClone).Components[1].Values[0]); } [Test] public void EvaluateWithinBranchPerformsProperInterAndExtrapolation() { //network 2 branches var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(100, 0), new Point(100, 100)); var networkCoverage = new NetworkCoverage { Network = network }; IBranch branch = network.Branches[0]; networkCoverage[new NetworkLocation(branch, 1)] = 1.0; networkCoverage[new NetworkLocation(branch, 2)] = 2.0; networkCoverage[new NetworkLocation(branch, 3)] = 3.0; var location0 = new NetworkLocation(branch, 0); var location1 = new NetworkLocation(branch, 1.4); var location2 = new NetworkLocation(branch, 2.4); var location3 = new NetworkLocation(branch, 3.1); var locations = networkCoverage.GetLocationsForBranch(branch); locations.Insert(0, location0); locations.Insert(2, location1); locations.Insert(4, location2); locations.Insert(6, location3); IList<double> results; networkCoverage.Locations.ExtrapolationType = ExtrapolationType.Constant; networkCoverage.Locations.InterpolationType = InterpolationType.Linear; results = networkCoverage.EvaluateWithinBranch(locations); results[0].Should("1").Be.EqualTo(1.0); results[2].Should("2").Be.EqualTo(1.4); results[4].Should("3").Be.EqualTo(2.4); results[6].Should("4").Be.EqualTo(3.0); /* * Linear extrapolation is not support until the 'normal' evaluate does this also to prevent differences networkCoverage.Locations.ExtrapolationType = ExtrapolationType.Linear; networkCoverage.Locations.InterpolationType = InterpolationType.Constant; results = networkCoverage.EvaluateWithinBranch(locations); results[0].Should("5").Be.EqualTo(0.0); results[2].Should("6").Be.EqualTo(1.0); results[4].Should("7").Be.EqualTo(2.0); results[6].Should("8").Be.EqualTo(3.1); */ } [Test] [ExpectedException(typeof(NotSupportedException), ExpectedMessage = "Evaluation failed : Currently only constant Extrapolation for locations is supported.")] public void EvaluateWithinBranchThrowsExceptionForNonConstantExtraPolation() { var network = RouteHelperTest.GetSnakeNetwork(false, 1); var networkCoverage = new NetworkCoverage { Network = network }; IBranch branch = network.Branches[0]; networkCoverage[new NetworkLocation(branch, 10)] = 1.0; networkCoverage[new NetworkLocation(branch, 20)] = 2.0; networkCoverage[new NetworkLocation(branch, 30)] = 3.0; networkCoverage.Locations.ExtrapolationType = ExtrapolationType.Linear; networkCoverage.EvaluateWithinBranch(new[] { new NetworkLocation(branch, 5) }); } [Test] [ExpectedException(typeof(NotSupportedException), ExpectedMessage = "Evaluation failed : currently only constant Extrapolation for locations is supported.")] public void EvaluateThrowsExceptionWhenEvaluatingWithNonConstantExtrapolation() { //network 1 branch var network = RouteHelperTest.GetSnakeNetwork(false, 1); var networkCoverage = new NetworkCoverage { Network = network }; //set values on the branch IBranch firstBranch = network.Branches[0]; networkCoverage[new NetworkLocation(firstBranch, 10)] = 10.0; networkCoverage[new NetworkLocation(firstBranch, 20)] = 10.0; //evaluate before the first location (extrapolation) networkCoverage.Locations.ExtrapolationType = ExtrapolationType.Linear; networkCoverage.Evaluate(new NetworkLocation(firstBranch, 5)); } [Test] public void ClearNetworkOnPropertyChangedShouldBeOK() { //relates to issue 5019 where flow model sets network to null after which NPC is handled in the coverage. var network = RouteHelperTest.GetSnakeNetwork(false, 1); INetworkCoverage networkCoverage = null;//= new NetworkCoverage { Network = network }; //be sure to subscribe before the coverage subscribes..otherwise the problem does not emerge ((INotifyPropertyChanged)network).PropertyChanged += (s, e) => { //when setting network to null subscribtion is removed for the NEXT change networkCoverage.Network = null; }; networkCoverage = new NetworkCoverage { Network = network }; network.BeginEdit("Delete"); } [Test] [NUnit.Framework.Category(TestCategory.Integration)] public void SplittingABranchMovesExistingPoints() { //unfortunately this test cannot be defined near networkcoverage because the splitting functionality is defined in HydroNH iso NH var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(0, 100)); var channelToSplit = network.Branches.First(); var networkCoverage = new NetworkCoverage { Network = network }; //set values at 0..10...90 etc networkCoverage.Locations.AddValues(Enumerable.Range(0, 10).Select(i => new NetworkLocation(channelToSplit, i * 10))); NetworkHelper.SplitBranchAtNode(channelToSplit, 50); //points 0..10.20.30.40 are on branch 1 //points 0..10.20.30.40 are on branch 2 Assert.AreEqual(new[] { 0, 10, 20, 30, 40, 50, 0, 10, 20, 30, 40 }, networkCoverage.Locations.Values.Select(l => l.Offset).ToList()); //take 5 ;) var newChannel = network.Branches.ElementAt(1); Assert.IsTrue(networkCoverage.Locations.Values.Take(6).All(l => l.Branch == channelToSplit)); Assert.IsTrue(networkCoverage.Locations.Values.Skip(6).Take(5).All(l => l.Branch == newChannel)); } [Test] [NUnit.Framework.Category(TestCategory.Integration)] public void SplittingABranchAddInterpolatedValueAtSplitPoint() { //unfortunately this test cannot be defined near networkcoverage because the splitting functionality is defined in HydroNH iso NH var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(0, 100)); var channelToSplit = network.Branches.First(); var networkCoverage = new NetworkCoverage { Network = network }; //from 1000 to 0 networkCoverage[new NetworkLocation(channelToSplit, 0.0)] = new[] {1000.0}; networkCoverage[new NetworkLocation(channelToSplit, 100.0)] = new[] {0.0}; //split at 50 should add two points var newBranch = NetworkHelper.SplitBranchAtNode(channelToSplit, 50.0).NewBranch; //one at the end of the original Assert.AreEqual(500.0, networkCoverage[new NetworkLocation(channelToSplit, 50.0)]); //one at start of new Assert.AreEqual(500.0, networkCoverage[new NetworkLocation(newBranch, 0.0)]); } [Test] public void SplittingABranchWithNoValuesDoesNotAddPoints() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(0, 100)); var channelToSplit = network.Branches.First(); var networkCoverage = new NetworkCoverage { Network = network }; NetworkHelper.SplitBranchAtNode(channelToSplit, 50.0); //still there should be no values Assert.AreEqual(0, networkCoverage.Locations.Values.Count); } [Test] public void ChangeBranchLengthAfterSplitOfBranchWithNoLocationsDoesNotThrowException() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(0, 100)); var channelToSplit = network.Branches.First(); //do not remove network coverage..the test is that NO exception occurs when the branch is split var networkCoverage = new NetworkCoverage { Network = network }; var result = NetworkHelper.SplitBranchAtNode(channelToSplit, 50.0); var newChannel = result.NewBranch; newChannel.Geometry = new LineString(new[] { new Coordinate(-10, 0), new Coordinate(50, 0) }); } [Test] public void MergingABranchesRemovesDataOnAffectedBranches() { //L-shaped network var network = RouteHelperTest.GetSnakeNetwork(false,new Point(0, 0), new Point(0, 100), new Point(100, 100)); var networkCoverage = new NetworkCoverage { Network = network }; //add locations on both branches var networkLocation = new NetworkLocation(network.Branches[0], 50); var networkLocation2 = new NetworkLocation(network.Branches[1], 50); networkCoverage[networkLocation] = 1.0d; networkCoverage[networkLocation2] = 21.0d; //merge the branches/remove the node NetworkHelper.MergeNodeBranches(network.Nodes[1], network); //check the values got removed Assert.AreEqual(0, networkCoverage.Components[0].Values.Count); } [Test] public void SplittingABranchShouldGiveSameValuesAtIntermediatePoints() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(0, 100)); var networkCoverage = new NetworkCoverage { Network = network }; networkCoverage.Components[0].InterpolationType = InterpolationType.Linear; networkCoverage.Components[0].ExtrapolationType = ExtrapolationType.Constant; //add locations var networkLocation1 = new NetworkLocation(network.Branches[0], 50); var networkLocation2 = new NetworkLocation(network.Branches[0], 100); networkCoverage[networkLocation1] = 1.0d; networkCoverage[networkLocation2] = 30.0d; double beforeLeft = networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 25)); double beforeRight = networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 75)); //merge the branches/remove the node NetworkHelper.SplitBranchAtNode(network.Branches[0], 60); double afterLeft = networkCoverage.Evaluate(new NetworkLocation(network.Branches[0], 25)); double afterRight = networkCoverage.Evaluate(new NetworkLocation(network.Branches[1], 15)); Assert.AreEqual(beforeLeft, afterLeft); Assert.AreEqual(beforeRight, afterRight); } [Test] public void FireNetworkCollectionChangedWhenNetworkBranchesCollectionChanges() { var network = RouteHelperTest.GetSnakeNetwork(false, new Point(0, 0), new Point(0, 100), new Point(100, 100)); var networkCoverage = new NetworkCoverage { Network = network }; int callCount = 0; networkCoverage.NetworkCollectionChanged += (s, e) => { callCount++; }; network.Branches.Add(new Branch()); Assert.AreEqual(1,callCount); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem77 : ProblemBase { private List<decimal> _primes = new List<decimal>(); private List<Dictionary<decimal, int>> _primeCounts = new List<Dictionary<decimal, int>>(); public override string ProblemName { get { return "77: Prime summations"; } } public override string GetAnswer() { _primeCounts.Add(new Dictionary<decimal, int>()); return PrimeSummations(5000).ToString(); } private int PrimeSummations(decimal count) { decimal num = 1; do { for (int primeIndex = 0; primeIndex < _primes.Count; primeIndex++) { BuildSums(num, primeIndex, num); } if (IsPrime(num)) { _primes.Add(num); _primeCounts.Add(new Dictionary<decimal, int>()); BuildSums(2, _primes.Count - 1, num); } if (GetCount(_primes.Count - 1, num) >= count) { return (int)num; } num++; } while (true); } private void BuildSums(decimal weight, int primeIndex, decimal num) { for (decimal weightIndex = weight; weightIndex <= num; weightIndex++) { decimal tempWeight = 0; while (tempWeight <= weightIndex) { int count = GetCount(primeIndex, weightIndex); if (tempWeight == weightIndex) { SetCount(primeIndex, weightIndex, count + 1); } else { SetCount(primeIndex, weightIndex, count + GetCount(primeIndex - 1, weightIndex - tempWeight)); } tempWeight += _primes[primeIndex]; } } } private int GetCount(int primeIndex, decimal weight) { primeIndex += 1; if (!_primeCounts[primeIndex].ContainsKey(weight)) { _primeCounts[primeIndex].Add(weight, 0); } return _primeCounts[primeIndex][weight]; } private void SetCount(int primeIndex, decimal weight, int value) { primeIndex += 1; if (!_primeCounts[primeIndex].ContainsKey(weight)) { _primeCounts[primeIndex].Add(weight, value); } else { _primeCounts[primeIndex][weight] = value; } } private bool IsPrime(decimal num) { if (num == 1) { return false; } else if (num == 2) { return true; } else if (num % 2 == 0) { return false; } else { for (ulong factor = 3; factor <= Math.Sqrt((double)num); factor += 2) { if (num % factor == 0) { return false; } } } return true; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using Moq; using Timeclock.Services; using TimeClock.Data; using TimeClock.Data.Models; namespace WebApplication1.Tests { /// <summary> /// Employee should be able to clock in, out and for lunch. /// Employee can not change clock status to their current status(IE can not clock in if already clocked in) /// Emplo /// </summary> [TestClass] public class EmployeeServicesTest { internal static class ServicesTestHelper { internal static IEmployeeService CreateService( Mock<TimeClockContext> context = null, Mock<DbSet<Employee>> employeData = null) { Mock<DbSet<Employee>> mockSet = employeData ?? new Mock<DbSet<Employee>>(); Mock<TimeClockContext> mockContext = context ?? new Mock<TimeClockContext>(); var data = new List<Employee>() { new Employee() {EmployeeId = 1, FirstName = "dylan", LastName = "orr", PunchStatus = TimePunchStatus.PunchedIn}, new Employee() {EmployeeId = 2, FirstName = "Tyler", LastName = "Mork", PunchStatus = TimePunchStatus.PunchedOut} }.AsQueryable(); mockSet.As<IQueryable<Employee>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Employee>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Employee>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Employee>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); mockContext.Setup(c => c.Employees).Returns(mockSet.Object); mockContext.Setup(m => m.Employees).Returns(mockSet.Object); mockSet.Setup(m => m.Find(It.IsAny<object[]>())) .Returns<object[]>(ids => mockContext.Object.Employees.FirstOrDefault(e => e.EmployeeId == (int)ids[0])); return new EmployeeService(mockContext.Object); } internal static Employee CreateEmployee(TimePunchStatus status = TimePunchStatus.PunchedIn) { Employee employee = new Employee() { EmployeeId = 1, FirstName = "Dylan", LastName = "Orr", PunchStatus = status }; return employee; } } [TestClass] public class TheClockMethod { private Mock<TimeClockContext> _context; [TestInitialize] public void Initialize() { _context = new Mock<TimeClockContext>(); } [TestMethod] public void Returns_True_When_ClockedOut_Employee_ClocksIn() { Employee employee = ServicesTestHelper.CreateEmployee(TimePunchStatus.PunchedOut); IEmployeeService service = ServicesTestHelper.CreateService(context: _context); bool success = service.ChangeClockStatus(employee, TimePunchStatus.PunchedIn); Assert.IsTrue(success); } [TestMethod] public void Returns_False_When_ClockedOut_Employee_ClocksOut() { Employee employee = ServicesTestHelper.CreateEmployee(TimePunchStatus.PunchedOut); IEmployeeService service = ServicesTestHelper.CreateService(); var success = service.ChangeClockStatus(employee, TimePunchStatus.PunchedOut); Assert.IsFalse(success); } [TestMethod] public void Sets_Employee_Current_Status_To_Last_Punch() { Employee employee = ServicesTestHelper.CreateEmployee(); IEmployeeService service = ServicesTestHelper.CreateService(); service.ChangeClockStatus(employee, TimePunchStatus.PunchedOut); Assert.IsTrue(employee.PunchStatus == TimePunchStatus.PunchedOut); } [TestMethod] public void Sets_Employee_Last_Punch_Time_To_Last_Punch() { Employee employee = ServicesTestHelper.CreateEmployee(); IEmployeeService service = ServicesTestHelper.CreateService(); service.ChangeClockStatus(employee, TimePunchStatus.PunchedOut); var span = (DateTime.Now - employee.LastPunchTime).Value.Seconds <= 100; Assert.IsTrue(span); } [TestMethod] public void Saves_Current_Punch_Status() { Employee employee = ServicesTestHelper.CreateEmployee(); IEmployeeService service = ServicesTestHelper.CreateService(context: _context); service.ChangeClockStatus(employee, TimePunchStatus.PunchedOut); _context.Verify(m => m.SaveChanges(), Times.Once); Assert.IsTrue(employee.PunchStatus == TimePunchStatus.PunchedOut); } } [TestClass] public class TheCreateEmployeeMethod { private Mock<TimeClockContext> _context; private Mock<DbSet<Employee>> _employees; [TestInitialize] public void Initialize() { _employees = new Mock<DbSet<Employee>>(); _context = new Mock<TimeClockContext>(); } [TestMethod] public void Add_Employee_To_Context() { Employee employee = ServicesTestHelper.CreateEmployee(); IEmployeeService service = ServicesTestHelper.CreateService(context: _context, employeData: _employees); service.CreateEmployee(employee); //Make sure an employee is added to the context, and saveChanges is called _employees.Verify(m => m.Add(It.IsAny<Employee>()), Times.Once); _context.Verify(m => m.SaveChanges(), Times.Once); } } [TestClass] public class TheGetEmployeeListMethod { private Mock<TimeClockContext> _context; private Mock<DbSet<Employee>> _employees; [TestInitialize] public void Initialize() { _employees = new Mock<DbSet<Employee>>(); _context = new Mock<TimeClockContext>(); var data = new List<Employee>() { new Employee() {FirstName = "dylan", LastName = "orr"}, new Employee() {FirstName = "Tyler", LastName = "Mork"} }.AsQueryable(); _employees.As<IQueryable<Employee>>().Setup(m => m.Provider).Returns(data.Provider); _employees.As<IQueryable<Employee>>().Setup(m => m.Expression).Returns(data.Expression); _employees.As<IQueryable<Employee>>().Setup(m => m.ElementType).Returns(data.ElementType); _employees.As<IQueryable<Employee>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); _context.Setup(c => c.Employees).Returns(_employees.Object); } [TestMethod] public void Return_List_Of_Employees_In_Context() { var service = ServicesTestHelper.CreateService(_context); List<Employee> employees = service.GetEmployeeList(); Assert.IsTrue(employees.Count == 2); } } [TestClass] public class TheFindByIdMethod { private Mock<DbSet<Employee>> _employees; private Mock<TimeClockContext> _context; [TestInitialize] public void Initialize() { _employees = new Mock<DbSet<Employee>>(); _context = new Mock<TimeClockContext>(); } [TestMethod] public void GivenAValidIdShouldReturnEmployee() { IEmployeeService service = ServicesTestHelper.CreateService(); Employee employee = service.FindById(1); Assert.IsNotNull(employee); } [TestMethod] public void GivenAnIdofONeShouldReturnEmployeeOne() { IEmployeeService service = ServicesTestHelper.CreateService(); Employee employee = service.FindById(1); Assert.IsTrue(employee.EmployeeId == 1); } [TestMethod] public void GivenAnInvalidIdShouldReturnNull() { IEmployeeService service = ServicesTestHelper.CreateService(); Employee employee = service.FindById(3); Assert.IsNull(employee); } } [TestClass] public class TheUpdateEmployeeMethod { private Mock<DbSet<Employee>> _employees; private Mock<TimeClockContext> _context; [TestInitialize] public void Initialize() { _employees = new Mock<DbSet<Employee>>(); _context = new Mock<TimeClockContext>(); } [TestMethod] public void ShouldUpdateCustomerInContext() { Employee employee = ServicesTestHelper.CreateEmployee(); IEmployeeService service = ServicesTestHelper.CreateService(context: _context, employeData: _employees); service.UpdateEmployee(employee); _context.Verify(m => m.SaveChanges(), Times.Once); } } [TestClass] public class TheGetByStatusMethod { private Mock<DbSet<Employee>> _employees; private Mock<TimeClockContext> _context; [TestInitialize] public void Initialize() { _employees = new Mock<DbSet<Employee>>(); _context = new Mock<TimeClockContext>(); } [TestMethod] public void Given_A_Status_Should_return_Employees_Of_That_Status() { IEmployeeService service = ServicesTestHelper.CreateService(); List<Employee> employees = service.FindByStatus(TimePunchStatus.PunchedIn); employees.ForEach(e => Assert.IsTrue(e.PunchStatus == TimePunchStatus.PunchedIn)); } } } }
namespace UnityAtoms { /// <summary> /// Enumeration for logical operators for `AtomCondition` Predicates /// </summary> public enum AtomConditionOperators { And, Or } }
namespace ControleEstacionamento.Persistence.Entity.Migrations { using System; using System.Data.Entity.Migrations; public partial class AlternadoCampoMovimentacaoVeiculo : DbMigration { public override void Up() { AlterColumn("dbo.tbl_movimentacao_veiculo", "mov_saida", c => c.DateTime()); } public override void Down() { AlterColumn("dbo.tbl_movimentacao_veiculo", "mov_saida", c => c.DateTime(nullable: false)); } } }
using Allyn.Domain.Models.Front; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Allyn.Domain.Specifications.Definite { class OrganizeIntegralEqualSpecification : SpecificationEqualMember<int, Organize> { #region Constructors public OrganizeIntegralEqualSpecification(int integral) : base(integral) { } #endregion public override Expression<Func<Organize, bool>> GetExpression() { return u => u.Integral <= Value; } } }
// talis.xivplugin.twintania // Settings.cs using FFXIVAPP.Common.Helpers; using FFXIVAPP.Common.Models; using FFXIVAPP.Common.Utilities; using NLog; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Diagnostics; using System.Drawing; using System.Runtime.CompilerServices; using System.Windows.Media; using Color = System.Windows.Media.Color; using ColorConverter = System.Windows.Media.ColorConverter; using FontFamily = System.Drawing.FontFamily; namespace talis.xivplugin.twintania.Properties { internal class Settings : ApplicationSettingsBase, INotifyPropertyChanged { private static Settings _default; public static Settings Default { get { return _default ?? (_default = ((Settings) (Synchronized(new Settings())))); } } public override void Save() { XmlHelper.DeleteXmlNode(Constants.XSettings, "Setting"); if (Constants.Settings.Count == 0) { } DefaultSettings(); foreach (var item in Constants.Settings) { try { var xKey = item; var xValue = Default[xKey].ToString(); var keyPairList = new List<XValuePair> { new XValuePair { Key = "Value", Value = xValue } }; XmlHelper.SaveXmlNode(Constants.XSettings, "Settings", "Setting", xKey, keyPairList); } catch (Exception ex) { Logging.Log(LogManager.GetCurrentClassLogger(), "", ex); } } Constants.XSettings.Save(Constants.BaseDirectory + "Settings.xml"); } private void DefaultSettings() { Constants.Settings.Clear(); Constants.Settings.Add("ShowTwintaniaHPWidgetOnLoad"); Constants.Settings.Add("TwintaniaHPWidgetUseNAudio"); Constants.Settings.Add("TwintaniaHPWidgetUseSoundCaching"); Constants.Settings.Add("TwintaniaHPWidgetTop"); Constants.Settings.Add("TwintaniaHPWidgetLeft"); Constants.Settings.Add("TwintaniaHPWidgetWidth"); Constants.Settings.Add("TwintaniaHPWidgetHeight"); Constants.Settings.Add("TwintaniaHPWidgetUIScale"); Constants.Settings.Add("TwintaniaHPWidgetEnrageTime"); Constants.Settings.Add("TwintaniaHPWidgetEnrageVolume"); Constants.Settings.Add("TwintaniaHPWidgetEnrageCounting"); Constants.Settings.Add("TwintaniaHPWidgetEnrageAlertFile"); Constants.Settings.Add("TwintaniaHPWidgetDivebombTimeFast"); Constants.Settings.Add("TwintaniaHPWidgetDivebombTimeSlow"); Constants.Settings.Add("TwintaniaHPWidgetDivebombCounting"); Constants.Settings.Add("TwintaniaHPWidgetDivebombVolume"); Constants.Settings.Add("TwintaniaHPWidgetDivebombAlertFile"); Constants.Settings.Add("TwintaniaHPWidgetTwisterVolume"); Constants.Settings.Add("TwintaniaHPWidgetClickThroughEnabled"); Constants.Settings.Add("TwintaniaHPWidgetOpacity"); } public new void Reset() { DefaultSettings(); foreach (var key in Constants.Settings) { var settingsProperty = Default.Properties[key]; if (settingsProperty == null) { continue; } var value = settingsProperty.DefaultValue.ToString(); SetValue(key, value); } } public static void SetValue(string key, string value) { try { var type = Default[key].GetType() .Name; switch (type) { case "Boolean": Default[key] = Convert.ToBoolean(value); break; case "Color": var cc = new ColorConverter(); var color = cc.ConvertFrom(value); Default[key] = color ?? Colors.Black; break; case "Double": Default[key] = Convert.ToDouble(value); break; case "Font": var fc = new FontConverter(); var font = fc.ConvertFromString(value); Default[key] = font ?? new Font(new FontFamily("Microsoft Sans Serif"), 12); break; case "Int32": Default[key] = Convert.ToInt32(value); break; default: Default[key] = value; break; } } catch (SettingsPropertyNotFoundException ex) { Logging.Log(LogManager.GetCurrentClassLogger(), "", ex); } catch (SettingsPropertyWrongTypeException ex) { Logging.Log(LogManager.GetCurrentClassLogger(), "", ex); } } #region Property Bindings (Settings) [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("#FF000000")] public Color ChatBackgroundColor { get { return ((Color) (this["ChatBackgroundColor"])); } set { this["ChatBackgroundColor"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("#FF800080")] public Color TimeStampColor { get { return ((Color) (this["TimeStampColor"])); } set { this["TimeStampColor"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("Microsoft Sans Serif, 12pt")] public Font ChatFont { get { return ((Font) (this["ChatFont"])); } set { this["ChatFont"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("100")] public Double Zoom { get { return ((Double) (this["Zoom"])); } set { this["Zoom"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("True")] public bool ShowTwintaniaHPWidgetOnLoad { get { return ((bool) (this["ShowTwintaniaHPWidgetOnLoad"])); } set { this["ShowTwintaniaHPWidgetOnLoad"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("100")] public int TwintaniaHPWidgetTop { get { return ((int) (this["TwintaniaHPWidgetTop"])); } set { this["TwintaniaHPWidgetTop"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("500")] public int TwintaniaHPWidgetLeft { get { return ((int) (this["TwintaniaHPWidgetLeft"])); } set { this["TwintaniaHPWidgetLeft"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("250")] public int TwintaniaHPWidgetWidth { get { return ((int) (this["TwintaniaHPWidgetWidth"])); } set { this["TwintaniaHPWidgetWidth"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("450")] public int TwintaniaHPWidgetHeight { get { return ((int) (this["TwintaniaHPWidgetHeight"])); } set { this["TwintaniaHPWidgetHeight"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("1.0")] public string TwintaniaHPWidgetUIScale { get { return ((string) (this["TwintaniaHPWidgetUIScale"])); } set { this["TwintaniaHPWidgetUIScale"] = value; RaisePropertyChanged(); } } [ApplicationScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue(@"<?xml version=""1.0"" encoding=""utf-16""?> <ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <string>0.8</string> <string>0.9</string> <string>1.0</string> <string>1.1</string> <string>1.2</string> <string>1.3</string> <string>1.4</string> <string>1.5</string> </ArrayOfString>")] public StringCollection TwintaniaHPWidgetUIScaleList { get { return ((StringCollection) (this["TwintaniaHPWidgetUIScaleList"])); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("780")] public Double TwintaniaHPWidgetEnrageTime { get { return ((Double) (this["TwintaniaHPWidgetEnrageTime"])); } set { this["TwintaniaHPWidgetEnrageTime"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("100")] public int TwintaniaHPWidgetEnrageVolume { get { return ((int)(this["TwintaniaHPWidgetEnrageVolume"])); } set { this["TwintaniaHPWidgetEnrageVolume"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("True")] public bool TwintaniaHPWidgetEnrageCounting { get { return ((bool)(this["TwintaniaHPWidgetEnrageCounting"])); } set { this["TwintaniaHPWidgetEnrageCounting"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue(@"\AlertSounds\LowHealth.wav")] public string TwintaniaHPWidgetEnrageAlertFile { get { return ((string)(this["TwintaniaHPWidgetEnrageAlertFile"])); } set { this["TwintaniaHPWidgetEnrageAlertFile"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("6.8")] public Double TwintaniaHPWidgetDivebombTimeFast { get { return ((Double) (this["TwintaniaHPWidgetDivebombTimeFast"])); } set { this["TwintaniaHPWidgetDivebombTimeFast"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("47.7")] public Double TwintaniaHPWidgetDivebombTimeSlow { get { return ((Double) (this["TwintaniaHPWidgetDivebombTimeSlow"])); } set { this["TwintaniaHPWidgetDivebombTimeSlow"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("True")] public bool TwintaniaHPWidgetUseNAudio { get { return ((bool) (this["TwintaniaHPWidgetUseNAudio"])); } set { this["TwintaniaHPWidgetUseNAudio"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("True")] public bool TwintaniaHPWidgetUseSoundCaching { get { return ((bool) (this["TwintaniaHPWidgetUseSoundCaching"])); } set { this["TwintaniaHPWidgetUseSoundCaching"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("True")] public bool TwintaniaHPWidgetDivebombCounting { get { return ((bool) (this["TwintaniaHPWidgetDivebombCounting"])); } set { this["TwintaniaHPWidgetDivebombCounting"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("100")] public int TwintaniaHPWidgetDivebombVolume { get { return ((int) (this["TwintaniaHPWidgetDivebombVolume"])); } set { this["TwintaniaHPWidgetDivebombVolume"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue(@"\AlertSounds\LowHealth.wav")] public string TwintaniaHPWidgetDivebombAlertFile { get { return ((string) (this["TwintaniaHPWidgetDivebombAlertFile"])); } set { this["TwintaniaHPWidgetDivebombAlertFile"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("100")] public int TwintaniaHPWidgetTwisterVolume { get { return ((int) (this["TwintaniaHPWidgetTwisterVolume"])); } set { this["TwintaniaHPWidgetTwisterVolume"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("0.7")] public string TwintaniaHPWidgetOpacity { get { return ((string) (this["TwintaniaHPWidgetOpacity"])); } set { this["TwintaniaHPWidgetOpacity"] = value; RaisePropertyChanged(); } } [ApplicationScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue(@"<?xml version=""1.0"" encoding=""utf-16""?> <ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <string>0.5</string> <string>0.6</string> <string>0.7</string> <string>0.8</string> <string>0.9</string> <string>1.0</string> </ArrayOfString>")] public StringCollection TwintaniaHPWidgetOpacityList { get { return ((StringCollection) (this["TwintaniaHPWidgetOpacityList"])); } set { this["TwintaniaHPWidgetOpacityList"] = value; RaisePropertyChanged(); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool TwintaniaHPWidgetClickThroughEnabled { get { return ((bool) (this["TwintaniaHPWidgetClickThroughEnabled"])); } set { this["TwintaniaHPWidgetClickThroughEnabled"] = value; RaisePropertyChanged(); } } #endregion #region Implementation of INotifyPropertyChanged public new event PropertyChangedEventHandler PropertyChanged = delegate { }; private void RaisePropertyChanged([CallerMemberName] string caller = "") { PropertyChanged(this, new PropertyChangedEventArgs(caller)); } #endregion } }
using UnityEngine; using UnityEngine.UI; public class RuntimeOptions : MonoBehaviour { public Button optionsButton; public GameObject optionsPanel; // Use this for initialization void Start () { optionsButton.onClick.AddListener(()=> { optionsPanel.SetActive(!optionsPanel.activeInHierarchy); if(optionsPanel.activeInHierarchy) Time.timeScale = 0; else Time.timeScale = 1; }); } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using Data; namespace Data { public static class SuppliersDB { //public static int SupplierId { get; private set; } //public static SqlConnection GetConnection() //method which needs a call and return // //this will be called in the StateDB (when connection needs to be made) //{ // string connectionString = @"Data Source=localhost\SQLEXPRESS; Initial Catalog = TravelExperts; Integrated Security = True"; // //@ allows you to put the entire path // //regardless of special characters // return new SqlConnection(connectionString); //} public static List<Supplier> GetAllSuppliers() //name in <> has to match a class name { List<Supplier> supplier = new List<Supplier>(); //empty list Supplier sup; //for reading using (SqlConnection connection = TravelExpertsDB.GetConnection()) { string query = "SELECT SupplierID, SupName " + "FROM Suppliers " + "ORDER by SupplierID"; using (SqlCommand cmd = new SqlCommand(query, connection)) { connection.Open(); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { sup = new Supplier(); //empty supplier object //fill with data from the reader sup.SupplierId = (int)reader["SupplierId"]; sup.SupName = reader["SupName"].ToString(); ; supplier.Add(sup); //add to the list } } //cmd object recycled }//connection object recycled return supplier; //----------------------- } //add supplier public static int AddSupplier(Supplier sup) { // create connection using (SqlConnection connection = TravelExpertsDB.GetConnection()) { // create INSERT command // SupplierID is IDENTITY so no value provided string query = "insert into Suppliers(SupplierId, SupName) values(@SupplierId, @SupName)"; using (SqlCommand cmd = new SqlCommand(query, connection)) //string insertStatement = //"INSERT INTO Suppliers(SupplierId, SupName ) " + //"OUTPUT inserted.SupplierId " + //"VALUES(@SupplierId, @SupName)"; //SqlCommand cmd = new SqlCommand(insertStatement, connection); //cmd.Parameters.AddWithValue("@SupplierId", sup.SupplierId); { cmd.Parameters.AddWithValue(" @SupName", sup.SupName); //cmd.Parameters.AddWithValue("@SupplierId"); connection.Open(); // execute insert command and get inserted ID int SupplierId = (int)cmd.ExecuteNonQuery(); if (SupplierId > 0) return SupplierId; else return -1; // retrieve generate customer ID to return //string selectStatement = // "SELECT IDENT_CURRENT('Suppliers')"; // SqlCommand selectCmd = new SqlCommand(selectStatement, connection); // SupplierId = Convert.ToInt32(selectCmd.ExecuteScalar()); // returns single value // // (int) does not work in this case } //catch (Exception ex) //{ // throw ex; //} //finally //{ // connection.Close(); //} } //return custID; } //public static bool DeleteSupplier(Supplier sup) //{ // bool success = false; // // create connection // using (SqlConnection connection = TravelExpertsDB.GetConnection()) // { // // create DELETE command // string deleteStatement = // "DELETE FROM Suppliers " + // "WHERE SupplierID = @SupplierID " + // needed for identification // "AND SupName = @SupName "; // the rest - for optimistic concurrency // SqlCommand cmd = new SqlCommand(deleteStatement, connection); // cmd.Parameters.AddWithValue("@SupplierId", sup.SupplierId); // cmd.Parameters.AddWithValue("@SupName", sup.SupName); // try // { // connection.Open(); // // execute the command // int count = cmd.ExecuteNonQuery(); // // check if successful // if (count > 0) // success = true; // } // catch (Exception ex) // { // throw ex; // } // finally // { // connection.Close(); // } // } // return success; //} } }
using Properties.Core.Objects; // ReSharper disable InconsistentNaming namespace Properties.Infrastructure.Zoopla.Objects { public class ZrtdfPropertyMedia { public string url { get; } public string type { get; } public ZrtdfPropertyMedia(Photo photo) { url = photo.PhotoUrl; type = "image"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using FairyGUI; using DG.Tweening; public class ServerErrorCodeEmitComponent : EmitComponent { private GTextField errorCodeText = null; public ServerErrorCodeEmitComponent() { this.touchable = false; errorCodeText = new GTextField(); errorCodeText.autoSize = AutoSizeType.Both; errorCodeText.color = Color.red; TextFormat tf = errorCodeText.textFormat; tf.color = Color.red; tf.size = 30; errorCodeText.textFormat = tf; AddChild(errorCodeText); } public override void ShowEmit(params object[] args) { base.ShowEmit(args); string errorStr = GameConvert.StringConvert(args[0]); this.SetXY(0, 300); DOTween.To(() => new Vector2(0, 300), val => { this.UpdatePosition(val); }, new Vector2(0, 0), 3f) .SetTarget(this).OnComplete(this.OnCompleted); errorCodeText.text = errorStr; EmitNumberManager.AddChild(this); } void UpdatePosition(Vector2 pos) { this.SetXY(pos.x, pos.y); } void OnCompleted() { EmitNumberManager.RemoveChild(this); EmitNumberManager.ReturnComponent(EmitNumberType.EmitNumberTypeServerErrorCode, this); } }
using System; using Rover.Enums; using Rover.Models; namespace Rover.Commands { /// <summary> /// Move command responsible for increasing the x or y position of the robot relative to its facing position. /// It will only apply the move if it is a valid new position (i.e. within the bounds of the location) /// </summary> public class MoveCommand : RobotCommand { public MoveCommand() : base() { } public override void Execute(Robot robot) { base.Execute(robot); int newX; int newY; switch (robot.CurrentPosition.Facing) { case Facing.E: newX = robot.CurrentPosition.X + 1; newY = robot.CurrentPosition.Y; break; case Facing.N: newX = robot.CurrentPosition.X; newY = robot.CurrentPosition.Y + 1; break; case Facing.W: newX = robot.CurrentPosition.X - 1; newY = robot.CurrentPosition.Y; break; case Facing.S: newX = robot.CurrentPosition.X; newY = robot.CurrentPosition.Y - 1; break; default: throw new InvalidOperationException($"Unknown Facing: {robot.CurrentPosition.Facing}"); } //ignore move if it has reached the boundary if (robot.Plateau.IsInBounds(newX, newY)) { robot.CurrentPosition.X = newX; robot.CurrentPosition.Y = newY; } } } }
#if NETFRAMEWORK using Sentry.PlatformAbstractions; namespace Sentry.Tests.PlatformAbstractions; public class FrameworkInfoNetFxTests { [SkippableFact] public void GetLatest_NotNull() { Skip.If(RuntimeInfo.GetRuntime().IsMono()); var latest = FrameworkInfo.GetLatest(Environment.Version.Major); Assert.NotNull(latest); } [SkippableFact] public void GetInstallations_NotEmpty() { Skip.If(RuntimeInfo.GetRuntime().IsMono()); var allInstallations = FrameworkInfo.GetInstallations(); Assert.NotEmpty(allInstallations); } [SkippableFact] public void GetInstallations_AllReleasesAreMappedToVersion() { Skip.If(RuntimeInfo.GetRuntime().IsMono()); var allInstallations = FrameworkInfo.GetInstallations(); foreach (var installation in allInstallations) { if (installation.Release != null) { // Release has no version mapped Assert.NotNull(installation.Version); } } } } #endif
using Photon.Pun; using Photon.Realtime; using UnityEngine; using UnityEngine.UI; /* * Allows to set each player's state in order to have the money manager be completely synced among players * when every player has a state property, money manager is enabled as well as the confirm and random button of the character * selection UI */ public class StatePresetManager : MonoBehaviour { private const string PLAYER_STATE = "My_State"; private bool notYet,once; public MoneyManager myMoneyManager; public Button ConfirmButton, RandomButton; // Start is called before the first frame update void Start() { notYet = true; once = false; } // Update is called once per frame void Update() { if(notYet) { SetCustomPpties(0); notYet = false; } if(!notYet) { foreach(Player p in PhotonNetwork.PlayerListOthers) { if(p.CustomProperties[PLAYER_STATE]==null) { once = true; } } if (!once) { myMoneyManager.enabled = true; ConfirmButton.interactable = true; RandomButton.interactable = true; this.enabled = false; } else { once = false; } } } private void SetCustomPpties(int ind) { //sets the local value of the selected object and sync it with other player int playerIndex = ind; if (GameManager._myCustomProperty[PLAYER_STATE] != null) { GameManager._myCustomProperty[PLAYER_STATE] = playerIndex; } else { GameManager._myCustomProperty.Add(PLAYER_STATE, playerIndex); } PhotonNetwork.LocalPlayer.CustomProperties = GameManager._myCustomProperty; PhotonNetwork.LocalPlayer.SetCustomProperties(PhotonNetwork.LocalPlayer.CustomProperties); } }
using MiEscuela.BIZ; using MiEscuela.COMMON.Entidades; using MiEscuela.COMMON.Interfaces; using MiEscuela.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MiEscuela.Vistas { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ViewMateria : ContentPage { Materia materia; IMateriaManager materiaManager; bool nuevo; public int contar=0; public int contar2; decimal calif; decimal calif2; public ViewMateria (Materia m, bool n) { materia = m; nuevo = n; InitializeComponent (); materiaManager = new MateriaManager(new GenericRepository<Materia>()); contenedor.BindingContext = materia; Appearing += ViewMateria_Appering; btnAgregarTarea.Clicked += (sender, e) => { Navigation.PushAsync(new ViewTarea(new Tarea { IdTarea = materia.Id },true)); }; btnGuardar.Clicked += (sender, e) => { if (nuevo) { materia = materiaManager.Agregar(contenedor.BindingContext as Materia); } else { materia = materiaManager.Modificar(contenedor.BindingContext as Materia); } if (materia != null) { DisplayAlert("Mi Escuela", "Materia Guardada", "OK"); Navigation.PopAsync(); } else { DisplayAlert("Mi Escuela", "Error al Guardar", "OK"); } }; btnEliminar.Clicked += (sender, e) => { if (materiaManager.Eliminar(materia.Id)) { DisplayAlert("Mi Escuela", "Materia Eliminada Correctamente", "Ok"); Navigation.PopAsync(); } else { DisplayAlert("Mi Escuela", "No se pudo eliminar la materia", "Ok"); } }; lstTareas.ItemTapped += (sender, e) => { if (lstTareas.SelectedItem != null) { Navigation.PushAsync(new ViewTarea(lstTareas.SelectedItem as Tarea, false)); } }; } private void ViewMateria_Appering(object sender, EventArgs e) { ITareaManager tareaManager = new TareaManager(new GenericRepository<Tarea>()); lstTareas.ItemsSource = null; var datos= tareaManager.BuscarTareasDeMateria(materia.Id); lstTareas.ItemsSource = datos; contar = datos.Count(p=>!p.Entregada); contar2 = datos.Count(); //d => !d.Entregada && d.Entregada calif = datos.Sum(d => d.Calificacion); //calif2 = (calif2 * 100) / contar2; materia.CalificacionMateria = calif2; materia.contador = contar; if (contar >= 1) { DisplayAlert("Mi Escuela", "Tareas por entregar: " + contar , "OK"); } if (contar2 >=1) { calif2 = calif / contar2; } else { calif2 = calif / 1; } materia.CalificacionMateria = calif2; } } }
using BaseLib.Xwt.Controls.DockPanel; using BaseLib.Xwt.Controls.PropertyGrid; using BaseLib.Xwt.Design; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Xwt; using Xwt.Drawing; namespace DockExample { partial class mainwindow { class testtoolitem : Canvas, IDockToolbar, IDockSerializable { Widget IDockContent.Widget => this; string IDockContent.TabText => $"tool{this.Id}"; IDockPane IDockContent.DockPane { get; set; } public int Id { get; } public testtoolitem(mainwindow main) : this(main.dock) { } private testtoolitem(DockPanel dock) { var w = dock.AllContent.OfType<testtoolitem>().Select(_tw => _tw.Id); if (w.Any()) { Id = w.Max() + 1; } else { Id = 1; } Initialize(); } public testtoolitem(string data) { this.Id = int.Parse(data); Initialize(); } void Initialize() { this.MinWidth = this.MinHeight = 10; this.BackgroundColor = Colors.Aquamarine; } string IDockSerializable.Serialize() { return this.Id.ToString(); } } class testpropertiesitem : Canvas, IDockToolbar { private PropertyGrid widget; private IDockPane dockpane; Widget IDockContent.Widget => this; string IDockContent.TabText => $"Properties"; IDockPane IDockContent.DockPane { get => this.dockpane; set { if (this.dockpane != null) { this.dockpane.DockPanel.ActiveDocumentChanged -= DockPanel_ActiveDocumentChanged; } if ((this.dockpane = value) != null) { this.dockpane.DockPanel.ActiveDocumentChanged += DockPanel_ActiveDocumentChanged; } } } class ICollectionEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { var svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); var dialog = new Dialog(); dialog.Content = new Label("hello"); var cmd = svc.ShowDialog(dialog); return value; } } class ICollectionConverter : CollectionConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return false; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { return $"Count={(value as ICollection)?.Count}"; } return base.ConvertTo(context, culture, value, destinationType); } } [TypeConverter(typeof(ExpandableObjectConverter))] public struct point { public int X { get; set; } public int Y { get; set; } } [TypeConverter(typeof(ExpandableObjectConverter))] class testobject { [Category("abc")] public point pt { get; set; } = new point(); [Category("abc")] [DefaultValue("hello")] public string Text { get; set; } public Int32 getal { get; set; } [Editor(typeof(ICollectionEditor), typeof(UITypeEditor))] [TypeConverter(typeof(ICollectionConverter))] public object[][] testarray { get; set; } = new object[][] { new object[] { "abc", 0 } }; [Editor(typeof(ICollectionEditor), typeof(UITypeEditor))] [TypeConverter(typeof(ICollectionConverter))] [BrowsableAttribute(true)] public List<Int32> testlist { get; set; } = new List<int>(new int[] { 2, 3 }); public enum testenum { een, twee, drie } public testenum test { get; set; } // [Category("test")] // public System.Drawing.Size size { get; set; } = new System.Drawing.Size(); // public System.Drawing.Rectangle rect { get; set; } = new System.Drawing.Rectangle(); } private void DockPanel_ActiveDocumentChanged(object sender, EventArgs e) { this.widget.SelectedObject = new testobject(); } public testpropertiesitem() { Initialize(); } void Initialize() { this.BackgroundColor = Colors.Aquamarine; this.widget = new PropertyGrid(); this.AddChild(this.widget); this.MinWidth = this.widget.MinWidth; this.MinWidth = this.widget.MinHeight; this.OnBoundsChanged(); } protected override void OnBoundsChanged() { this.SetChildBounds(this.widget, this.Bounds); } } } }
using Solutia.Logging.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Logging.Classes { public class DbLogSinkCommandParameter { public string Name { get; set; } public LogEntryComponent LogEntryComponent { get; set; } } public enum CommandType { Table, StoredProcedure } public class DatabaseLogSink:ILogSink { public string ConnectionString { get; set; } public string CommandText { get; set;} public CommandType CommandType { get; set; } public IList<DbLogSinkCommandParameter> Parameters { get; set; } public string Name { get; set; } public EventLevel MinimumEventLevel { get; set; } public IList<LogEntryComponent> LogEntryConfiguration => throw new NotImplementedException(); } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using ApartmentApps.Client.Models; using Microsoft.Rest; namespace ApartmentApps.Client { public partial interface ICheckins { /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<CourtesyCheckinBindingModel>>> GetWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name='locationId'> /// Required. /// </param> /// <param name='latitude'> /// Optional. /// </param> /// <param name='longitude'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<string>> PostWithOperationResponseAsync(int locationId, double? latitude = null, double? longitude = null, CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using UnityEngine; using System.Collections; public class Tone : MonoBehaviour { static void ShiftAudio(AudioSource audio) { var twelfthRootOfTwo = Mathf.Pow(2f, 1.0f/12); var randomShift = Random.Range(1, 12); audio.pitch = Mathf.Pow(twelfthRootOfTwo, randomShift); } public static void SpawnClip (AudioClip sample) { var go = new GameObject("tone", typeof(AudioSource)); var audio = go.GetComponent<AudioSource>(); audio.playOnAwake = false; audio.loop = false; audio.clip = sample; ShiftAudio(audio); audio.Play(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Thingy.WebServerLite.Api; namespace Thingy.WebServerLite { /// <summary> /// This class represents a set of view templates selected from various files to render a /// page. /// /// The view can produce any kind of text file. The ContentType will be dictated by /// the extension of the controllerMethodPage /// /// Parse-time Directives /// /// {@TemplateName ...} - Declare a named template /// {!FileName} - Include a template file /// {* ... } - A comment /// /// Render-time Directives /// /// {PropertyName[.PropertyName]} - Render this property here /// {#TemplateName} - Render this named template here /// {=FunctionName(Params)} - Render the output of this function here /// /// </summary> public class View : IView { private readonly char[] period = new char[] { '.' }; private readonly char[] comma = new char[] { ',' }; private readonly IDictionary<string, string> templates = new Dictionary<string, string>(); private readonly IViewLibrary[] commandLibraries; private readonly string contentType; public View(IViewLibrary[] commandLibraries, IMimeTypeProvider mimeTypeProvider, string masterPage, string controllerMasterPage, string controllerMethodPage) { this.commandLibraries = commandLibraries; templates["."] = string.Empty; if (!string.IsNullOrEmpty(masterPage)) { AddPage(masterPage); } if (!string.IsNullOrEmpty(controllerMasterPage)) { AddPage(controllerMasterPage); } if (!string.IsNullOrEmpty(controllerMethodPage)) { AddPage(controllerMethodPage); } this.contentType = mimeTypeProvider.GetMimeType(controllerMethodPage); } private void AddPage(string path) { using (ViewReader reader = new ViewReader(path)) { do { string content = reader.ReadContent(); AddContent(content); if (!reader.EndOfView) { string template = reader.ReadTemplate(); if (template[0] == '@') { AddTemplate(template); } else { if (template[0] == '!') { IncludeTemplate(path, template); } else { if (template[0] != '*') { AddContent(string.Format("{0}{1}{2}", "{", template, "}")); } } } } } while (!reader.EndOfView); } } private void IncludeTemplate(string path, string template) { AddPage(Path.Combine(Path.GetDirectoryName(path), GetFirstTemplateElement(template))); } private void AddTemplate(string template) { templates[GetFirstTemplateElement(template)] = GetTemplateContent(template); } private void AddContent(string content) { templates["."] = string.Format("{0}{1}", templates["."], content); } private string GetFirstTemplateElement(string template) { int spacePos = template.IndexOf(' '); int newlinePos = template.IndexOf(Environment.NewLine); int delimiterPos = spacePos < newlinePos || newlinePos == -1 ? spacePos : newlinePos; if (delimiterPos == -1) { return template.Substring(1); } else { return template.Substring(1, delimiterPos - 1); } } private string GetTemplateContent(string template) { int spacePos = template.IndexOf(' '); int newlinePos = template.IndexOf(Environment.NewLine); if (spacePos < newlinePos || newlinePos == -1) { return template.Substring(spacePos + 1, template.Length - spacePos - 1); } else { return template.Substring(newlinePos + 2, template.Length - newlinePos - 2); } } public IViewResult Render(object model) { return new ViewResult() { Content = InternalRender(templates["."], model), ContentType = contentType }; } private string InternalRender(string workingText, object model) { StringBuilder contentBuilder = new StringBuilder(); while (!string.IsNullOrEmpty(workingText)) { int openPos = workingText.IndexOf('{'); if (openPos == -1) { contentBuilder.Append(workingText); workingText = string.Empty; } else { workingText = ResolveInsert(model, contentBuilder, workingText, openPos); } } contentBuilder.Append(workingText); return contentBuilder.ToString(); } private string ResolveInsert(object model, StringBuilder contentBuilder, string workingText, int openPos) { contentBuilder.Append(workingText.Substring(0, openPos)); int closePos = FindMatchingClose(workingText, openPos); string newText; if (workingText[openPos + 1] == '#') { int spacePos = workingText.IndexOf(' ', openPos); if (spacePos == -1 || spacePos > closePos) { string templateName = workingText.Substring(openPos + 2, closePos - openPos - 2); if(!templates.ContainsKey(templateName)) { throw new ViewException(string.Format("Error rendering template named \"{0}\". No template with that name is defined.", templateName)); } newText = templates[templateName]; } else { string templateName = workingText.Substring(openPos + 2, spacePos - openPos - 2); if (!templates.ContainsKey(templateName)) { throw new ViewException(string.Format("Error rendering template named \"{0}\". No template with that name is defined.", templateName)); } string propertyName = workingText.Substring(spacePos + 1, closePos - spacePos - 1); object newModel = GetPropertyValueFromModel(model, propertyName); if (newModel is Array) { StringBuilder newTextBuilder = new StringBuilder(); foreach (object modelElement in (Array)newModel) { newTextBuilder.Append(InternalRender(templates[templateName], modelElement)); } newText = newTextBuilder.ToString(); } else { newText = InternalRender(templates[templateName], newModel); } } } else { if (workingText[openPos + 1] == '=' || workingText[openPos + 1] == '?') { char action = workingText[openPos + 1]; string commandText = workingText.Substring(openPos + 2, closePos - openPos - 2); newText = RunCommands(model, action, commandText); } else { string propertyName = workingText.Substring(openPos + 1, closePos - openPos - 1); newText = GetPropertyValueFromModel(model, propertyName).ToString(); } } return string.Format("{0}{1}", newText, workingText.Substring(closePos + 1)); } private string RunCommands(object model, char action, string commandText) { // The command up to the ) needs to be run regardless of if we have a template or not and wether we're doing a conditional or an insert int closePos = commandText.IndexOf(")"); string content; if (action == '?') { // This is a conditional template. We only include it if the command returns true content = (bool)RunCommand(model, commandText.Substring(0, closePos + 1)) ? commandText.Substring(closePos + 1) : string.Empty; } else { object commandResult = RunCommand(model, commandText.Substring(0, closePos + 1)).ToString(); string template = commandText.Substring(closePos + 1); if (template.All(c => Char.IsWhiteSpace(c))) { // This is a simple command result insert content = commandResult.ToString(); } else { if (commandResult is string && ((string)commandResult).StartsWith("[[HasContent]]")) { // This is a 'wrapping' function that contains a placeholder for the template content = ((string)commandResult).Substring(14).Replace("[[Content]]", InternalRender(commandText.Substring(closePos + 1), model)); } else { // This is a render-with-model template where the command result is the new model content = InternalRender(commandText.Substring(closePos + 1), commandResult); } } } return content; } private object RunCommand(object model, string commandText) { try { int openPos = commandText.IndexOf('('); string[] commandNameParts = commandText.Substring(0, openPos).Split(period); object commandLibrary; if (commandNameParts[0] == "model") { commandLibrary = model; for (int i = 1; i < commandNameParts.Length - 1; i++) { PropertyInfo p = commandLibrary.GetType().GetProperty(commandNameParts[i]); commandLibrary = p.GetValue(commandLibrary); } } else { commandLibrary = commandLibraries.FirstOrDefault(l => l.GetType().Name.StartsWith(commandNameParts[0])); if (commandLibrary == null) { throw new ViewException(string.Format("Error running command \"{0}\". Could not find a command library named \"{1}\"", commandText, commandNameParts[0])); } } MethodInfo methodInfo = commandLibrary.GetType().GetMethods().FirstOrDefault(m => m.Name == commandNameParts[1]); if (methodInfo == null) { throw new ViewException(string.Format("Error running command \"{0}\". Method could not be found.", commandText)); } ParameterInfo[] parameterInfos = methodInfo.GetParameters(); string parameterString = commandText.Substring(openPos + 1, commandText.Length - openPos - 2).Trim(); object[] parameters = new object[parameterInfos.Length]; int parametersAssigned = 0; if (!string.IsNullOrEmpty(parameterString)) { string[] parameterNames = parameterString.Split(comma).Select(p => p.Trim()).ToArray(); if (parameterNames.Length > parameterInfos.Length) { throw new ViewException(string.Format("Error running command \"{0}\". Too many parameters.", commandText)); } for (int index = 0; index < parameterNames.Length; index++) { if (parameterNames[index][0] == '"') { parameters[index] = parameterNames[index].Substring(1, parameterNames[index].Length - 2); } else { if ((parameterNames[index][0] >= '0' && parameterNames[index][0] <= '9') || parameterNames[index][0] == '-' || parameterNames[index][0] == '+') { if (!parameterNames[index].Contains(".")) { parameters[index] = Convert.ToInt32(parameterNames[index]); } else { parameters[index] = Convert.ToDecimal(parameterNames[index]); } } else { if (parameterNames[index].ToLower() == "true" || parameterNames[index].ToLower() == "false") { parameters[index] = Convert.ToBoolean(parameterNames[index]); } else { parameters[index] = GetPropertyValueFromModel(model, parameterNames[index]); } } } } parametersAssigned = parameterNames.Length; } if (parameterInfos.Length > parametersAssigned) { int start = parametersAssigned; for (int index = start; index < parameters.Length; index++) { if (!parameterInfos[index].HasDefaultValue) { throw new ViewException(string.Format("Error running command \"{0}\". Not enough parameters.", commandText)); } parameters[index] = parameterInfos[index].DefaultValue; } } try { if (methodInfo.GetParameters().Any()) { return methodInfo.Invoke(commandLibrary, parameters); } else { return methodInfo.Invoke(commandLibrary, null); } } catch (Exception exception) { throw new ViewException(string.Format("Error running command \"{0}\". The command threw an exception.", commandText), exception); } } catch (ViewException) { throw; } catch (Exception exception) { throw new ViewException(string.Format("Error running command \"{0}\". Unexpected Error.", commandText), exception); } } private static int FindMatchingClose(string workingText, int openPos) { int closePos = workingText.IndexOf('}', openPos); int nestedOpenPos = workingText.IndexOf('{', openPos + 1); int nestingLevel = 0; while (nestingLevel > 0 || nestedOpenPos < closePos) { if (nestedOpenPos == -1) { nestedOpenPos = int.MaxValue; } else { if (nestingLevel == -1 || nestedOpenPos < closePos) { nestingLevel++; nestedOpenPos = workingText.IndexOf('{', nestedOpenPos + 1); } else { nestingLevel--; closePos = workingText.IndexOf('}', closePos + 1); } } } return closePos; } private object GetPropertyValueFromModel(object model, string propertyName) { string[] propertyNames = propertyName.Split(period); Type type = model.GetType(); object nestedModel = model; for (int index = 0; index < propertyNames.Length; index++) { if (propertyNames[index] != "model") { PropertyInfo propertyInfo = type.GetProperties().FirstOrDefault(p => p.Name == propertyNames[index]); if (propertyInfo == null) { throw new ViewException(string.Format("Error resolving property \"{0}\". {1} does not exist.", propertyName, propertyNames[index])); } type = propertyInfo.PropertyType; nestedModel = propertyInfo.GetValue(nestedModel); } } return nestedModel; } } }
using UnityEngine; public class PlayerMovementController : MonoBehaviour { #region Variables #region Components private Rigidbody2D m_rigidbody2D; #endregion #region Private Variables [SerializeField] private float m_initialMoveSpeed; private Vector2 xyinput; #endregion #region Public Variables public float m_currentMoveSpeed; #endregion #endregion #region BuiltIn Methods void Start() { m_currentMoveSpeed = m_initialMoveSpeed; m_rigidbody2D = GetComponent<Rigidbody2D>(); } void FixedUpdate() { Move(); } #endregion #region Custom Methods Vector2 GetInput() { return new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); } void Move() { xyinput = GetInput(); m_rigidbody2D.velocity = xyinput * m_currentMoveSpeed * Time.deltaTime; } #endregion }
using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace DSSLib { public interface IFileSelector { FileInfo Open(); FileInfo Save(); } public class DialogFileSelector : IFileSelector { private string DefaultExt { get; set; } private string DefaultDirectory { get; set; } private string DefaultFilter { get; set; } public DialogFileSelector(params FileExtInfo[] infos) { } public DialogFileSelector(string defaultExt = ".xml", string defaultFolder = null, string filter = "XML-файлы (*.xml) |*.xml|JSON-файлы (*.json) |*.json| TXT-файлы (*.txt*)|*.txt") { DefaultExt = defaultExt; DefaultDirectory = defaultFolder; DefaultFilter = filter; } public FileInfo Open() { OpenFileDialog dialog = new OpenFileDialog(); dialog.DefaultExt = DefaultExt; dialog.InitialDirectory = DefaultDirectory; dialog.Filter = DefaultFilter; if (dialog.ShowDialog() == true) { return new FileInfo(dialog.FileName); } return null; } public FileInfo Save() { SaveFileDialog dialog = new SaveFileDialog(); dialog.DefaultExt = DefaultExt; dialog.InitialDirectory = DefaultDirectory; dialog.Filter = DefaultFilter; if (dialog.ShowDialog() == true) { return new FileInfo(dialog.FileName); } return null; } } public class FileExtInfo { public string Name { get; private set; } public string Extension { get; private set; } public string Filter { get; private set; } public int Priority { get; private set; } public FileExtInfo(string name, string ext, int priority = 1) { Name = name; Extension = ext; Priority = priority; } } }
 namespace _05.HashSet { using System; using System.Collections.Generic; using System.Linq; using _04.HashTable; public class HashSet<T> : IEnumerable<T> { private HashTable<T, bool> set; public HashSet(int capacity = 16) { this.set = new HashTable<T, bool>(capacity); } public int Count { get { return this.set.Count; } } //public int Capacity //{ // get // { // return this.set.Capacity; // } //} public void Add(T value) { set.Add(value, true); } public void Remove(T value) { set.Remove(value); } public void Clear() { this.set.Clear(); } //public T Find(T value) //{ // return set.FindPair(value).Key; //} //public bool Contains(T key) //{ // return this.set.Contains(key); //} public IEnumerator<T> GetEnumerator() { foreach (var item in this.set) { yield return item.Key; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public void Union(HashSet<T> otherSet) { foreach (var item in otherSet) { if (!this.Contains(item)) { this.Add(item); } } } public void Intersect(HashSet<T> otherSet) { var newSet = new HashTable<T, bool>(); //(this.Capacity) foreach (var item in this) { if (otherSet.Contains(item)) { newSet.Add(item, true); } } this.set = newSet; } } }
namespace P10InfernoInfinity.Models.Weapons.WeaponLevels { using System; using Enums; public class RareWeaponLevel : WeaponLevel { private const WeaponLevelEnumeration DefaultWeaponLevel = WeaponLevelEnumeration.Rare; private const string DefaultWeaponLevelAsString = "Rare"; private const int DefaultDamageMultiplier = 3; public RareWeaponLevel() : base(DefaultWeaponLevel, DefaultDamageMultiplier) { } public RareWeaponLevel(string levelOfWeapon) : base(DefaultDamageMultiplier) { base.LevelOfWeapon = base.ParseWeaponLevel(this.ValidateLevel(levelOfWeapon)); } protected override sealed string ValidateLevel(string level) { if (level != DefaultWeaponLevelAsString) { throw new ArgumentException(DefaultWrongLevelMessage); } return level; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercise9 { public class Logger { public List<string> LoggPosts { get; private set; } public Logger() { this.LoggPosts = new List<string>(); } public void Logg(string message) { DateTime koll = new DateTime(); koll = DateTime.Now; LoggPosts.Add("Registered: "+koll+" "+ message); } public void ReadLog() { if (LoggPosts.Count == 0) { Console.WriteLine("LoggBok is empty");return; } foreach (var item in LoggPosts) { Console.WriteLine(item); } } } }
using SFA.DAS.Authorization.ModelBinding; namespace SFA.DAS.ProviderCommitments.Web.Models.Cohort { public class ConfirmEmployerRequest : IAuthorizationContextModel { public long ProviderId { get; set; } public string EmployerAccountLegalEntityPublicHashedId { get; set; } public long AccountLegalEntityId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HomeWorkOOP7_1 { /* Задание * Описать структуру с именем Train, содержащую следующие поля: название пункта назначения, номер поезда, время отправления. *Написать программу, выполняющую следующие действия: * - ввод с клавиатуры данных в массив, состоящий из восьми элементов типа Train (записи должны быть упорядочены по номерам поездов); * - вывод на экран информации о поезде, номер которого введен с клавиатуры (если таких поездов нет, вывести соответствующее сообщение). */ class Program { static void Main(string[] args) { //создаем массив для расписания Train[] trains = new Train[3]; //добавляем поезд в расписание StaticTrain.AddTrain(trains); //поиск поезда по номеру StaticTrain.Search(trains,3); Console.ReadKey(); } } }
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Support.UI; using Assert = NUnit.Framework.Assert; namespace RMS { [TestFixture] public class Test { [Test] public void A_PatentEntry() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("http://172.16.18.106/RMSSTAGE/Login.aspx"); driver.Manage().Window.Maximize(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).SendKeys("fassv4"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).SendKeys("mubop@123"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_Button1")).Click(); Task.Delay(2000).Wait(); IWebElement mnuElement; IWebElement submnuElement; mnuElement = driver.FindElement(By.LinkText("Patent")); submnuElement = driver.FindElement(By.XPath("//a[contains(text(),'Patent Entry')]")); Task.Delay(2000).Wait(); Actions builder = new Actions(driver); // Move cursor to the Main Menu Element builder.MoveToElement(mnuElement).Perform(); // Pause 2 Seconds for submenu to be displayed Task.Delay(2000).Wait(); //Pause 2 seconds submnuElement.Click();// Clicking on the Hidden submnuElement Task.Delay(2000).Wait(); Assert.AreEqual("Patent Entry", driver.FindElement(By.XPath("//div[@id='ctl00_ContentPlaceHolder1_Panel2']/div")).Text); Task.Delay(2000).Wait(); driver.FindElement(By.Id("ctl00_Label3")).Click(); Task.Delay(2000).Wait(); driver.Close(); } [Test] public void B_PatentView() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("http://172.16.18.106/RMSSTAGE/Login.aspx"); driver.Manage().Window.Maximize(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).SendKeys("fassv4"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).SendKeys("mubop@123"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_Button1")).Click(); Task.Delay(2000).Wait(); IWebElement mnuElement; IWebElement submnuElement; mnuElement = driver.FindElement(By.LinkText("Patent")); submnuElement = driver.FindElement(By.XPath("//a[contains(text(),'Patent View')]")); Task.Delay(2000).Wait(); Actions builder = new Actions(driver); // Move cursor to the Main Menu Element builder.MoveToElement(mnuElement).Perform(); // Pause 2 Seconds for submenu to be displayed Task.Delay(2000).Wait(); //Pause 2 seconds submnuElement.Click();// Clicking on the Hidden submnuElement Task.Delay(2000).Wait(); Assert.AreEqual("Patent View", driver.FindElement(By.XPath("//div[contains(text(),'Patent View')]")).Text); Task.Delay(2000).Wait(); driver.FindElement(By.Id("ctl00_Label3")).Click(); Task.Delay(2000).Wait(); driver.Close(); } [Test] public void C_ProjectReports() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("http://172.16.18.106/RMSSTAGE/Login.aspx"); driver.Manage().Window.Maximize(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).SendKeys("fassv4"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).SendKeys("mubop@123"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_Button1")).Click(); Task.Delay(2000).Wait(); IWebElement mnuElement; IWebElement submnuElement; mnuElement = driver.FindElement(By.LinkText("Reports")); submnuElement = driver.FindElement(By.XPath("//a[contains(text(),'Project Reports')]")); Task.Delay(2000).Wait(); Actions builder = new Actions(driver); // Move cursor to the Main Menu Element builder.MoveToElement(mnuElement).Perform(); // Pause 2 Seconds for submenu to be displayed Task.Delay(2000).Wait(); //Pause 2 seconds submnuElement.Click();// Clicking on the Hidden submnuElement Task.Delay(2000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_LinkButton9")).Click(); Task.Delay(2000).Wait(); IWebElement selectDate = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_TextBoxFromDate")); selectDate.Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_CalendarExtender1_day_1_2")).Click(); Task.Delay(2000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_view")).Click(); Task.Delay(2000).Wait(); Assert.AreEqual("Pharmacology ", driver.FindElement(By.XPath("/html[1]/body[1]/form[1]/div[3]/div[3]/center[3]/span[1]/div[1]/table[1]/tbody[1]/tr[5]/td[3]/div[1]/div[1]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[2]/td[3]/table[1]/tbody[1]/tr[5]/td[7]/div[1]")).Text); Task.Delay(2000).Wait(); driver.FindElement(By.Id("ctl00_Label3")).Click(); Task.Delay(2000).Wait(); driver.Close(); } [Test] public void D_ProjectEntry() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("http://172.16.18.106/RMSSTAGE/Login.aspx"); driver.Manage().Window.Maximize(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxUid")).SendKeys("fassv4"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Click(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).Clear(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_TextBoxPassword")).SendKeys("mubop@123"); Task.Delay(1000).Wait(); driver.FindElement(By.Id("ctl00_ContentPlaceHolderhead_Button1")).Click(); Task.Delay(2000).Wait(); IWebElement mnuElement; IWebElement submnuElement; mnuElement = driver.FindElement(By.LinkText("Project")); submnuElement = driver.FindElement(By.XPath("//a[contains(text(),'Project Entry')]")); Task.Delay(2000).Wait(); Actions builder = new Actions(driver); // Move cursor to the Main Menu Element builder.MoveToElement(mnuElement).Perform(); // Pause 2 Seconds for submenu to be displayed Task.Delay(2000).Wait(); //Pause 2 seconds submnuElement.Click();// Clicking on the Hidden submnuElement Task.Delay(2000).Wait(); Assert.AreEqual("Project View", driver.FindElement(By.XPath("//legend[contains(text(),'Existing Project Entry')]")).Text); Task.Delay(2000).Wait(); driver.FindElement(By.Id("ctl00_Label3")).Click(); Task.Delay(2000).Wait(); driver.Close(); } } }
namespace Alunos.Biblioteca { public class Livro { public string Nome { get; set; } private string Descricao { get; set; } protected string Autor { get; set; } internal string Versao { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjekatZdravoKorporacija.ModelDTO { class TypeOfExaminationDTO { public string Type { get; set; } public TypeOfExaminationDTO(string type) { this.Type = type; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Sinav { class Program { static void Main(string[] args) { Console.WriteLine("Girilen kelimeyi tersine çevirip yazdırma"); string kelime = "Can"; Quiz1Issue(kelime); Console.WriteLine("Palindrome mu ?"); string palindrome = "ece"; Quiz2Issue(palindrome); Console.WriteLine("0'dan 10'a kadar sayıları ekrana yazdıralım"); Quiz3Issue(10); Console.WriteLine("Girilen bütün sayıları toplayalım"); int[] sayi1 = { 1, 10, 20, 30, 40, 4000, 50, 60, 70, 1 }; Console.WriteLine(Quiz4Issue(sayi1)); Console.WriteLine("Girilen 3 sayıdan en Büyüğünü bulalım"); int[] sayi2 = { 1000, 900, 5000 }; Console.WriteLine(Quiz5Issue(sayi2)); Console.WriteLine("Girilen 3 sayıdan en Küçüğünü bulalım"); int[] sayi3 = { 1000, 900, 5000 }; Console.WriteLine(Quiz6Issue(sayi3)); Console.WriteLine("Girilen 5 sayıdan Enbüyük ve enküçük bulalım"); int[] sayi4 = { 1000, 900, 5000, 10, 50001 }; Quiz7Issue(sayi4); Console.WriteLine("Girilen 10 sayıdan ortalamasına en yakın olanı bulalım"); double[] sayi5 = { 1, 10, 20, 30, 40, 4000, 50, 60, 70, 1 }; Quiz8Issue(sayi5); Console.WriteLine("İsim ve Soyisminiz N kadar yazdırın"); Quiz9Issue(5); Console.WriteLine("Girilen 10 sayının negatif/pozitif olduğunu yazdırma."); int[] sayi6 = { 1, -10, 20, -30, 40, 4000, -50, 60, 70, -1 }; Quiz10Issue(sayi6); Console.ReadLine(); } // 1) Girilen kelimeyi tersine çevirip yazdırma static void Quiz1Issue(string input) { string kelime = ""; for (int i = 0; i <= input.Length - 1; i++) { kelime += (input[input.Length - i - 1]); } Console.WriteLine(kelime); } // 2) Palindrome static void Quiz2Issue(string input) { bool pol = true; for (int i = 0; i <= input.Length - 1; i++) { if (input[input.Length - i - 1] == input[i]) { pol = true; } else { pol = false; } } if (pol) { Console.WriteLine("Polindromdur."); } else { Console.WriteLine("Polindrom değildir."); } } // 3) 0'dan 10'a kadar sayıları ekrana yazdıralım static void Quiz3Issue(int input) { for (int i = 0; i <= input; i++) { Console.WriteLine(i); } } // 4) Girilen bütün sayıları toplayalım static int Quiz4Issue(int [] input) { int toplam = 0; for (int i = 0; i <= input.Length - 1; i++) { toplam += input[i]; } return (toplam); } // 5) Girilen 3 sayıdan en Büyüğünü bulalım static int Quiz5Issue(int[] input) { int enBuyuk = 0; for (int i = 0; i <= input.Length - 1; i++) { if (input[i] > enBuyuk) { enBuyuk = input[i]; } } return(enBuyuk); } // 6) Girilen 3 sayıdan en Küçüğünü bulalım static int Quiz6Issue(int[] input) { int enKucuk = input[0]; foreach(int value in input) { if (value < enKucuk) enKucuk = value; } return enKucuk; } // 7) Girilen 5 sayıdan Enbüyük ve enküçük bulalım static void Quiz7Issue(int[] input) { int enBuyuk = 0; for (int i = 0; i <= input.Length - 1; i++) { if (input[i] > enBuyuk) { enBuyuk = input[i]; } } int enKucuk = input[0]; foreach (int value in input) { if (value < enKucuk) enKucuk = value; } Console.WriteLine("EnBüyük = " + enBuyuk + " EnKüçük = " + enKucuk); } // 8) Girilen 10 sayıdan ortalamasına en yakın olanı bulalım static void Quiz8Issue(double [] input) { double enKucuk = Double.MaxValue; int yeri = 0; List<double> fark = new List<double>(); double ortalama = input.Average(); for (int i = 0; i <= input.Length - 1; i++) { fark.Add(Math.Abs(ortalama - input[i])); } for (int i = 0; i <= input.Length - 1; i++) { if (fark[i] < enKucuk) { enKucuk = fark[i]; yeri = i; } } Console.WriteLine(input[yeri]); } // 9) İsim ve Soyisminiz N kadar yazdırın static void Quiz9Issue(int input) { string[] isim = { "Mehmet Can Onur YARALI" }; for (int i = 0; i < input; i++) { Console.WriteLine(isim[0]); } } // 10) Girilen 10 sayının negatif/pozitif olduğunu yazdırma. static void Quiz10Issue(int [] input) { for (int i = 0; i < input.Length - 1; i++) { if (input[i] < 0) { Console.WriteLine(input[i] + " Negatif"); } else { Console.WriteLine(input[i] + " Pozitif"); } } } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StarlightRiver.Abilities; using Terraria; using Terraria.DataStructures; using Terraria.Enums; using Terraria.ModLoader; using Terraria.ObjectData; namespace StarlightRiver.Tiles.Void { class Void1 : ModTile { public override void SetDefaults() { Main.tileSolid[Type] = true; Main.tileMergeDirt[Type] = false; Main.tileBlockLight[Type] = true; Main.tileLighted[Type] = true; drop = mod.ItemType("Void1Item"); dustType = mod.DustType("Darkness"); AddMapEntry(new Color(35, 40, 20)); } } class Void2 : ModTile { public override void SetDefaults() { Main.tileSolid[Type] = true; Main.tileMergeDirt[Type] = false; Main.tileBlockLight[Type] = true; Main.tileLighted[Type] = true; drop = mod.ItemType("Void2Item"); dustType = mod.DustType("Darkness"); AddMapEntry(new Color(45, 50, 30)); } } class VoidTorch1 : ModTile { public override void SetDefaults() { Main.tileLavaDeath[Type] = false; Main.tileFrameImportant[Type] = true; TileObjectData.newTile.CopyFrom(TileObjectData.Style1x2); TileObjectData.addTile(Type); AddMapEntry(new Color(45, 50, 30)); dustType = mod.DustType("Darkness"); disableSmartCursor = true; } public override void KillMultiTile(int i, int j, int frameX, int frameY) { Item.NewItem(i * 16, j * 16, 32, 32, mod.ItemType("VoidTorch1Item")); } public override void DrawEffects(int i, int j, SpriteBatch spriteBatch, ref Color drawColor, ref int nextSpecialDrawIndex) { if (Main.tile[i, j].frameX == 0 && Main.tile[i, j].frameY == 0) { for(int k = 0; k <= 3; k++) { Dust.NewDust(new Vector2((i * 16) - 1, (j - 1) * 16), 12, 16, mod.DustType("Darkness")); } } } } class VoidTorch2 : ModTile { public override void SetDefaults() { Main.tileLavaDeath[Type] = false; Main.tileFrameImportant[Type] = true; TileObjectData.newTile.CopyFrom(TileObjectData.Style2x1); TileObjectData.newTile.AnchorWall = true; TileObjectData.newTile.AnchorBottom = AnchorData.Empty; TileObjectData.addTile(Type); AddMapEntry(new Color(45, 50, 30)); dustType = mod.DustType("Darkness"); disableSmartCursor = true; } public override void KillMultiTile(int i, int j, int frameX, int frameY) { Item.NewItem(i * 16, j * 16, 32, 32, mod.ItemType("VoidTorch2Item")); } public override void DrawEffects(int i, int j, SpriteBatch spriteBatch, ref Color drawColor, ref int nextSpecialDrawIndex) { if (Main.tile[i, j].frameX == 0 && Main.tile[i, j].frameY == 0) { for (int k = 0; k <= 6; k++) { Dust.NewDust(new Vector2((i * 16) + 5, (j - 0.8f) * 16), 18, 14, mod.DustType("Darkness")); } } } } class VoidPillarB : ModTile { public override void SetDefaults() { Main.tileLavaDeath[Type] = false; Main.tileFrameImportant[Type] = true; TileObjectData.newTile.CopyFrom(TileObjectData.Style3x2); TileObjectData.addTile(Type); AddMapEntry(new Color(45, 50, 30)); dustType = mod.DustType("Darkness"); disableSmartCursor = true; } public override void KillMultiTile(int i, int j, int frameX, int frameY) { Item.NewItem(i * 16, j * 16, 32, 32, mod.ItemType("VoidPillarBItem")); } } class VoidPillarM : ModTile { public override void SetDefaults() { Main.tileFrameImportant[Type] = true; TileObjectData.newTile.CopyFrom(TileObjectData.Style3x2); TileObjectData.newTile.AnchorBottom = new AnchorData(AnchorType.AlternateTile, TileObjectData.newTile.Width, 0); TileObjectData.newTile.AnchorAlternateTiles = new int[] { ModContent.TileType<VoidPillarB>(), ModContent.TileType<VoidPillarM>() }; TileObjectData.addTile(Type); dustType = mod.DustType("Darkness"); } public override void KillMultiTile(int i, int j, int frameX, int frameY) { Item.NewItem(i * 16, j * 16, 32, 32, mod.ItemType("VoidPillarMItem")); } } class VoidPillarT : ModTile { public override void SetDefaults() { Main.tileFrameImportant[Type] = true; TileObjectData.newTile.Width = 3; TileObjectData.newTile.Height = 1; TileObjectData.newTile.CoordinateHeights = new int[] { 16 }; TileObjectData.newTile.UsesCustomCanPlace = true; TileObjectData.newTile.CoordinateWidth = 16; TileObjectData.newTile.CoordinatePadding = 2; TileObjectData.newTile.Origin = new Point16(0, 0); TileObjectData.newTile.AnchorBottom = new AnchorData(AnchorType.AlternateTile, TileObjectData.newTile.Width, 0); TileObjectData.newTile.AnchorTop = new AnchorData(AnchorType.SolidTile, TileObjectData.newTile.Width, 0); TileObjectData.newTile.AnchorAlternateTiles = new int[] { ModContent.TileType<VoidPillarM>() }; TileObjectData.addTile(Type); dustType = mod.DustType("Darkness"); } public override void KillMultiTile(int i, int j, int frameX, int frameY) { Item.NewItem(i * 16, j * 16, 32, 32, mod.ItemType("VoidPillarTItem")); } } class VoidPillarP : ModTile { public override void SetDefaults() { Main.tileFrameImportant[Type] = true; TileObjectData.newTile.Width = 3; TileObjectData.newTile.Height = 1; TileObjectData.newTile.CoordinateHeights = new int[] { 16 }; TileObjectData.newTile.UsesCustomCanPlace = true; TileObjectData.newTile.CoordinateWidth = 16; TileObjectData.newTile.CoordinatePadding = 2; TileObjectData.newTile.Origin = new Point16(0, 0); TileObjectData.newTile.AnchorBottom = new AnchorData(AnchorType.AlternateTile, TileObjectData.newTile.Width, 0); TileObjectData.newTile.AnchorAlternateTiles = new int[] { ModContent.TileType<VoidPillarM>() }; TileObjectData.addTile(Type); dustType = mod.DustType("Darkness"); } public override void KillMultiTile(int i, int j, int frameX, int frameY) { Item.NewItem(i * 16, j * 16, 32, 32, mod.ItemType("VoidPillarPItem")); } } }
using System.Collections; using System.Linq; using TMPro; using UnityEngine; public class Player : MonoBehaviour { public static Player Instance { get; private set; } private Health _health; private TextMeshProUGUI _healthText; private Canvas _canvas; private Rigidbody2D _rb2D; private SpriteRenderer _spriteRenderer; private void Awake() { if (Instance == null) { Instance = this; } else { Destroy(gameObject); } gameObject.tag = "player"; AddComponents(); } private void AddComponents() { _health = gameObject.AddComponent<Health>(); gameObject.AddComponent<BoxCollider2D>(); _rb2D = gameObject.AddComponent<Rigidbody2D>(); _spriteRenderer = GetComponent<SpriteRenderer>(); _canvas = FindObjectsOfType<Canvas>().First(e => e.renderMode == RenderMode.ScreenSpaceOverlay); _healthText = _canvas.gameObject.AddComponent<TextMeshProUGUI>(); _healthText.rectTransform.anchorMax = Vector2.one; _healthText.rectTransform.anchorMin = Vector2.one; } private void Start() { _health.amount = 2000f; } private void OnCollisionStay2D(Collision2D other) { if (other.gameObject.CompareTag("spike")) DoWhatEverOnDamageHere(other.gameObject.GetComponent<DamageObject>(), true); } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("spike")) DoWhatEverOnDamageHere(other.gameObject.GetComponent<DamageObject>()); } private void DoWhatEverOnDamageHere(DamageObject damageObject, bool stay = false) { _health.amount-= damageObject.damageAmount * (stay ? 1f : Time.deltaTime); _healthText.text = $"{Mathf.RoundToInt(_health.amount)}HP"; _rb2D.AddForce(Vector2.up * 100); StartCoroutine(AnimateOnDamage()); } private IEnumerator AnimateOnDamage() { _spriteRenderer.color = new Color32(255, 100, 100, 255); yield return new WaitForSeconds(0.1f); _spriteRenderer.color = new Color32(0, 255, 255, 255); } private void OnDestroy() { Instance = null; } } public class DamageObject : MonoBehaviour { public float damageAmount; private void Awake() { gameObject.tag = "spike"; gameObject.AddComponent<PolygonCollider2D>(); } } public class Health : MonoBehaviour { public float amount; }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Domain; namespace Persistence { public class Seed { public static async Task SeedData(DataContext context) { if (context.Todos.Any()) return; var Todos = new List<Todo> { new Todo { Title = "Past Todo", completed = false, Description = "Description of the Past Todo Task" }, new Todo { Title = "Present Todo", completed = true, Description = "Description of the Present Todo Task" }, new Todo { Title = "Future Todo", completed = false, Description = "Description of the Future Todo Task" } }; await context.Todos.AddRangeAsync(Todos); await context.SaveChangesAsync(); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Text; namespace DemoFinalExam2 { class Program { static void Main(string[] args) { List<string> input = Console.ReadLine().Split("&").ToList(); string regex = @"^[\d\w]{16}$|^[\d\w]{25}$"; StringBuilder sb = new StringBuilder(); List<string> final = new List<string>(); foreach (var item in input) { if (Regex.IsMatch(item, regex)) { char[] process = item.ToCharArray(); // Console.WriteLine(string.Join("", process)); if (process.Length==25) { string append = string.Empty; for (int i = 0; i < process.Length; i++) { if (i>0 && i%5==0) { append+="-"; } if (!char.IsDigit(process[i])) { append+=process[i].ToString().ToUpper(); } if (Char.IsDigit(process[i])) { int b = int.Parse(process[i].ToString()); int a = 9 - b; append+=a; } } //Console.WriteLine(append); final.Add(append); } else if (process.Length==16) { string append = string.Empty; for (int i = 0; i < process.Length; i++) { if (i > 0 && i % 4 == 0) { append += "-"; } if (!char.IsDigit(process[i])) { append += process[i].ToString().ToUpper(); } if (Char.IsDigit(process[i])) { int b = int.Parse(process[i].ToString()); int a = 9 - b; append += a; } } final.Add(append); } } } Console.WriteLine(string.Join(", ",final)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TBQuestGame.Models { public class Character { #region ENUMERABLES public enum SpecialMove { Fireball, Tackle, Sweep, Powerpush, Uppercut, Megapunch, } #endregion #region FIELDS private int id; private string name; private int locationId; private int health; private SpecialMove specialMove; #endregion #region PROPERTIES public int _id { get { return id; } set { id = value; } } public string _name { get { return name; } set { name = value; } } public int _locationId { get { return locationId; } set { locationId = value; } } public int _health { get { return health; } set { health = value; } } public SpecialMove _specialMove { get { return specialMove; } set { specialMove = value; } } #endregion #region CONSTRUCTORS public Character() { } public Character(string name, SpecialMove specialMove, int locationId, int health) { _name = name; _specialMove = specialMove; _locationId = locationId; _health = health; } #endregion #region METHODS public virtual string DefaultGreeting() { return $"Hello, my name is {_name}. My special move is {_specialMove}. I am ready to fight!"; } #endregion } }
using System; class NumbersFromOneToN { static void Main() { Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!"); while (true) { int iNum; Console.Write("Enter integer number: "); if (int.TryParse(Console.ReadLine(), out iNum)) { for (int i = 0; i < iNum; i++) { Console.WriteLine(i+1); } } else { Console.WriteLine("Only numbers."); } } } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Text; namespace PingoSnake { class SpawnController { public SpawnController() { } public virtual void Update(GameTime gameTime) { } } }
using StardewValley; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AshleyMod { public class CustomEvent : Event { public int EventID = -1; public CustomEvent(string eventString, int eventID = -1) :base(eventString, eventID) { this.EventID = eventID; } public CustomEvent() :base() { } } }
using System.ComponentModel.DataAnnotations.Schema; namespace CodeCityCrew.Settings.Model { [Table("Setting")] public class Setting { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public string Id { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public string Value { get; set; } /// <summary> /// Gets or sets the name of the environment. /// </summary> /// <value> /// The name of the environment. /// </value> public string EnvironmentName { get; set; } /// <summary> /// Gets or sets the name of the assembly. /// </summary> /// <value> /// The name of the assembly. /// </value> public string AssemblyName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightingBook.Tests.Api.Product.Dto.GetItinerary.Request { public class Passenger { public string HomeAirportCode { get; set; } public string Identifier { get; set; } public string ClientId { get; set; } public string Title { get; set; } public object Salutation { get; set; } public object Firstname { get; set; } public object Lastname { get; set; } public object Email { get; set; } public object Mobile { get; set; } public object EmployeeNumber { get; set; } public object CostCentreCode { get; set; } public object CostCentreName { get; set; } public object DepartmentCode { get; set; } public object DebtorIdentifier { get; set; } public object EmployeeCode { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GraphicalEditor.DTO { public class EquipmentWithRoomDTO { public int IdEquipment { get; set; } public int RoomNumber { get; set; } public int Quantity { get; set; } public string EquipmentName { get; set; } public bool IsEquipmentConsumable { get; set; } public EquipmentWithRoomDTO() {} public EquipmentWithRoomDTO(int idEquipment, int roomNumber, int quantity, string equipmentName) { this.IdEquipment = idEquipment; this.RoomNumber = roomNumber; this.Quantity = quantity; this.EquipmentName = equipmentName; } } }
using FPGADeveloperTools.Common.Model.Ports; namespace FPGADeveloperTools.NewTCWindow.Model { public class PortSel { private Port port; private bool isSel; public Port Port { get { return this.port; } } public string Name { get { return this.port.Name; } } public bool IsSel { get { return this.isSel; } set { this.isSel = value; } } public PortSel(Port port) { this.port = port; this.isSel = false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class SpinMechanisum : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { /// <summary> /// Hole player Body it has Rigitbody Atach /// </summary> [HideInInspector] public GameObject fullBody; /// <summary> /// PlayerAnimationControlar /// </summary> private PlayerJumpMechanism playerJumpMechanism; /// <summary> /// Score Manger Handel all Score Related Operatios Use up upade Player is rotate or not /// </summary> public ScoreManager SM; //player is spining or not public bool spin = false; private Rigidbody FullBodyRigitbody; //all player iks Script private List<SingleIkMove> PlayerIK = new List<SingleIkMove>(); void Start() { //find player jump playerJumpMechanism = GetComponent<PlayerJumpMechanism>(); //upate self fullbody from playerJumpMechanism fullBody = playerJumpMechanism.fullBody; FullBodyRigitbody = fullBody.GetComponent<Rigidbody>(); //find plyer Iks a get SingleIKMove Script GetSingleIKMove(); } /// <summary> /// Finding PlayerIK GameObject and gating SingleIkMove Script and Adding To PlayerIK List /// </summary> private void GetSingleIKMove() { GameObject[] go = GameObject.FindGameObjectsWithTag("PlayerIk"); foreach (GameObject d in go) { SingleIkMove sm = d.GetComponent<SingleIkMove>(); PlayerIK.Add(sm); } } /// <summary> /// Rotating body /// </summary> private void FixedUpdate() { if (spin) { fullBody.transform.Rotate(fullBody.transform.right, -11f); // rotating main body //fullBody.transform.Rotate(fullBody.transform.right, -10f); // rotating main body } } public void OnPointerDown(PointerEventData eventData) { if (playerJumpMechanism.ClickCounter == 2) { spin = true; SM.FlipStart = true; BendPose(spin); } } /// <summary> /// /// </summary> /// <param name="eventData"></param> public void OnPointerUp(PointerEventData eventData) { if (spin &&playerJumpMechanism.ClickCounter == 2) { FullBodyRigitbody.AddTorque(fullBody.transform.right * -3f, ForceMode.VelocityChange);//adding extar tork fter relesing button spin = false; SM.FlipStart = false; BendPose(spin); } } /// <summary> /// Giveing instruction Player Iks Go go its Bend position, /// </summary> /// <param name="fl"> </param> private void BendPose(bool fl) { foreach (SingleIkMove sm in PlayerIK) { sm.Spin = fl; } } //*******************************************reset public void Retry() { spin = false; BendPose(spin); } }
using FichaTecnica.Dominio; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FichaTecnica.Models { public class MembroDetalheProjetoModel { public int Id { get; set; } public string Foto { get; set; } public Cargo cargo { get; set; } public string Nome { get; set; } public string Email { get; set; } public ICollection<Projeto> Projetos { get; set; } public int TotalComentariosPosivo { get; set; } public int TotalComentarioNegativo { get; set; } public GraficoAtividadesModel LinksGithub { get; set; } public DateTime DataUltimoCommit { get; set; } public string CommitSHA { get; set; } public string CommitLink { get; set; } public string Commitmenssage { get; set; } public MembroDetalheProjetoModel(Membro entity) { this.Id = entity.Id; this.Foto = entity.Foto; this.cargo = entity.Cargo; this.Nome = entity.Nome; this.Email = entity.Email; this.Projetos = entity.Projetos; } } }
using System.ComponentModel.DataAnnotations; namespace Uintra.Attributes { public class RequiredVirtualAttribute : RequiredAttribute { public bool IsRequired { get; set; } = true; public override bool IsValid(object value) { if (IsRequired) return base.IsValid(value); return true; } public override bool RequiresValidationContext => IsRequired; } }
using Alabo.Framework.Core.WebApis.Controller; using Alabo.Framework.Core.WebApis.Filter; using Alabo.Industry.Cms.Articles.Domain.Entities; using Alabo.Industry.Cms.Articles.Domain.Services; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; namespace Alabo.Industry.Cms.Articles.Controllers { [ApiExceptionFilter] [Route("Api/About/[action]")] public class ApiAboutController : ApiBaseController<About, ObjectId> { public ApiAboutController() { BaseService = Resolve<IAboutService>(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Dev_QuitandReload : MonoBehaviour { void Update() { if (Input.GetKeyDown(KeyCode.Tilde)) { Scene loadedLevel = SceneManager.GetActiveScene (); SceneManager.LoadScene (loadedLevel.buildIndex); } if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.Runtime.InteropServices; using System.Data.OleDb; using System.Threading; using Apache.NMS; using Apache.NMS.ActiveMQ; using Apache.NMS.ActiveMQ.Commands; namespace IRAP.PLC.Collection { public partial class frmMainPLCCollection : Form { [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); private CustomSendToESBThread dataCollect = null; private bool canClosed = false; private bool boolRunning = false; private OleDbConnection connection = null; public frmMainPLCCollection() { InitializeComponent(); } #region 自定义函数 private void ShowForm() { Show(); ShowInTaskbar = true; WindowState = FormWindowState.Normal; Activate(); SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle); } private void HideForm() { Hide(); ShowInTaskbar = false; } #endregion private void notifyIcon_DoubleClick(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) ShowForm(); else { WindowState = FormWindowState.Minimized; HideForm(); } } private void frmMainPLCCollection_FormClosing(object sender, FormClosingEventArgs e) { if (canClosed) e.Cancel = false; else { e.Cancel = true; HideForm(); } } private void frmMainPLCCollection_Resize(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) HideForm(); } private void tsmiQuit_Click(object sender, EventArgs e) { canClosed = true; Close(); } private void frmMainPLCCollection_Load(object sender, EventArgs e) { notifyIcon.Text = Text; } private void btnStart_Click(object sender, EventArgs e) { if (SystemParams.Instance.DataFileName == "") { MessageBox.Show( "工艺参数数据库文件没有配置!", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (dataCollect != null) dataCollect = null; switch (SystemParams.Instance.DeviceType) { case 0: dataCollect = new DC_CPPlating_NB(mmoLogs); break; case 1: dataCollect = new DC_Baking_NB(mmoLogs); break; case 2: dataCollect = new DC_Baking_NMT(mmoLogs); break; case 3: dataCollect = new DC_Leak(mmoLogs); break; case 4: dataCollect = new DC_Tighten(mmoLogs); break; } if (dataCollect == null) { MessageBox.Show( "不支持当前选择的设备类型", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { dataCollect.StartWatch(); btnStart.Enabled = false; btnStop.Enabled = true; } } private void contextMenuStrip_Opening(object sender, CancelEventArgs e) { tsmiConfiguration.Enabled = !boolRunning; } private void tsmiConfiguration_Click(object sender, EventArgs e) { using (frmSystemParams frmParams = new frmSystemParams()) { frmParams.ShowDialog(); } } private void btnStop_Click(object sender, EventArgs e) { if (dataCollect != null) { if (dataCollect.Enabled) { dataCollect.Enabled = false; btnStart.Enabled = true; btnStop.Enabled = false; } } } private void timer_Tick(object sender, EventArgs e) { timer.Enabled = false; try { if (connection == null) { connection = new OleDbConnection( string.Format( "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=\"{0}\";Persist Security Info=false", SystemParams.Instance.DataFileName)); connection.Open(); } try { switch (SystemParams.Instance.DeviceCode) { case "BF-0016": case "BF-0824": case "BF-0017": GetData_NB(connection, SystemParams.Instance.DeviceCode); break; case "BF-0825": GetData_NMT(connection); break; } } catch (Exception error) { } } finally { timer.Enabled = true; } } private void GetData_NMT(OleDbConnection conn) { int deltaTimeSpan = SystemParams.Instance.DeltaTimeSpan; DateTime beginDT = SystemParams.Instance.BeginDT; DateTime endDT = beginDT.AddMinutes(deltaTimeSpan); if (endDT < DateTime.Now) { #region 采集烤箱1的数据 { string sql = string.Format( "SELECT * FROM 烤箱1存盘数据_MCGS " + "WHERE MCGS_Time >= #{0}# AND MCGS_Time <= #{1}#", beginDT, endDT); OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string xml = ""; if (reader["Oven1_Product1"].ToString().Trim() != "") { xml = string.Format( "<ROOT>" + "<Row T133Code=\"{0}\" Time=\"{1}\" MCGS_TimeMS=\"{2}\" " + "第1台PV=\"{3}\" 第2台PV=\"{4}\" 第3台PV=\"{5}\" " + "第4台PV=\"{6}\" 第5台PV=\"{7}\" ProductNo1=\"{8}\" " + "ProductNo2=\"{9}\" ProductNo3=\"{10}\" Productno4=\"{11}\" " + "ProductNo5=\"{12}\" />" + "</ROOT>", "BF-0825-1", reader["MCGS_Time"].ToString(), reader["MCGS_TimeMS"].ToString(), reader["一台PV"].ToString(), reader["二台PV"].ToString(), reader["三台PV"].ToString(), reader["四台PV"].ToString(), reader["五台PV"].ToString(), reader["Oven1_Product1"].ToString(), reader["Oven1_Product2"].ToString(), reader["Oven1_Product3"].ToString(), reader["Oven1_Product4"].ToString(), reader["Oven1_Product5"].ToString()); SendToESB(xml); } Thread.Sleep(100); } } #endregion #region 采集烤箱2的数据 { string sql = string.Format( "SELECT * FROM 烤箱2存盘数据_MCGS " + "WHERE MCGS_Time >= #{0}# AND MCGS_Time <= #{1}#", beginDT, endDT); OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string xml = ""; if (reader["Oven2_Product1"].ToString().Trim() != "") { xml = string.Format( "<ROOT>" + "<Row T133Code=\"{0}\" Time=\"{1}\" MCGS_TimeMS=\"{2}\" " + "第6台PV=\"{3}\" 第7台PV=\"{4}\" 第8台PV=\"{5}\" " + "第9台PV=\"{6}\" 第10台PV=\"{7}\" ProductNo1=\"{8}\" " + "ProductNo2=\"{9}\" ProductNo3=\"{10}\" Productno4=\"{11}\" " + "ProductNo5=\"{12}\" />" + "</ROOT>", "BF-0825-2", reader["MCGS_Time"].ToString(), reader["MCGS_TimeMS"].ToString(), reader["六台PV"].ToString(), reader["七台PV"].ToString(), reader["八台PV"].ToString(), reader["九台PV"].ToString(), reader["十台PV"].ToString(), reader["Oven2_Product1"].ToString(), reader["Oven2_Product2"].ToString(), reader["Oven2_Product3"].ToString(), reader["Oven2_Product4"].ToString(), reader["Oven2_Product5"].ToString()); SendToESB(xml); Thread.Sleep(100); } } } #endregion #region 采集烤箱3的数据 { string sql = string.Format( "SELECT * FROM 烤箱3存盘数据_MCGS " + "WHERE MCGS_Time >= #{0}# AND MCGS_Time <= #{1}#", beginDT, endDT); OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string xml = ""; if (reader["Oven3_Product1"].ToString().Trim() != "") { xml = string.Format( "<ROOT>" + "<Row T133Code=\"{0}\" Time=\"{1}\" MCGS_TimeMS=\"{2}\" " + "第11台PV=\"{3}\" 第12台PV=\"{4}\" 第13台PV=\"{5}\" " + "第14台PV=\"{6}\" 第15台PV=\"{7}\" ProductNo1=\"{8}\" " + "ProductNo2=\"{9}\" ProductNo3=\"{10}\" Productno4=\"{11}\" " + "ProductNo5=\"{12}\" />" + "</ROOT>", "BF-0825-3", reader["MCGS_Time"].ToString(), reader["MCGS_TimeMS"].ToString(), reader["十一台PV"].ToString(), reader["十二台PV"].ToString(), reader["十三台PV"].ToString(), reader["十四台PV"].ToString(), reader["十五台PV"].ToString(), reader["Oven3_Product1"].ToString(), reader["Oven3_Product2"].ToString(), reader["Oven3_Product3"].ToString(), reader["Oven3_Product4"].ToString(), reader["Oven3_Product5"].ToString()); SendToESB(xml); Thread.Sleep(100); } } } #endregion SystemParams.Instance.BeginDT = endDT; } } private void GetData_NB(OleDbConnection conn, string DeviceCode) { int deltaTimeSpan = SystemParams.Instance.DeltaTimeSpan; DateTime beginDT = SystemParams.Instance.BeginDT; DateTime endDT = beginDT.AddMinutes(deltaTimeSpan); if (endDT < DateTime.Now) { #region 采集入线表的数据 { string sql = string.Format( "SELECT * FROM 入线表 " + "WHERE CDATE(出线时间) BETWEEN #{0}# AND #{1}#", beginDT, endDT); OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string xml = string.Format( "<ROOT>" + "<Row T133Code=\"{0}\" 飞巴号=\"{1}\" 零件号码=\"{2}\" " + "零件批次=\"{3}\" 零件数量=\"{4}\" 入线时间=\"{5}\" " + "出线时间=\"{6}\" />" + "</ROOT>", DeviceCode, reader["飞巴号"].ToString(), reader["零件号码"].ToString(), reader["零件批次"].ToString(), reader["零件数量"].ToString(), reader["入线时间"].ToString(), reader["出线时间"].ToString()); SendToESB(xml); Thread.Sleep(100); } } #endregion #region 采集线状态历史的数据 { string sql = string.Format( "SELECT * FROM 线状态历史 " + "WHERE CDATE(时间) BETWEEN #{0}# AND #{1}#", beginDT, endDT); OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string xml = ""; if (reader["Oven1_Product1"].ToString().Trim() != "") { xml = string.Format( "<ROOT>" + "<Row T133Code=\"{0}\" 槽工位号=\"{1}\" 运行工步=\"{2}\" " + "槽位名称=\"{3}\" 零件号码=\"{4}\" 零件批次=\"{5}\" " + "设定时间=\"{6}\" 入槽时间=\"{7}\" 设定温度=\"{8}\" " + "实际温度=\"{9}\" 设定电流=\"{10}\" 实际电流=\"{11}\" " + "实际电压=\"{12}\" 零件数量=\"{13}\" 安培小时=\"{14}\" " + "飞巴号=\"{15}\" 时间=\"{16}\" 设定温度波形=\"{17}\" " + "实际温度波形=\"{18}\" 设定电流波形=\"{19}\" 实际电流波形=\"{20}\" " + "实际电压波形=\"{21}\" />" + "</ROOT>", DeviceCode, reader["槽工位号"].ToString(), reader["运行工步"].ToString(), reader["槽位名称"].ToString(), reader["零件号码"].ToString(), reader["零件批次"].ToString(), reader["设定时间"].ToString(), reader["入槽时间"].ToString(), reader["设定温度"].ToString(), reader["实际温度"].ToString(), reader["设定电流"].ToString(), reader["实际电流"].ToString(), reader["实际电压"].ToString(), reader["零件数量"].ToString(), reader["安培小时"].ToString(), reader["飞巴号"].ToString(), reader["时间"].ToString(), reader["设定温度波形"].ToString(), reader["实际温度波形"].ToString(), reader["设定电流波形"].ToString(), reader["实际电流波形"].ToString(), reader["实际电压波形"].ToString()); SendToESB(xml); Thread.Sleep(100); } } } #endregion SystemParams.Instance.BeginDT = endDT; } } private IConnectionFactory factory = null; private void SendToESB(string bodyXML) { string brokerUri = string.Format( "failover://({0})?&transport.startupMaxReconnectAttempts=2&" + "transport.initialReconnectDelay=10", SystemParams.Instance.ActiveMQ_URI); try { if (factory == null) factory = new ConnectionFactory(brokerUri); using (IConnection esbConn = factory.CreateConnection()) { using (ISession session = esbConn.CreateSession()) { IMessageProducer prod = session.CreateProducer( new ActiveMQQueue( SystemParams.Instance.ActiveMQ_QueueName)); ITextMessage message = prod.CreateTextMessage(); message.Text = string.Format( "<?xml version=\"1.0\"?>" + "<Softland><Head><ExCode>MES2DPA</ExCode>" + "<CorrelationID>{0}</CorrelationID>" + "<CommunityID>60002</CommunityID>" + "<SysLogID>1</SysLogID>" + "<UserCode>Admin</UserCode>" + "<AgencyLeaf>1</AgencyLeaf>" + "<RoleLeaf>2</RoleLeaf>" + "<StationID>60002MNGMT001</StationID>" + "</Head><Body>{1}</Body></Softland>", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), bodyXML); message.Properties.SetString("Filter", "Device"); message.Properties.SetString("ESBServerAddr", "http://192.168.57.210:16911/RESTFul/SendMQ/"); message.Properties.SetString("ExCode", "MES2DPA"); prod.Send(message, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.MinValue); } } } catch (Exception error) { } } } }
using EmberKernel.Services.Statistic.DataSource.Variables; using EmberKernel.Services.Statistic.DataSource.Variables.Value; using System; using System.Collections.Generic; using System.Collections.Specialized; namespace EmberKernel.Services.Statistic { public interface IDataSource : IList<Variable>, INotifyCollectionChanged, IKernelService { event Action<IEnumerable<Variable>> OnMultiDataChanged; IEnumerable<Variable> Variables { get; } bool TryGetVariable(string id, out Variable variable); IEnumerable<Variable> GetVariables(IEnumerable<string> variableIds); bool IsRegistered(Variable variable); void Register(Variable variable, IValue fallback); void Unregister(Variable variable); void Publish(Variable variable); void Publish(string id, IValue value); void Publish(IEnumerable<Variable> variables); } }
using DemoCode.Models; using DemoCode.Services; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace DemoCode { public class ToolTipService : IToolTipService { #region Public API /// <summary> /// Build ToolTip Object /// </summary> /// <param name="applicationUrlRoot">Root website url</param> /// <param name="applicationPathRoot">Root website path</param> /// <param name="toolTipFolder">ToolTip folder path</param> /// <returns>ToolTip Object</returns> public ToolTip GetToolTip(string applicationUrlRoot, string applicationPathRoot, string toolTipFolder) { var toolTipMarkupText = ToolTipUtil.GetToolTipMarkupText(toolTipFolder); var toolTipImagesUrl = ToolTipUtil.BuildUrlsToFilesFromFolder(applicationUrlRoot, applicationPathRoot, toolTipFolder); return new ToolTip { Markup = toolTipMarkupText, ImagesUrl = toolTipImagesUrl }; } /// <summary> /// Get toolTip folder /// </summary> /// <param name="applicationPathRoot">Root website path</param> /// <param name="language">toolTip language</param> /// <param name="folders">all folder names from UNDER the language folder to the final folder that have the toolTips files</param> /// <returns>ToolTip Folder Path</returns> public string GetToolTipFolderPath(string applicationPathRoot, string language, params string[] folders) { var path = new string[] { applicationPathRoot, "ToolTips", language }; return Path.Combine(path.Concat(folders).ToArray()); } #endregion } }
using System; using System.Diagnostics; using System.IO; using System.Threading; using Serilog; using Serilog.Core; namespace Titan.Logging { public static class LogCreator { private static DirectoryInfo _logDir; static LogCreator() { _logDir = new DirectoryInfo(Path.Combine( Titan.Instance != null ? Titan.Instance.Directory.ToString() : Environment.CurrentDirectory, "logs" )); } public static Logger Create(string name) { if (Titan.Instance != null && Titan.Instance.Options.Debug) { return CreateDebugLogger(name); } return CreateInfoLogger(name); } public static Logger CreateInfoLogger(string name) { return new LoggerConfiguration() .WriteTo.Console( outputTemplate: "{Timestamp:HH:mm:ss} [{Thread}] {Level:u} {Name} - {Message}{NewLine}{Exception}" ) .WriteTo.Async(c => c.RollingFile( Path.Combine(_logDir.ToString(), name + "-{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u}] {Name} {ThreadId} - {Message}{NewLine}{Exception}" )) .MinimumLevel.Information() .Enrich.WithProperty("Name", name) .Enrich.WithProperty("Thread", Thread.CurrentThread.Name) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); } public static Logger CreateDebugLogger(string name) { return new LoggerConfiguration() .WriteTo.Console( outputTemplate: "{Timestamp:HH:mm:ss} [{Thread}] {Level:u} {Name} - {Message}{NewLine}{Exception}" ) .WriteTo.Async(c => c.RollingFile( Path.Combine(_logDir.ToString(), name + "-{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u}] {Name} {ThreadId} - {Message}{NewLine}{Exception}" )) .MinimumLevel.Debug() .Enrich.WithProperty("Name", name) .Enrich.WithProperty("Thread", Thread.CurrentThread.Name) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); } public static Logger CreateDebugFileLogger(string name) { return new LoggerConfiguration() .WriteTo.Async(c => c.RollingFile( Path.Combine(_logDir.ToString(), name + "-{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u}] {Name} {ThreadId} - {Message}{NewLine}{Exception}" )) .MinimumLevel.Debug() .Enrich.WithProperty("Name", name) .Enrich.WithProperty("Thread", Thread.CurrentThread.Name) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); } public static Logger CreateQuartzLogger() { return new LoggerConfiguration() .WriteTo.Console( outputTemplate: "{Timestamp:HH:mm:ss} [{Thread}] {Level:u} {Name} - {Message}{NewLine}{Exception}" ) .WriteTo.Async(c => c.RollingFile( Path.Combine(_logDir.ToString(), "Quartz.Net-Scheduler-{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u}] {Name} {ThreadId} - {Message}{NewLine}{Exception}" )) .MinimumLevel.Debug() .Enrich.WithProperty("Name", "Quartz.NET Scheduler") .Enrich.WithProperty("Thread", Thread.CurrentThread.Name) .Enrich.FromLogContext() .Enrich.WithThreadId() .Filter.ByExcluding(logEvent => logEvent.RenderMessage().Contains("Batch acquisition") && logEvent.RenderMessage().Contains("triggers")) .CreateLogger(); } public static Logger Create() { var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType; return Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)"); } } }
using System; using Tomelt.ContentManagement; namespace Tomelt.Tasks.Scheduling { public interface IScheduledTask { string TaskType { get; } DateTime? ScheduledUtc { get; } ContentItem ContentItem { get; } } }
//#define DISABLE_SHOW_MESSAGE // 選擇一種等待手臂動作完成的做法,都不選就是使用預設方法。 #define USE_CALLBACK_MOTION_STATE_WAIT // #define USE_MOTION_STATE_WAIT #if (DISABLE_SHOW_MESSAGE) #warning Message is disabled. #endif using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Windows.Forms; using Timer = System.Windows.Forms.Timer; using Basic; using Basic.Message; using Arm.Action; using Arm.Type; using SDKHrobot; namespace Arm { /// <summary> /// 上銀機械手臂控制實作。 /// </summary> public class HiwinArm : IArm { #if (USE_CALLBACK_MOTION_STATE_WAIT) private static bool Waiting = false; #endif public HiwinArm(string armIp, IMessage message) { Ip = armIp; Message = message; #if (!USE_MOTION_STATE_WAIT && !USE_CALLBACK_MOTION_STATE_WAIT) InitTimer(); #endif } public int Id { get; private set; } public string Ip { get; private set; } #region - Default Position - public static double[] DescartesHomePosition { get; } = { 0, 368, 294, 180, 0, 90 }; public static double[] JointHomePosition { get; } = { 0, 0, 0, 0, 0, 0 }; #endregion - Default Position - #region - Speed and Acceleration - public int Acceleration { get { int acc; if (Connected) { acc = HRobot.get_acc_dec_ratio(Id); if (acc == -1) { Message.Show("取得手臂加速度時出錯。", LoggingLevel.Error); } } else { acc = -1; Message.Show("手臂未連線。", LoggingLevel.Info); } return acc; } set { if (value > 100 || value < 1) { Message.Show($"手臂加速度應為1% ~ 100%之間。輸入值為: {value}", LoggingLevel.Warn); } else { if (Connected) { var returnCode = HRobot.set_acc_dec_ratio(Id, value); // 執行HRobot.set_acc_dec_ratio時會固定回傳錯誤代碼4000。 IsErrorAndHandler(returnCode, 4000); } else { Message.Show("手臂未連線。", LoggingLevel.Info); } } } } public int Speed { get { int speed; if (Connected) { speed = HRobot.get_override_ratio(Id); if (speed == -1) { Message.Show("取得手臂速度時出錯。", LoggingLevel.Error); } } else { speed = -1; Message.Show("手臂未連線。", LoggingLevel.Info); } return speed; } set { if (value > 100 || value < 1) { Message.Show($"手臂速度應為1% ~ 100%之間。輸入值為: {value}", LoggingLevel.Warn); } else { if (Connected) { var returnCode = HRobot.set_override_ratio(Id, value); IsErrorAndHandler(returnCode); } else { Message.Show("手臂未連線。", LoggingLevel.Info); } } } } #endregion - Speed and Acceleration - #region - Motion - public void Do(IArmAction armAction) { Message.Log(armAction.Message, LoggingLevel.Info); armAction.ArmId = Id; var success = armAction.Do(); if (success && armAction.NeedWait) { WaitForMotionComplete(); } } private void WaitForMotionComplete() { #if (USE_CALLBACK_MOTION_STATE_WAIT) // 使用 HRSDK 中的 delegate CallBackFun 來接收從手臂回傳的資訊, // 並從中取得 motion_state 來判斷手臂是否還在運動中。 Waiting = true; while (Waiting) { } #elif (USE_MOTION_STATE_WAIT) // 使用 HRSDK 中的 method get_motion_state() 來取得手臂 motion_state 來判斷手臂是否還在運動中。 // motion_state = 1: Idle. while (HRobot.get_motion_state(Id) != 1) { Thread.Sleep(200); } #endif } /// <summary> /// 等待手臂運動完成。 /// </summary> /// <param name="targetPosition"></param> /// <param name="coordinateType"></param> private void WaitForMotionComplete(double[] targetPosition, CoordinateType coordinateType) { #if (USE_CALLBACK_MOTION_STATE_WAIT) // 使用 HRSDK 中的 delegate CallBackFun 來接收從手臂回傳的資訊, // 並從中取得 motion_state 來判斷手臂是否還在運動中。 Waiting = true; while (Waiting) { // 等待 EventFun() 將 Waiting 的值改成 false 即跳出迴圈。 // 此 Thread.Sleep() 不一定要有。 Thread.Sleep(50); } #elif (USE_MOTION_STATE_WAIT) // 使用 HRSDK 中的 method get_motion_state() 來取得手臂 motion_state 來判斷手臂是否還在運動中。 // motion_state = 1: Idle. while (HRobot.get_motion_state(Id) != 1) { Thread.Sleep(200); } #else // 使用比較目標座標及手臂目前的座標來判斷手臂是否還在運動中。 double[] nowPosition = new double[6]; ActionTimer.Enabled = true; // For無限回圈。 for (; ; ) { if (TimeCheck % 1 == 0 && positionType == PositionType.Descartes) { foreach (int k in nowPosition) { // 取得目前的笛卡爾座標。 HRobot.get_current_position(Id, nowPosition); } if (Math.Abs(targetPosition[0] - nowPosition[0]) < 0.01 && Math.Abs(targetPosition[1] - nowPosition[1]) < 0.01 && Math.Abs(targetPosition[2] - nowPosition[2]) < 0.01 && Math.Abs(Math.Abs(targetPosition[3]) - Math.Abs(nowPosition[3])) < 0.01 && Math.Abs(Math.Abs(targetPosition[4]) - Math.Abs(nowPosition[4])) < 0.01 && Math.Abs(Math.Abs(targetPosition[5]) - Math.Abs(nowPosition[5])) < 0.01) { // 跳出For無限回圈。 break; } } else if (TimeCheck % 1 == 0 && positionType == PositionType.Joint) { foreach (int k in nowPosition) { // 取得目前的關節座標。 HRobot.get_current_joint(Id, nowPosition); } if (Math.Abs(targetPosition[0] - nowPosition[0]) < 0.01 && Math.Abs(targetPosition[1] - nowPosition[1]) < 0.01 && Math.Abs(targetPosition[2] - nowPosition[2]) < 0.01 && Math.Abs(targetPosition[3] - nowPosition[3]) < 0.01 && Math.Abs(targetPosition[4] - nowPosition[4]) < 0.01 && Math.Abs(targetPosition[5] - nowPosition[5]) < 0.01) { // 跳出For無限回圈。 break; } } } ActionTimer.Enabled = false; TimeCheck = 0; #endif } #endregion - Motion - #region - Connect and Disconnect - /// <summary> /// 此 delegate 必須要是 static,否則手臂動作有可能會出現問題。 /// </summary> private static readonly HRobot.CallBackFun CallBackFun = EventFun; public bool Connected { get; private set; } = false; public bool Connect() { // 連線。測試連線設定:("127.0.0.1", 1, CallBackFun); Id = HRobot.open_connection(Ip, 1, CallBackFun); // 0 ~ 65535為有效裝置ID。 if (Id >= 0 && Id <= 65535) { int alarmState; int motorState; int connectionLevel; // 將所有錯誤代碼清除。 alarmState = HRobot.clear_alarm(Id); // 錯誤代碼300代表沒有警報,無法清除警報。 alarmState = alarmState == 300 ? 0 : alarmState; // 設定控制器: 1為啟動,0為關閉。 HRobot.set_motor_state(Id, 1); Thread.Sleep(500); // 取得控制器狀態。 motorState = HRobot.get_motor_state(Id); // 取得連線等級。 connectionLevel = HRobot.get_connection_level(Id); var text = "連線成功!\r\n" + $"手臂ID: {Id}\r\n" + $"連線等級: {(connectionLevel == 0 ? "觀測者" : "操作者")}\r\n" + $"控制器狀態: {(motorState == 0 ? "關閉" : "開啟")}\r\n" + $"錯誤代碼: {alarmState}"; Message.Show(text, "連線", MessageBoxButtons.OK, MessageBoxIcon.None); Connected = true; return true; } else { string message; switch (Id) { case -1: message = "-1:連線失敗。"; break; case -2: message = "-2:回傳機制創建失敗。"; break; case -3: message = "-3:無法連線至Robot。"; break; case -4: message = "-4:版本不相符。"; break; default: message = $"未知的錯誤代碼: {Id}"; break; } Message.Show($"無法連線!\r\n{message}", LoggingLevel.Error); Connected = false; return false; } } public bool Disconnect() { int alarmState; int motorState; // 將所有錯誤代碼清除。 alarmState = HRobot.clear_alarm(Id); // 錯誤代碼300代表沒有警報,無法清除警報。 alarmState = alarmState == 300 ? 0 : alarmState; // 設定控制器: 1為啟動,0為關閉。 HRobot.set_motor_state(Id, 0); Thread.Sleep(500); // 取得控制器狀態。 motorState = HRobot.get_motor_state(Id); // 關閉手臂連線。 HRobot.disconnect(Id); var text = "斷線成功!\r\n" + $"控制器狀態: {(motorState == 0 ? "關閉" : "開啟")}\r\n" + $"錯誤代碼: {alarmState}"; Message.Show(text, "斷線", MessageBoxButtons.OK, MessageBoxIcon.None); Connected = false; return true; } /// <summary> /// 控制器回傳。 /// </summary> /// <param name="cmd"></param> /// <param name="rlt"></param> /// <param name="Msg"></param> /// <param name="len"></param> private static void EventFun(UInt16 cmd, UInt16 rlt, ref UInt16 Msg, int len) { // 該 Method 的內容請參考 HRSDK-SampleCode: 11.CallbackNotify。 // 此處不受 IMessage 影響。 // Get info. String info = ""; unsafe { fixed (UInt16* p = &Msg) { for (int i = 0; i < len; i++) { info += (char)p[i]; } } } var infos = info.Split(','); // Show in Console. Console.WriteLine($"Command:{cmd}, Result:{rlt}"); switch (cmd) { case 0 when rlt == 4702: Console.WriteLine($"HRSS Mode:{infos[0]}\r\n" + $"Operation Mode:{infos[1]}\r\n" + $"Override Ratio:{infos[2]}\r\n" + $"Motor State:{infos[3]}\r\n" + $"Exe File Name:{infos[4]}\r\n" + $"Function Output:{infos[5]}\r\n" + $"Alarm Count:{infos[6]}\r\n" + $"Keep Alive:{infos[7]}\r\n" + $"Motion Status:{infos[8]}\r\n" + $"Payload:{infos[9]}\r\n" + $"Speed:{infos[10]}\r\n" + $"Position:{infos[11]}\r\n" + $"Coor:{infos[14]},{infos[15]},{infos[16]},{infos[17]},{infos[18]},{infos[19]}\r\n" + $"Joint:{infos[20]},{infos[21]},{infos[22]},{infos[23]},{infos[24]},{infos[25]}\r\n"); #if (USE_CALLBACK_MOTION_STATE_WAIT) // Motion state=1: Idle. Waiting = infos[8] != "1"; #endif break; case 4011 when rlt != 0: #if (!DISABLE_SHOW_MESSAGE) MessageBox.Show("Update fail. " + rlt, "HRSS update callback", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); #endif break; } } #endregion - Connect and Disconnect - #region - Timer - private Timer ActionTimer = null; private int TimeCheck = 0; /// <summary> /// 初始化計時器。 /// </summary> private void InitTimer() { ActionTimer = new Timer { Interval = 50, Enabled = false }; ActionTimer.Tick += (s, e) => ++TimeCheck; } #endregion - Timer - #region - Message - private IMessage Message { get; set; } /// <summary> /// 如果出現錯誤,顯示錯誤代碼。 /// </summary> /// <param name="code"></param> /// <param name="successCode"></param> /// <param name="ignoreCode"></param> /// <returns> /// 是否出現錯誤。<br/> /// ● true:出現錯誤。<br/> /// ● false:沒有出現錯誤。 /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsErrorAndHandler(int code, int ignoreCode = 0, int successCode = 0) { if (code == successCode || code == ignoreCode) { // Successful. return false; } else { // Not successful. Message.Show($"上銀機械手臂控制錯誤。\r\n錯誤代碼:{code}", LoggingLevel.Error); return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ShowUnknownCoordinateType() { Message.Show($"錯誤的座標類型。\r\n" + $"座標類型應為:{CoordinateType.Descartes} 或是 {CoordinateType.Joint}", LoggingLevel.Warn); } #endregion - Message - #region - Others - public void ClearAlarm() { var returnCode = HRobot.clear_alarm(Id); // 錯誤代碼300代表沒有警報,無法清除警報 IsErrorAndHandler(returnCode, 300); } public double[] GetPosition(CoordinateType type = CoordinateType.Descartes) { var position = new double[6]; Func<int, double[], int> action; switch (type) { case CoordinateType.Descartes: action = HRobot.get_current_position; break; case CoordinateType.Joint: action = HRobot.get_current_joint; break; default: ShowUnknownCoordinateType(); return position; } var returnCode = action(Id, position); IsErrorAndHandler(returnCode); return position; } #endregion - Others - } }
namespace BettingSystem.Application.Betting.Gamblers.Commands.Common { using Application.Common; public abstract class GamblerCommand<TCommand> : EntityCommand<int> where TCommand : EntityCommand<int> { public string Name { get; set; } = default!; } }
using System.Web.Mvc; namespace PunchOutAPI.Controllers { public class APIController : Controller { } }
using System; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Quote.Common; using Quote.Framework; using Tests.Common; namespace UnitTests { [TestClass] public class LenderRawDataProviderFromFileTests { [TestMethod] [DataRow("asd.csv")] [ExpectExceptionWithMessage(typeof(ValidationException), "The file path 'asd.csv' does not exist")] public async Task When_File_Does_Not_Exist(string filePath) { var fileData = await new LenderRawRateProviderFromFile(filePath).Read(); } [TestMethod] [DataRow("LenderData.csv")] public async Task File_Four_Lender_Rows(string filePath) { var fileData = await new LenderRawRateProviderFromFile(filePath).Read(); Assert.IsTrue(fileData.Contains("Bob")); } } }
using DistCWebSite.Core.Entities; using DistCWebSite.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DistCWebSite.Controllers { public class PPTProcessController : Controller { ProcInstBasicInfoRespository procInstBasicInfoRespository = new ProcInstBasicInfoRespository(); PPTDownLoadRepository pptDownLoadRepository = new PPTDownLoadRepository(); BLL.PPTProcessService pptProcessService = new BLL.PPTProcessService(); // GET: PPTProcess public ActionResult Index() { return View(); } public void DownLoadPPT(int ProcInstID) { M_ProcInstBasicInfo basicInfo= procInstBasicInfoRespository.GetInstBasicInfo(ProcInstID); pptDownLoadRepository.Add(new PPTDownLoad { ProcInstID = basicInfo.ProcInstID, OpeDate = DateTime.Now, OpeUser = User.Identity.Name }); var url = ""; // Response.Redirect("~/Home/Index"); } public ContentResult SubmitPPT(int ProcInstID) { return Content(""); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace Northwind { [ServiceContract] public interface IClientAccessPolicy { [OperationContract, System.ServiceModel.Web.WebGet(UriTemplate = "/clientaccesspolicy.xml")] System.IO.Stream GetClientAccessPolicy(); } }