text
stringlengths
13
6.01M
namespace myBOOK.data.Migrations { using System; using System.Data.Entity.Migrations; public partial class DeleteOldTables : DbMigration { public override void Up() { DropForeignKey("dbo.Favourites", new[] { "Book_BookName", "Book_Author" }, "dbo.Books"); DropForeignKey("dbo.Favourites", "User_Login", "dbo.Users"); DropForeignKey("dbo.FutureReadBooks", new[] { "Book_BookName", "Book_Author" }, "dbo.Books"); DropForeignKey("dbo.FutureReadBooks", "User_Login", "dbo.Users"); DropForeignKey("dbo.PastReadBooks", new[] { "Book_BookName", "Book_Author" }, "dbo.Books"); DropForeignKey("dbo.PastReadBooks", "User_Login", "dbo.Users"); DropIndex("dbo.Favourites", new[] { "Book_BookName", "Book_Author" }); DropIndex("dbo.Favourites", new[] { "User_Login" }); DropIndex("dbo.FutureReadBooks", new[] { "Book_BookName", "Book_Author" }); DropIndex("dbo.FutureReadBooks", new[] { "User_Login" }); DropIndex("dbo.PastReadBooks", new[] { "Book_BookName", "Book_Author" }); DropIndex("dbo.PastReadBooks", new[] { "User_Login" }); DropTable("dbo.Favourites"); DropTable("dbo.FutureReadBooks"); DropTable("dbo.PastReadBooks"); } public override void Down() { CreateTable( "dbo.PastReadBooks", c => new { ID = c.Int(nullable: false, identity: true), Book_BookName = c.String(maxLength: 128), Book_Author = c.String(maxLength: 128), User_Login = c.String(maxLength: 128), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.FutureReadBooks", c => new { ID = c.Int(nullable: false, identity: true), Book_BookName = c.String(maxLength: 128), Book_Author = c.String(maxLength: 128), User_Login = c.String(maxLength: 128), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Favourites", c => new { ID = c.Int(nullable: false, identity: true), Book_BookName = c.String(maxLength: 128), Book_Author = c.String(maxLength: 128), User_Login = c.String(maxLength: 128), }) .PrimaryKey(t => t.ID); CreateIndex("dbo.PastReadBooks", "User_Login"); CreateIndex("dbo.PastReadBooks", new[] { "Book_BookName", "Book_Author" }); CreateIndex("dbo.FutureReadBooks", "User_Login"); CreateIndex("dbo.FutureReadBooks", new[] { "Book_BookName", "Book_Author" }); CreateIndex("dbo.Favourites", "User_Login"); CreateIndex("dbo.Favourites", new[] { "Book_BookName", "Book_Author" }); AddForeignKey("dbo.PastReadBooks", "User_Login", "dbo.Users", "Login"); AddForeignKey("dbo.PastReadBooks", new[] { "Book_BookName", "Book_Author" }, "dbo.Books", new[] { "BookName", "Author" }); AddForeignKey("dbo.FutureReadBooks", "User_Login", "dbo.Users", "Login"); AddForeignKey("dbo.FutureReadBooks", new[] { "Book_BookName", "Book_Author" }, "dbo.Books", new[] { "BookName", "Author" }); AddForeignKey("dbo.Favourites", "User_Login", "dbo.Users", "Login"); AddForeignKey("dbo.Favourites", new[] { "Book_BookName", "Book_Author" }, "dbo.Books", new[] { "BookName", "Author" }); } } }
using System; using DataAccessLibrary; using Microsoft.EntityFrameworkCore; namespace DataAccessLibrary { public class ApplicationContext : DbContext { public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { } public DbSet<User> Users { get; set; } public DbSet<Expense> Expenses { get; set; } public DbSet<SavingGoalsModel> SavingGoals { get; set; } public DbSet<Category> Categories { get; set; } } }
using Irony.Ast; using Irony.Interpreter; using Irony.Parsing; namespace Bitbrains.AmmyParser { public partial class AstMixinDefinition { public override void Init(AstContext context, ParseTreeNode treeNode) { base.Init(context, treeNode); AsString = GetType().Name; } protected override object DoEvaluate(ScriptThread thread) { return GetData(thread); } public IAstStatement GetData(ScriptThread thread) { var a = (object[])base.DoEvaluate(thread); return new AstMixinDefinitionData(Span, (string)a[0], (AstObjectSettingsCollection)a[3] ); } } }
using UnityEngine; using System.Collections; public class MapData : MonoBehaviour { public int rows; public int columns; public int monsterCount; public int trapCount; public Vector2[] entryTiles; //Q: How can I force these to be ints within range? }
using System.Collections.Generic; using System.Reflection; using AutoTests.Framework.TestData; using AutoTests.Framework.TestData.Entities; using AutoTests.Framework.TestData.TestDataProviders.EmbeddedResourceProviders; namespace AutoTests.Framework.Example.Resources.Providers { public class JsonResourceProvider : EmbeddedJsonProviderBase { public JsonResourceProvider(TestDataDependencies dependencies) : base(dependencies) { } protected override IEnumerable<EmbeddedResourceLocation> GetResourceLocations() { yield return new EmbeddedResourceLocation( Assembly.GetExecutingAssembly(), "AutoTests.Framework.Example.Resources.Assets.(.*).json"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml.Serialization; namespace BooksWebAPI.Server.Models { [XmlRoot("catalog")] public class CatalogEm { [XmlElement("book")] public List<BookEm> Books { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Euler_Logic.Problems.AdventOfCode.Y2018 { public class Problem17 : AdventOfCodeBase { private Dictionary<int, Dictionary<int, enumNodeType>> _grid; private int _highestY; private int _lowestY; private int _highestX; private int _lowestX; private enum enumNodeType { Empty, Wall, WaterStagnant, WaterFlowing } public override string ProblemName { get { return "Advent of Code 2018: 17"; } } public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { GetGrid(input); SetHighestLowest(); Vertical(500, 0); return GetCount(false); } private int Answer2(List<string> input) { GetGrid(input); SetHighestLowest(); Vertical(500, 0); return GetCount(true); } private int GetCount(bool onlyStagnant) { int count = 0; foreach (var x in _grid) { foreach (var y in x.Value) { if (y.Key >= _lowestY && y.Key <= _highestY) { if (y.Value == enumNodeType.WaterStagnant) { count++; } else if (y.Value == enumNodeType.WaterFlowing && !onlyStagnant) { count++; } } } } return count; } private bool Vertical(int startX, int startY) { int x = startX; int y = startY; while (y <= _highestY && GetNode(x, y) == enumNodeType.Empty) { SetNode(x, y, enumNodeType.WaterFlowing); y++; } if (y <= _highestY) { y--; bool left; bool right; bool foundFlowing = LookForFlowing(x - 1, y, -1); foundFlowing = foundFlowing || LookForFlowing(x + 1, y, 1); if (!foundFlowing) { do { SetNode(x, y, enumNodeType.WaterStagnant); left = Horizontal(x - 1, y, -1); right = Horizontal(x + 1, y, 1); if (!left || !right) { SetNode(x, y, enumNodeType.WaterFlowing); SetRowToFlowing(x, y); } y--; foundFlowing = LookForFlowing(x - 1, y, -1); foundFlowing = foundFlowing || LookForFlowing(x + 1, y, 1); } while (left && right && y > startY && !foundFlowing); if (GetNode(x, y - 1) == enumNodeType.WaterStagnant) { SetNode(x, y, enumNodeType.WaterStagnant); } } } return y <= startY; } private void SetRowToFlowing(int x, int y) { int step = 1; bool leftStop = false; bool rightStop = false; do { if (!leftStop && GetNode(x - step, y) == enumNodeType.WaterStagnant) { SetNode(x - step, y, enumNodeType.WaterFlowing); } else if (!leftStop) { leftStop = true; } if (!rightStop && GetNode(x + step, y) == enumNodeType.WaterStagnant) { SetNode(x + step, y, enumNodeType.WaterFlowing); } else if (!rightStop) { rightStop = true; } step++; } while (!leftStop || !rightStop); } private bool LookForFlowing(int startX, int startY, int direction) { int x = startX; int y = startY; var node = GetNode(x, y + 1); if (node == enumNodeType.WaterStagnant || node == enumNodeType.WaterFlowing) { do { x += direction; } while (GetNode(x, y) == enumNodeType.Empty && GetNode(x, y + 1) != enumNodeType.Empty); if (GetNode(x, y) == enumNodeType.WaterFlowing) { return true; } } return false; } private bool Horizontal(int startX, int startY, int direction) { int x = startX; int y = startY; if (GetNode(x, y + 1) == enumNodeType.WaterStagnant) { do { x += direction; } while (GetNode(x, y) == enumNodeType.Empty && GetNode(x, y + 1) != enumNodeType.Empty); if (GetNode(x, y) != enumNodeType.Wall) { if (GetNode(x, y) == enumNodeType.WaterFlowing) { return false; } if (GetNode(x - direction, y + 1) == enumNodeType.WaterStagnant) { return false; } } x = startX; } do { var next = GetNode(x, y); if (next == enumNodeType.Wall) { return true; } SetNode(x, y, enumNodeType.WaterStagnant); if (GetNode(x, y + 1) == enumNodeType.Empty) { var result = Vertical(x, y + 1); if (!result) { return false; } } x += direction; } while (true); } private void SetHighestLowest() { _highestY = 0; _highestX = _grid.Keys.Max(); _lowestY = int.MaxValue; _lowestX = _grid.Keys.Min(); foreach (var points in _grid) { var highest = points.Value.Keys.Max(); if (highest > _highestY) { _highestY = highest; } var lowest = points.Value.Keys.Min(); if (lowest < _lowestY) { _lowestY = lowest; } } } private void GetGrid(List<string> input) { _grid = new Dictionary<int, Dictionary<int, enumNodeType>>(); foreach (var line in input) { var split = line.Split(','); bool isNum1X = split[0][0] == 'x'; var num1 = Convert.ToInt32(split[0].Replace("x=", "").Replace("y=", "")); var subSplit = split[1].Replace("..", ",").Split(','); var num2 = Convert.ToInt32(subSplit[0].Replace("x=", "").Replace("y=", "")); var num3 = Convert.ToInt32(subSplit[1]); for (int axis = num2; axis <= num3; axis++) { if (isNum1X) { SetNode(num1, axis, enumNodeType.Wall); } else { SetNode(axis, num1, enumNodeType.Wall); } } } } private enumNodeType GetNode(int x, int y) { if (_grid.ContainsKey(x) && _grid[x].ContainsKey(y)) { return _grid[x][y]; } else { return enumNodeType.Empty; } } private void SetNode(int x, int y, enumNodeType node) { if (!_grid.ContainsKey(x)) { _grid.Add(x, new Dictionary<int, enumNodeType>()); } if (!_grid[x].ContainsKey(y)) { _grid[x].Add(y, node); } else { _grid[x][y] = node; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Values : MonoBehaviour { private Button button; public string status; private TextManager textManager; // Start is called before the first frame update void Start() { textManager = GameObject.Find("TextManager").GetComponent<TextManager>(); button = GetComponent<Button>(); button.onClick.AddListener(SetStatus); } void SetStatus() { Debug.Log(button.gameObject.name + " was clicked"); textManager.ChangeText(status); } }
namespace NumericProblems.Problems { public static class ArrayExtension { public static unsafe bool IsEqual(this int[] x, int[] y) { if (x == null || y == null) return false; if (x.Length != y.Length) return false; var len = x.Length; fixed (int* p1 = x, p2 = y) { var left = p1; var right = p2; while (len > 0) { if (*left != *right) return false; left++; right++; len--; } } return true; } public static unsafe bool Find(this int[] array, int dupl, int position = -1) { if (position == -1) position = array.Length; var idx = 0; fixed (int* pointer = array) { var current = pointer; while (idx++ < position) { if (*current == dupl) return true; current++; } } return false; } /// <summary> /// Returns sum of an array. /// </summary> /// <param name="array"></param> /// <returns></returns> public static unsafe int Sum(this int[] array) { var sum = 0; fixed (int* ptr = array) { var cur = ptr; var idx = 0; while (idx++ < array.Length) { sum += *cur; cur++; } } return sum; } /// <summary> /// Return sum and summed indexes. /// </summary> /// <returns></returns> public static unsafe int Sum(this int[] array, out int[] indexes) { var sum = 0; indexes = new int[array.Length]; fixed (int* ptr = array) { var cur = ptr; var idx = 0; while (idx < array.Length) { var value = *cur; if (value != 0) indexes[idx] = 1; sum += value; cur++; idx++; } } return sum; } } }
using System; using System.Threading; using System.Threading.Tasks; using AgentR.Server; using MediatR; using Microsoft.AspNetCore.SignalR; namespace IntegrationTests { public static class Extensions { public static IRequestHandler<TRequest, TResponse> CreateHandler<TRequest, TResponse>(this IHubContext<AgentHub> hub) where TRequest : IRequest<TResponse> { if (null == hub) throw new ArgumentNullException(nameof(hub)); return new AgentHandler<TRequest, TResponse>(hub); } public static Task<TResponse> SendRequest<TResponse>(this IHubContext<AgentHub> hub, IRequest<TResponse> request, CancellationToken cancellationToken = default(CancellationToken)) { var method = typeof(Extensions).GetMethod(nameof(CreateHandler)).MakeGenericMethod(request.GetType(), typeof(TResponse)); var handler = method.Invoke(null, new[] { hub }); var handle = handler.GetType().GetMethod(nameof(IRequestHandler<IRequest<Unit>>.Handle)); return (Task<TResponse>)handle.Invoke(handler, new object[] { request, cancellationToken }); } } }
using EasySave.Helpers; using EasySave.Helpers.Files; using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace EasySave.Model.Job.Specialisation { /// <summary> /// Create a mirror save from a source to a target folder. /// </summary> public class SaveMirrorJob : BaseJob { /// <summary> /// Constructor /// </summary> public SaveMirrorJob() : base("save-mirror", "Create a mirror save from a source to a target folder.") { this.Options = new List<Option> { new Option("name", "Name of the save", @"^((?![\*\.\/\\\[\]:;\|,]).)*$"), new Option("encrypt", "Encrypt special files", @"yes|no"), new Option("source", "Source folder", @".*"), new Option("target", "Target folder", @".*") }; } /// <summary> /// Save the priority files /// </summary> /// <param name="saveJob">SaveJob object <see cref="SaveJob"/></param> /// <param name="priority">List of path to priority files</param> /// <returns>Number of file copied or -1 if error</returns> private int SaveFilesPriority(SaveJob saveJob, List<string> priority) { if (priority.Count > 0) management.Threads.SetThreadPriority(saveJob.Name, true); FilesHelper.CopyDirectoryTree(saveJob.Source, saveJob.Target); foreach (string path in priority) { management.Threads.Map[saveJob.Name].Pause.WaitOne(); saveJob.CheckAndCopy(path); if (saveJob.CheckIfStopped(path)) { management.Threads.SetThreadPriority(saveJob.Name, false); return -1; } saveJob.CheckERP(); } management.Threads.SetThreadPriority(saveJob.Name, false); return 0; } /// <summary> /// Save the files that are not prioritary /// </summary> /// <param name="saveJob">SaveJob object <see cref="SaveJob"/></param> /// <param name="priority">List of path to non prioritary files</param> /// <returns>Number of file copied or -1 if error</returns> private int SaveFilesOthers(SaveJob saveJob, List<string> others) { foreach (string path in others) { management.Threads.Priority.WaitOne(); //Pause management.Threads.Map[saveJob.Name].Pause.WaitOne(); saveJob.CheckAndCopy(path); if (saveJob.CheckIfStopped(path)) return -1; saveJob.CheckERP(); } return 0; } /// <summary> /// Save files from a source folder to a target folder. /// </summary> /// <param name="saveJob">SaveJob object</param> /// <returns>Success message, otherwise throw an error</returns> private int SaveFiles(SaveJob saveJob) { string[] files = saveJob.GetFiles(); List<string> priority = new List<string>(); List<string> others = new List<string>(); saveJob.GetPriorityFiles(files, priority, others); saveJob.Target = Path.Combine(saveJob.Target, saveJob.Name, FilesHelper.GenerateName("mirror")); FilesHelper.CopyDirectoryTree(saveJob.Source, saveJob.Target); if (SaveFilesPriority(saveJob, priority) < 0) return -1; if (SaveFilesOthers(saveJob, others) < 0) return -1; return saveJob.Progress.FilesDone; } /// <summary> /// <see cref="BaseCommand.Execute(Dictionary{string, string})"/> /// <see cref="BaseCommand.CheckOptions(Dictionary{string, string})"/> /// Launch the mirro save. Check if the folders exists beforewise. /// </summary> /// <param name="options">Dictionary of options needed to execute the mirror job</param> public override void Execute(Dictionary<string, string> options) { SaveJob saveJob = new SaveJob( management, options["name"], options["source"], options["target"], (options["encrypt"].Equals("yes")) ? true : false ); management.Display.DisplayText(Statut.INFO, management.Lang.Translate("Job started : ") + saveJob.Name + " ..."); Thread thread = new Thread(new ThreadStart(() => { CheckOptions(options); saveJob.CheckIfFoldersExist(); saveJob.SaveEnd(SaveFiles(saveJob)); })); saveJob.StartIfNotExist(thread); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Persistence; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Models; namespace App { class Program { private static readonly CancellationTokenSource Cts = new(); static async Task Main(string[] args) { Console.WriteLine("Press Ctrl+C to cancel"); Console.CancelKeyPress += Console_CancelKeyPress; IConfiguration config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var connectionString = config.GetConnectionString("Default"); var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlite(connectionString) .Options; await using var appDbContext = new AppDbContext(options); //for (int i = 1; i < 11; i++) //{ // await appDbContext.Products.AddAsync( // new Product {InStock = 28 % i, IsForSale = i % 2 < 1 || i % 3 < 1, Name = $"{i}"}, Cts.Token); //} //await appDbContext.SaveChangesAsync(Cts.Token); // First // foreach (var p in appDbContext.Products.Where(p => p.IsForSale && p.InStock > 1)) // Second // IT DOESN'T WORK BECAUSE I DON'T KNOW (MAYBE THAT'S TRUE ONLY FOR SQLITE PROVIDER?) // foreach (var p in appDbContext.Products.Where(p => p.IsAvailable)) // Third // It works! //foreach (var p in appDbContext.Products.Where(new IsForSaleSpec() && !new IsInStockSpec())) // Fourth // It works as well! foreach (var p in appDbContext.Products.Where(Product.IsAvailable)) { Console.WriteLine($"{p.Id}: {p.Name} | {p.InStock} | {p.IsForSale}"); } } private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { Console.WriteLine("Operation has been cancelled by user"); Cts.Cancel(); while (!Cts.IsCancellationRequested) { } Environment.Exit(-1); } } }
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 MOTHER3; using Extensions; namespace MOTHER3Funland { public partial class frmLevelExpEditor : M3Form { bool loading = false; bool loading2 = false; // Level stuff Label[] lblLevel = new Label[10]; TextBox[] txtLevel = new TextBox[10]; // Text cache string[] pcharnames = new string[TextPCharNames.Entries]; public frmLevelExpEditor() { InitializeComponent(); // Load the char names for (int i = 0; i < pcharnames.Length; i++) pcharnames[i] = TextPCharNames.GetName(i); // Draw the level stuff for (int i = 0; i < 10; i++) { var l = new Label(); l.AutoSize = true; l.Left = 12; l.Top = cboLevelRange.Top + ((i + 1) * 27) + 2; this.Controls.Add(l); lblLevel[i] = l; var t = new TextBox(); t.Left = cboLevelRange.Left; t.Top = l.Top - 2; t.Width = 96; this.Controls.Add(t); txtLevel[i] = t; } // Load the data LevelExpData.Init(); Helpers.CheckFont(cboChar); loading = true; for (int i = 0; i < 9; i++) cboLevelRange.Items.Add("Levels " + ((i * 10) + 1).ToString() + " to " + ((i + 1) * 10) .ToString()); cboLevelRange.Items.Add("Levels 91 to 99"); cboLevelRange.SelectedIndex = 0; for (int i = 0; i < 16; i++) cboChar.Items.Add("[" + i.ToString("X2") + "] " + pcharnames[i]); loading = false; cboChar.SelectedIndex = 0; } private void cboChar_SelectedIndexChanged(object sender, EventArgs e) { if (loading) return; int cindex = cboChar.SelectedIndex; int lindex = cboLevelRange.SelectedIndex; if (lindex == 9) { lblLevel[9].Visible = false; txtLevel[9].Visible = false; } else { lblLevel[9].Visible = true; txtLevel[9].Visible = true; } for (int i = 0; i < 10; i++) { int tindex = ((lindex * 10) + i); lblLevel[i].Text = "Level " + ((lindex * 10) + i + 1).ToString(); if (tindex < 99) txtLevel[i].Text = LevelExpData.LevelExpEntries[cindex] .Data[(lindex * 10) + i].ToString(); } if (!loading2) txtName.Text = pcharnames[cindex]; } private void cboLevelRange_SelectedIndexChanged(object sender, EventArgs e) { loading2 = true; cboChar_SelectedIndexChanged(null, null); loading2 = false; } private void btnApply_Click(object sender, EventArgs e) { int cindex = cboChar.SelectedIndex; int lindex = cboLevelRange.SelectedIndex; var ed = LevelExpData.LevelExpEntries[cindex]; loading = true; TextPCharNames.SetName(cindex, txtName.Text); string newName = TextPCharNames.GetName(cindex); pcharnames[cindex] = newName; cboChar.Items[cindex] = ""; cboChar.Items[cindex] = "[" + cindex.ToString("X2") + "] " + newName; loading = false; for (int i = 0; i < 10; i++) { if ((lindex == 9) && (i == 9)) break; try { ed.Data[(lindex * 10) + i] = uint.Parse(txtLevel[i].Text); } catch { txtLevel[i].SelectAll(); return; } } ed.Save(); cboChar_SelectedIndexChanged(null, null); } public override void SelectIndex(int[] index) { cboChar.SelectedIndex = index[0]; } public override int[] GetIndex() { return new int[] { cboChar.SelectedIndex }; } } }
using EddiSpanshService; using Microsoft.VisualStudio.TestTools.UnitTesting; using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Net; using Tests.Properties; namespace UnitTests { // A mock rest client for the Spansh Service internal class FakeSpanshRestClient : ISpanshRestClient { public Dictionary<string, string> CannedContent = new Dictionary<string, string>(); public Uri BuildUri(IRestRequest request) { return new Uri("fakeSpansh://" + request.Resource); } IRestResponse<T> ISpanshRestClient.Execute<T>(IRestRequest request) { // this will throw if given a resource not in the canned dictionaries: that's OK string content = CannedContent[request.Resource]; IRestResponse<T> restResponse = new RestResponse<T> { Content = content, ResponseStatus = ResponseStatus.Completed, StatusCode = HttpStatusCode.OK, }; return restResponse; } IRestResponse ISpanshRestClient.Get(IRestRequest request) { // this will throw if given a resource not in the canned dictionaries: that's OK string resourceString = $"{request.Resource}"; resourceString += request.Parameters.Any() ? "?" : string.Empty; foreach (var parameter in request.Parameters) { resourceString += $"{parameter.Name}={parameter.Value}"; } string content = CannedContent[resourceString]; IRestResponse restResponse = new RestResponse { Content = content, ResponseStatus = ResponseStatus.Completed, StatusCode = HttpStatusCode.OK, }; return restResponse; } public void Expect(string resource, string content) { CannedContent[resource] = content; } } [TestClass] public class SpanshServiceTests : TestBase { FakeSpanshRestClient fakeSpanshRestClient; private SpanshService fakeSpanshService; [TestInitialize] public void start() { fakeSpanshRestClient = new FakeSpanshRestClient(); fakeSpanshService = new SpanshService(fakeSpanshRestClient); MakeSafe(); } [TestMethod] public void TestSpanshCarrierRoute() { // Arrange fakeSpanshRestClient.Expect("systems/field_values/system_names?q=NLTT 13249", "{\"values\":[\"NLTT 13249\"]}"); fakeSpanshRestClient.Expect("systems/field_values/system_names?q=Sagittarius A*", "{\"values\":[\"Sagittarius A*\"]}"); fakeSpanshRestClient.Expect("fleetcarrier/route?source=NLTT 13249capacity_used=25000calculate_starting_fuel=1destinations=Sagittarius A*", "{\"job\":\"F2B5B476-4458-11ED-9B9F-5DE194EB4526\",\"status\":\"queued\"}"); fakeSpanshRestClient.Expect("results/F2B5B476-4458-11ED-9B9F-5DE194EB4526", DeserializeJsonResource<string>(Resources.SpanshCarrierResult)); // Act var result = fakeSpanshService.GetCarrierRoute("NLTT 13249", new[] { "Sagittarius A*" }, 25000); // Assert Assert.IsNotNull(result); Assert.IsTrue(result.FillVisitedGaps); Assert.IsFalse(result.GuidanceEnabled); Assert.AreEqual(26021.94M, result.RouteDistance); Assert.AreEqual(6845, result.RouteFuelTotal); Assert.AreEqual(54, result.Waypoints.Count); Assert.AreEqual(0M, result.Waypoints[0].distance); Assert.AreEqual(26021.94M, result.Waypoints[0].distanceRemaining); Assert.AreEqual(0M, result.Waypoints[0].distanceTraveled); Assert.AreEqual(6845, result.Waypoints[0].fuelNeeded); Assert.AreEqual(0, result.Waypoints[0].fuelUsed); Assert.AreEqual(0, result.Waypoints[0].fuelUsedTotal); Assert.IsFalse(result.Waypoints[0].hasIcyRing); Assert.IsFalse(result.Waypoints[0].hasNeutronStar); Assert.IsFalse(result.Waypoints[0].hasPristineMining); Assert.AreEqual(0, result.Waypoints[0].index); Assert.IsTrue(result.Waypoints[0].isDesiredDestination); Assert.IsFalse(result.Waypoints[0].isMissionSystem); Assert.AreEqual(0, result.Waypoints[0].missionids.Count); Assert.IsFalse(result.Waypoints[0].refuelRecommended); Assert.AreEqual((ulong)2869440882065, result.Waypoints[0].systemAddress); Assert.AreEqual("NLTT 13249", result.Waypoints[0].systemName); Assert.IsFalse(result.Waypoints[0].visited); Assert.AreEqual(-38.8125M, result.Waypoints[0].x); Assert.AreEqual(9.3125M, result.Waypoints[0].y); Assert.AreEqual(-60.53125M, result.Waypoints[0].z); Assert.AreEqual(499.52M, result.Waypoints[3].distance); Assert.AreEqual(24522.68M, result.Waypoints[3].distanceRemaining); Assert.AreEqual(1499.26M, result.Waypoints[3].distanceTraveled); Assert.AreEqual(6449, result.Waypoints[3].fuelNeeded); Assert.AreEqual(132, result.Waypoints[3].fuelUsed); Assert.AreEqual(396, result.Waypoints[3].fuelUsedTotal); Assert.IsTrue(result.Waypoints[3].hasIcyRing); Assert.IsFalse(result.Waypoints[3].hasNeutronStar); Assert.IsTrue(result.Waypoints[3].hasPristineMining); Assert.AreEqual(3, result.Waypoints[3].index); Assert.IsFalse(result.Waypoints[3].isDesiredDestination); Assert.IsFalse(result.Waypoints[3].isMissionSystem); Assert.AreEqual(0, result.Waypoints[3].missionids.Count); Assert.IsFalse(result.Waypoints[3].refuelRecommended); Assert.AreEqual((ulong)18262335236073, result.Waypoints[3].systemAddress); Assert.AreEqual("Praea Euq IQ-W b56-8", result.Waypoints[3].systemName); Assert.IsFalse(result.Waypoints[3].visited); Assert.AreEqual(-51.15625M, result.Waypoints[3].x); Assert.AreEqual(-2.96875M, result.Waypoints[3].y); Assert.AreEqual(1437.34375M, result.Waypoints[3].z); Assert.AreEqual(34.82M, result.Waypoints[53].distance); Assert.AreEqual(0M, result.Waypoints[53].distanceRemaining); Assert.AreEqual(26021.94M, result.Waypoints[53].distanceTraveled); Assert.AreEqual(0, result.Waypoints[53].fuelNeeded); Assert.AreEqual(14, result.Waypoints[53].fuelUsed); Assert.AreEqual(6845, result.Waypoints[53].fuelUsedTotal); Assert.IsFalse(result.Waypoints[53].hasIcyRing); Assert.IsFalse(result.Waypoints[53].hasNeutronStar); Assert.IsFalse(result.Waypoints[53].hasPristineMining); Assert.AreEqual(53, result.Waypoints[53].index); Assert.IsTrue(result.Waypoints[53].isDesiredDestination); Assert.IsFalse(result.Waypoints[53].isMissionSystem); Assert.AreEqual(0, result.Waypoints[53].missionids.Count); Assert.IsFalse(result.Waypoints[53].refuelRecommended); Assert.AreEqual((ulong)20578934, result.Waypoints[53].systemAddress); Assert.AreEqual("Sagittarius A*", result.Waypoints[53].systemName); Assert.IsFalse(result.Waypoints[53].visited); Assert.AreEqual(25.21875M, result.Waypoints[53].x); Assert.AreEqual(-20.90625M, result.Waypoints[53].y); Assert.AreEqual(25899.96875M, result.Waypoints[53].z); } [TestMethod] public void TestSpanshGalaxyRoute() { // Arrange fakeSpanshRestClient.Expect("systems/field_values/system_names?q=NLTT 13249", "{\"values\":[\"NLTT 13249\"]}"); fakeSpanshRestClient.Expect("systems/field_values/system_names?q=Soul Sector EL-Y d7", "{\"values\":[\"Soul Sector EL-Y d7\"]}"); fakeSpanshRestClient.Expect("generic/route?source=NLTT 13249destination=Soul Sector EL-Y d7is_supercharged=0use_supercharge=1use_injections=0exclude_secondary=0fuel_power=2.60fuel_multiplier=0.012optimal_mass=1800.0base_mass=0tank_size=16internal_tank_size=1.07max_fuel_per_jump=8.00range_boost=0", "{\"job\":\"F2B5B476-4458-11ED-9B9F-5DE194EB4527\",\"status\":\"queued\"}"); fakeSpanshRestClient.Expect("results/F2B5B476-4458-11ED-9B9F-5DE194EB4527", DeserializeJsonResource<string>(Resources.SpanshGalaxyResult)); // Act var ship = EddiDataDefinitions.ShipDefinitions.FromEDModel("Anaconda"); ship.frameshiftdrive = EddiDataDefinitions.Module.FromEDName("Int_Hyperdrive_Size6_Class5"); var result = fakeSpanshService.GetGalaxyRoute("NLTT 13249", "Soul Sector EL-Y d7", ship); // Assert[9] Assert.IsNotNull(result); Assert.IsTrue(result.FillVisitedGaps); Assert.IsFalse(result.GuidanceEnabled); Assert.AreEqual(8178.36M, result.RouteDistance); Assert.AreEqual(259, result.Waypoints.Count); Assert.AreEqual(0M, result.Waypoints[0].distance); Assert.AreEqual(8178.36M, result.Waypoints[0].distanceRemaining); Assert.AreEqual(0M, result.Waypoints[0].distanceTraveled); Assert.IsFalse(result.Waypoints[0].hasNeutronStar); Assert.AreEqual(0, result.Waypoints[0].index); Assert.IsFalse(result.Waypoints[0].isDesiredDestination); Assert.IsFalse(result.Waypoints[0].isMissionSystem); Assert.IsFalse(result.Waypoints[0].isScoopable); Assert.AreEqual(0, result.Waypoints[0].missionids.Count); Assert.IsFalse(result.Waypoints[0].refuelRecommended); Assert.AreEqual((ulong)2869440882065, result.Waypoints[0].systemAddress); Assert.AreEqual("NLTT 13249", result.Waypoints[0].systemName); Assert.IsFalse(result.Waypoints[0].visited); Assert.AreEqual(-38.8125M, result.Waypoints[0].x); Assert.AreEqual(9.3125M, result.Waypoints[0].y); Assert.AreEqual(-60.53125M, result.Waypoints[0].z); Assert.AreEqual(30.06M, result.Waypoints[63].distance); Assert.AreEqual(6311.29M, result.Waypoints[63].distanceRemaining); Assert.AreEqual(1867.07M, result.Waypoints[63].distanceTraveled); Assert.IsTrue(result.Waypoints[63].hasNeutronStar); Assert.AreEqual(63, result.Waypoints[63].index); Assert.IsFalse(result.Waypoints[63].isDesiredDestination); Assert.IsFalse(result.Waypoints[63].isMissionSystem); Assert.IsFalse(result.Waypoints[63].isScoopable); Assert.AreEqual(0, result.Waypoints[63].missionids.Count); Assert.IsFalse(result.Waypoints[63].refuelRecommended); Assert.AreEqual((ulong)147647924467, result.Waypoints[63].systemAddress); Assert.AreEqual("Outopps AS-B d13-4", result.Waypoints[63].systemName); Assert.IsFalse(result.Waypoints[63].visited); Assert.AreEqual(-1276.5M, result.Waypoints[63].x); Assert.AreEqual(182.53125M, result.Waypoints[63].y); Assert.AreEqual(-1182.375M, result.Waypoints[63].z); Assert.AreEqual(30.74M, result.Waypoints[254].distance); Assert.AreEqual(201.48M, result.Waypoints[254].distanceRemaining); Assert.AreEqual(7976.88M, result.Waypoints[254].distanceTraveled); Assert.IsFalse(result.Waypoints[254].hasNeutronStar); Assert.AreEqual(254, result.Waypoints[254].index); Assert.IsFalse(result.Waypoints[254].isDesiredDestination); Assert.IsFalse(result.Waypoints[254].isMissionSystem); Assert.IsTrue(result.Waypoints[254].isScoopable); Assert.AreEqual(0, result.Waypoints[254].missionids.Count); Assert.IsTrue(result.Waypoints[254].refuelRecommended); Assert.AreEqual((ulong)937166915403, result.Waypoints[254].systemAddress); Assert.AreEqual("Hypoae Ain LI-K d8-27", result.Waypoints[254].systemName); Assert.IsFalse(result.Waypoints[254].visited); Assert.AreEqual(-4917.28125M, result.Waypoints[254].x); Assert.AreEqual(74.8125M, result.Waypoints[254].y); Assert.AreEqual(-5385.25M, result.Waypoints[254].z); Assert.AreEqual(118.13M, result.Waypoints[258].distance); Assert.AreEqual(0M, result.Waypoints[258].distanceRemaining); Assert.AreEqual(8178.36M, result.Waypoints[258].distanceTraveled); Assert.IsFalse(result.Waypoints[258].hasNeutronStar); Assert.AreEqual(258, result.Waypoints[258].index); Assert.IsFalse(result.Waypoints[258].isDesiredDestination); Assert.IsFalse(result.Waypoints[258].isMissionSystem); Assert.IsFalse(result.Waypoints[258].isScoopable); Assert.AreEqual(0, result.Waypoints[258].missionids.Count); Assert.IsFalse(result.Waypoints[258].refuelRecommended); Assert.AreEqual((ulong)249938593603, result.Waypoints[258].systemAddress); Assert.AreEqual("Soul Sector EL-Y d7", result.Waypoints[258].systemName); Assert.IsFalse(result.Waypoints[258].visited); Assert.AreEqual(-5043.15625M, result.Waypoints[258].x); Assert.AreEqual(85.03125M, result.Waypoints[258].y); Assert.AreEqual(-5513.09375M, result.Waypoints[258].z); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using SSDAssignmentBOX.Models; using System.ComponentModel.DataAnnotations; namespace SSDAssignmentBOX.Pages.Libraries { public class IndexModel : PageModel { private readonly SSDAssignmentBOX.Models.BookContext _context; public IndexModel(SSDAssignmentBOX.Models.BookContext context) { _context = context; } public IList<Library> Library { get;set; } public string SearchString { get; set; } public async Task OnGetAsync(string SearchString) { var libraries = from l in _context.Library select l; if (!String.IsNullOrEmpty(SearchString)) { SearchString = "%"; string query = "SELECT * FROM Library WHERE BranchName like {0}"; Library = await _context.Library.FromSql(query, SearchString).ToListAsync(); libraries = libraries.Where(s => s.BranchName.Contains(SearchString)); } Library = await libraries.ToListAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace com.Sconit.Web.Models.SearchModels.CUST { public class ItemPropertySearchModel : SearchModelBase { public string RmItem { get; set; } public string Flow { get; set; } } }
using System; using System.Linq; using System.Management; namespace WPFTemplet.Class { class CheckMotherBoardSerial { string[] AllowedMotherbordIDs = new string[] { "..CN1374089701IT.", /*My Home PC*/ "..CN1374085305DS.", /*My Company PC*/ ".95560N1.CN701660CK00W6.", /*lab D atef El sady*/ "/J8XFXS2/CNCMC008CF039B/" /*lab D atef El sady*/ }; public bool GetMotherboardSerialNo() { string CurrentMotherBordSerial = String.Empty; bool DeviceStatus = false; ManagementScope scope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2"); scope.Connect(); ManagementObject wmiClass = new ManagementObject(scope, new ManagementPath("Win32_BaseBoard.Tag=\"Base Board\""), new ObjectGetOptions()); foreach (PropertyData propData in wmiClass.Properties) { if (propData.Name == "SerialNumber") //mbInfo = String.Format("{0,-25}{1}", propData.Name, Convert.ToString(propData.Value)); CurrentMotherBordSerial = Convert.ToString(propData.Value); } if (AllowedMotherbordIDs.Contains(CurrentMotherBordSerial)) { DeviceStatus = true; } return DeviceStatus; } } }
using Alabo.App.Share.HuDong.Domain.Enums; using Alabo.Domains.Entities; using Alabo.Domains.Enums; using Alabo.Validations; using Alabo.Web.Mvc.Attributes; using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Alabo.App.Share.HuDong.Domain.Entities { /// <summary> /// </summary> [BsonIgnoreExtraElements] [Table("Hudong")] [ClassProperty(Name = "互动", Icon = "fa fa-cog", SortOrder = 1)] public class Hudong : AggregateMongodbUserRoot<Hudong> { /// <summary> /// 活动名称 /// /// /// </summary> [Display(Name = "活动名称")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [Field(IsShowBaseSerach = true, SortOrder = 1, ControlsType = ControlsType.TextBox, IsMain = true, EditShow = true, ListShow = true, Link = "/Admin/Activitys/Edit?Key=[[Key]]&Id=[[Id]]")] public string Name { get; set; } = "活动名称"; /// <summary> /// 所属营销活动类型,如:Alabo.App.Share.HuDong.Modules.BigWheel /// 大转盘 /// </summary> [Display(Name = "所属营销活动类型")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public string Key { get; set; } /// <summary> /// 是否启用 /// </summary> public bool IsEnable { get; set; } /// <summary> /// 可抽奖次数 /// </summary> public long DrawCount { get; set; } /// <summary> /// 抽奖规则文字显示 /// </summary> public string DrawRule { get; set; } /// <summary> /// 奖品列表 /// </summary> public List<HudongAward> Awards { get; set; } = new List<HudongAward>(); /// <summary> /// 互动设置 /// </summary> public HudongSetting Setting { get; set; } = new HudongSetting(); } /// <summary> /// 互动奖品 /// </summary> public class HudongAward { /// <summary> /// 互动奖品唯一标识 /// </summary> public Guid AwardId { get; set; } /// <summary> /// 图片路径 /// </summary> public string img { get; set; } /// <summary> /// 等级 /// </summary> public string Grade { get; set; } /// <summary> /// 获奖机率 /// </summary> [Display(Name = "获奖机率")] [Field(ControlsType = ControlsType.Label, ListShow = true, EditShow = true)] public decimal Rate { get; set; } /// <summary> /// 奖项数量 /// </summary> [Display(Name = "奖项数量")] [Field(ControlsType = ControlsType.Label, ListShow = true, EditShow = true)] public long Count { get; set; } /// <summary> /// 奖品类型 /// </summary> [Display(Name = "奖品类型")] [Field(ControlsType = ControlsType.Label, ListShow = true, EditShow = true)] public HudongAwardType Type { get; set; } /// <summary> /// 奖品价值 /// </summary> [Display(Name = "奖品价值")] [Field(ControlsType = ControlsType.Label, ListShow = true, EditShow = true)] public decimal worth { get; set; } /// <summary> /// 设置说明 /// </summary> [Display(Name = "设置说明")] [Field(ControlsType = ControlsType.Label, ListShow = true, EditShow = true)] public string Intro { get; set; } } /// <summary> /// 互动设置 /// </summary> public class HudongSetting { /// <summary> /// 奖项数量设置 /// 如果为0的时候 :用户可以在前台自定义添加奖项数量 /// 如果大于0时:表示奖项数量固定,用户不允许自行添加数量,数量少的时候也不能保存 /// 比如:大装盘和前台先对应,数量必须为8个。保存大转盘设置的时候,将项数量只能为8个 /// </summary> public long RewardCount { get; set; } = 0; } }
/* * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * * == AUCTION MASTER == * * Author: Henrique Fantini * Contact: contact@henriquefantini.com * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * * Auction Master is a software with the objective to collect and process data * from World of Warcraft's auction house. The idea behind this is display data * and graphics about the market of each realm and analyse your movimentation. * * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + */ // == IMPORTS // ============================================================================== using AuctionMaster.App.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; // == NAMESPACE // ============================================================================== namespace AuctionMaster.App.Service.Task { // == CLASS // ========================================================================== /// <summary> /// Interface of ScheduledTaskService /// </summary> public interface IScheduledTaskService { // == DECLARATIONS // ====================================================================== // == CONST // == VAR // == CONSTRUCTOR(S) // ====================================================================== // == METHOD(S) // ====================================================================== void initTaskService(); // == EVENT(S) // ====================================================================== // == GETTER(S) AND SETTER(S) // ====================================================================== } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MidTermAssignment1 { class Program { static void Main(string[] args) { Bank ourBank = new Bank("Developer's bank", 5); ourBank.AddAccount(new Account(1001, "Shakib", 2000, new Address(4, 10, "Dhaka", "Bangladesh"))); ourBank.AddAccount(account: new Account(3003, "Mushfiq", 5000, new Address(4, 10, "Sylhet", "Bangladesh"))); ourBank.AddAccount(new Account(1002, "Tamim", 3000, new Address(7, 20, "Chittagong", "Bangladesh"))); ourBank.PrintAllAccounts(); //ourBank.SearchAccount(300); } } }
using UnityEngine; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Net; using System; public class MessageTranslator { private static MemoryStream stream = new MemoryStream(); private static BinaryFormatter formatter = new BinaryFormatter(); private static Message message; public static Message Read(byte[] bytes) { return Read<Message> (bytes); } public static T Read<T>( byte[] bytes ) { stream.SetLength(0); stream.Seek (0, SeekOrigin.Begin); stream.Write (bytes, 0, bytes.Length); stream.Seek (0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } public static byte[] ToByteArray(Message message) { return ToByteArray<Message> (message); } public static byte[] ToByteArray<T>( T message ) { stream.SetLength(0); stream.Seek (0, SeekOrigin.Begin); formatter.Serialize (stream, message); return stream.ToArray (); } public static void Interpret(IPEndPoint source, byte[] bytes) { try { message = Read (bytes); } catch (Exception ex) { Debug.Log(ex); return; } if (message.SourceID == GameObject.FindObjectOfType<Network> ().NetworkCommon.ID) { // TODO message sent by self returned } else { if (message.Type == Message.MessageType.GAMEPLAY) GameplayTranslator.Interpret(source, message, Read<GameplayMessage>(message.SerializedContent)); else if (message.Type == Message.MessageType.NETWORK) NetworkTranslator.Interpret(source, message, Read<NetworkMessage>(message.SerializedContent)); } } }
namespace E7 { public class Alfajor { string nombre; int precio; public int Precio { get => precio; } string nombreDeLaEmpresa; public Alfajor(string nombre, int precio, string nombreDeLaEmpresa) { this.nombre = nombre; this.precio = precio; this.nombreDeLaEmpresa = nombreDeLaEmpresa; } public void Aumentos(int opcion){ switch (opcion){ case 1: precio += 80; break; case 2: precio *= 2; break; case 3: if (nombreDeLaEmpresa != "Waymayen"){ precio += 1000; } break; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; namespace Ruzzle { public partial class RuzzleBoxControl : UserControl { private static Random RND = new Random(); //STATICA PERCHE' ALTRIMENTI GENEREREBBE VALORI SEMPRE UGUALI //ATTRIBUTI private char _letter; //LETTERA DELLA CASELLA private int _points; //PUNTEGGIO DELLA CASELLA private bool _selected; //SELEZIONATA PER COMPORRE LA PAROLA private bool _clickAvailable; //POSSO CLICCARE IL CONTROLLO IN QUESTO MOMENTO? private IDBox _id; //PROPRIETA' public char Letter { get { return _letter; } private set { _letter = value; } } public int Points { get { return _points; } private set { _points = value; } } public bool Selected { get { return _selected; } set { _selected = value; } } public bool ClickAvailable { get { return _clickAvailable; } set { _clickAvailable = value; } } public IDBox ID { get { return _id; } private set { _id = value; } } //COSTRUTTORE public RuzzleBoxControl(int Column, int Row) { InitializeComponent(); Letter = RandomLetter(); //ASSEGNA VALORE ATTRAVERSO IL METODO Points = RandomPoints(); //ASSEGNA VALORE ATTRAVERSO IL METODO Selected = false; //DI DEFAULT ClickAvailable = true; //AL PRIMO CLICK SONO TUTTI DISPONIBILI Paint += RuzzleBoxControl_Paint; Click += RuzzleBoxControl_Click; ID = new IDBox(Column, Row); } private void RuzzleBoxControl_Click(object sender, EventArgs e) { if (ClickAvailable && !Selected) { SoundPlayer click = new SoundPlayer("media/click.wav"); click.Play(); Selected = (Selected) ? false : true; Invalidate(); foreach (var item in Game.Table) { item.ClickAvailable = false; } Game.ReEnable(Game.FromIDs(ID.NearThis())); Game.UserWord += Letter; Game.TempPoints += Points; } } private void RuzzleBoxControl_Paint(object sender, PaintEventArgs e) { ControlPaint.DrawBorder3D(e.Graphics, ((Control)sender).ClientRectangle, Border3DStyle.Bump); BackColor = (Selected) ? Color.Red : Color.Orange; e.Graphics.DrawString(Letter.ToString(), new Font("Arial", 20), Brushes.Black, new Point(12, 10)); e.Graphics.DrawString(Points.ToString(), new Font("Arial", 10), Brushes.Black, new Point(0, 0)); } /// <summary> /// RITORNA UNA LETTERA CASUALE DELL'ALFATBETO /// </summary> /// <returns>CARATTERE RANDOM DELLL'ALFABETO</returns> private char RandomLetter() { char[] alphabet = "ABCDEFGHILMNOPQRSTUVZ".ToCharArray(); return alphabet[RND.Next(0, 21)]; } /// <summary> /// RITORNA UN INT CON VALORE CASUALE DA 1 A 5 /// </summary> /// <returns>NUMERO INTERO CON VALORE CASUALE</returns> private int RandomPoints() { return RND.Next(1, 6); } } }
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GYOMU_CHECK { class CommonUtil { /// <summary> /// 検索結果を返す /// </summary> /// <param name="sql">SQL文</param> /// <returns>DataSet</returns> public bool CSerch(string sql, ref DataSet ds) { var connectionString = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString; // データベース接続の準備 var connection = new MySqlConnection(connectionString); try { // データベースの接続開始 connection.Open(); } catch { MessageBox.Show("DBの接続に失敗しました。", "エラー"); return false; } // 実行するSQLの準備 var command = new MySqlCommand(); command.Connection = connection; command.CommandText = sql; DataTable dt = new DataTable(); MySqlDataAdapter adapter = new MySqlDataAdapter(); adapter.SelectCommand = command; try { adapter.Fill(dt); command.Dispose(); connection.Close(); connection.Dispose(); ds.Tables.Add(dt); return true; } catch (Exception e) { MessageBox.Show(e.ToString(), "エラー"); MessageBox.Show("テーブルの取得に失敗しました。", "エラー"); return false; } } /// <summary> /// 登録・削除可能か判定 /// </summary> /// <param name="sql"></param> /// <returns></returns> public bool CExecute(ref MySqlTransaction transaction, ref MySqlCommand command, string sql) { try { command.CommandText = sql; // 実行 command.ExecuteNonQuery(); return true; } catch (MySqlException me) { // クローズ transaction.Rollback(); command.Connection.Close(); return false; } } /// <summary> /// 登録・削除可能か判定 /// </summary> /// <param name="sql"></param> /// <returns></returns> public bool CConnect(ref MySqlTransaction transaction, ref MySqlCommand command) { var connectionString = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString; try { // データベース接続の準備 var connection = new MySqlConnection(connectionString); // 実行するSQLの準備 command.Connection = connection; // オープン command.Connection.Open(); // コマンドオブジェクトにコネクションを設定します。 // トランザクションを使用する場合、設定しないと例外が発生します。 command.Connection = connection; // トランザクションを開始します。 transaction = connection.BeginTransaction(); return true; } catch (MySqlException me) { // クローズ transaction.Rollback(); command.Connection.Close(); MessageBox.Show("DB接続に失敗しました。", "エラー"); return false; } } /// <summary> /// 時間を取得 /// </summary> /// <returns></returns> public List<int> CHour() { List<int> listHour = new List<int>(); for (int i = 0; i < 24; i++) { listHour.Add(i); } return listHour; } /// <summary> /// 分を取得 /// </summary> /// <returns></returns> public List<int> CMinute() { List<int> listMinute = new List<int>(); for (int i = 0; i < 60; i++) { listMinute.Add(i); } return listMinute; } /// <summary> /// 年を取得 /// </summary> /// <returns></returns> public List<string> CYear(bool brankFlg) { List<string> listYear = new List<string>(); DateTime dt = System.DateTime.Now; string str; for (int i = dt.Year - 10; i <= dt.Year + 1; i++) { str = Convert.ToString(i); listYear.Add(str); } if (brankFlg) { listYear.Insert(0, ""); } return listYear; } /// <summary> /// 月を取得 /// </summary> /// <returns></returns> public List<string> CMonth(bool brankFlg) { List<string> listMonth = new List<string>(); string str; for (int i = 1; i < 13; i++) { if (i < 10) { str = Convert.ToString(i).PadLeft(2, '0'); } else { str = Convert.ToString(i); } listMonth.Add(str); } if (brankFlg) { listMonth.Insert(0, ""); } return listMonth; } /// <summary> /// 業務コンボボックス設定 /// </summary> /// <returns></returns> public bool CGyomu(ref DataSet ds, bool allFlg) { try { StringBuilder sql = new StringBuilder(); sql.Append(" SELECT "); sql.Append(" CD"); sql.Append(" ,NAME"); sql.Append(" FROM mst_gyomu"); sql.Append(" WHERE "); sql.Append(" DEL_FLG = 0 "); sql.Append(" ORDER BY "); sql.Append(" HYOJI_JUN "); var connectionString = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString; // データベース接続の準備 var connection = new MySqlConnection(connectionString); // データベースの接続開始 connection.Open(); // 実行するSQLの準備 var command = new MySqlCommand(); command.Connection = connection; command.CommandText = sql.ToString(); DataTable dt = new DataTable(); MySqlDataAdapter adapter = new MySqlDataAdapter(); adapter.SelectCommand = command; adapter.Fill(dt); command.Dispose(); connection.Close(); connection.Dispose(); if (dt.Rows.Count == 0) { MessageBox.Show("業務マスタが登録されていません。\n\r業務マスタの登録を行ってください。", "エラー"); return false; } if (allFlg) { DataRow row = dt.NewRow(); row["CD"] = "0"; row["NAME"] = "すべて"; dt.Rows.InsertAt(row, 0); } ds.Tables.Add(dt); return true; } catch (MySqlException me) { MessageBox.Show("DBの接続に失敗しました。", "エラー"); return false; } } /// <summary> /// 作業コンボボックス設定 /// </summary> /// <returns></returns> public bool CSagyo(ref DataSet ds, string gyomuCd) { try { StringBuilder sql = new StringBuilder(); sql.Append(" SELECT "); sql.Append(" CD"); sql.Append(" ,NAME"); sql.Append(" FROM mst_SAGYO"); sql.Append(" WHERE "); sql.Append(" DEL_FLG = 0 "); sql.Append(" AND "); sql.Append($" GYOMU_CD = {gyomuCd} "); sql.Append(" ORDER BY "); sql.Append(" HYOJI_JUN "); var connectionString = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString; // データベース接続の準備 var connection = new MySqlConnection(connectionString); // データベースの接続開始 connection.Open(); // 実行するSQLの準備 var command = new MySqlCommand(); command.Connection = connection; command.CommandText = sql.ToString(); DataTable dt = new DataTable(); MySqlDataAdapter adapter = new MySqlDataAdapter(); adapter.SelectCommand = command; adapter.Fill(dt); command.Dispose(); connection.Close(); connection.Dispose(); if (dt.Rows.Count == 0) { MessageBox.Show("作業マスタが登録されていません。\n\r作業マスタの登録を行ってください。", "エラー"); return false; } ds.Tables.Add(dt); return true; } catch (MySqlException me) { MessageBox.Show("DBの接続に失敗しました。", "エラー"); return false; } } /// <summary> /// 文字列を'でくくる /// </summary> /// <param name="str"></param> /// <returns></returns> public string CAddQuotation(string str) { return "'" + str + "'"; } /// <summary> /// 文字列の/を削除 /// </summary> /// <param name="str"></param> /// <returns></returns> public string CReplace(string str) { return str.Replace("/", ""); } /// <summary> /// 排他登録 /// </summary> /// <param name="transaction"></param> /// <param name="command"></param> /// <param name="yyyyMM"></param> /// <param name="kbn"></param> /// <param name="id"></param> /// <param name="pId"></param> /// <returns></returns> public bool InsertHaitaTrn(MySqlTransaction transaction, ref MySqlCommand command, string yyyyMM, string kbn, string id, string pId) { StringBuilder sql = new StringBuilder(); sql.Append(" SELECT "); sql.Append(" *"); sql.Append(" FROM TRN_HAITA"); sql.Append($" WHERE GYOMU_CD = {kbn}"); sql.Append($" AND SAGYO_YYMM = {yyyyMM}"); DataSet ds = new DataSet(); if (!CSerch(sql.ToString(), ref ds)) { return false; } if (ds.Tables["Table1"].Rows.Count != 0) { MessageBox.Show("他のユーザーが編集中です。", "エラー"); return false; } sql = new StringBuilder(); sql.Append(" INSERT INTO TRN_HAITA "); sql.Append(" (GYOMU_CD "); sql.Append(" ,SAGYO_YYMM "); sql.Append(" ,USER "); sql.Append(" ,INS_DT "); sql.Append(" ,INS_USER "); sql.Append(" ,INS_PGM "); sql.Append(" ,UPD_DT "); sql.Append(" ,UPD_USER "); sql.Append(" ,UPD_PGM) "); sql.Append(" VALUES "); sql.Append($" ({CAddQuotation(kbn)} "); sql.Append($" ,{yyyyMM} "); sql.Append($" ,{id} "); sql.Append(" ,now() "); sql.Append($" ,{id} "); sql.Append($" ,{CAddQuotation(pId)} "); sql.Append(" ,now() "); sql.Append($" ,{id} "); sql.Append($" ,{CAddQuotation(pId)}) "); if (!CExecute(ref transaction, ref command, sql.ToString())) { MessageBox.Show("他のユーザーが編集中です。", "エラー"); return false; } return true; } /// <summary> /// 削除排他 /// </summary> /// <param name="transaction"></param> /// <param name="command"></param> /// <param name="yyyyMM"></param> /// <param name="kbn"></param> /// <returns></returns> public bool DeleteHaitaTrn(MySqlTransaction transaction, ref MySqlCommand command, string yyyyMM, string kbn) { StringBuilder sql = new StringBuilder(); sql.Append(" DELETE FROM TRN_HAITA "); sql.Append($" WHERE GYOMU_CD = {kbn}"); sql.Append($" AND SAGYO_YYMM = {yyyyMM}"); if (!CExecute(ref transaction, ref command, sql.ToString())) { MessageBox.Show("排他テーブルの削除に失敗しました。", "エラー"); return false; } return true; } /// <summary> /// ユーザー排他削除 /// </summary> /// <param name="transaction"></param> /// <param name="command"></param> /// <param name="user"></param> /// <returns></returns> public bool DeleteHaitaUser(MySqlTransaction transaction, ref MySqlCommand command, string user) { StringBuilder sql = new StringBuilder(); sql.Append(" DELETE FROM TRN_HAITA "); sql.Append($" WHERE USER = {CAddQuotation(user)}"); if (!CExecute(ref transaction, ref command, sql.ToString())) { MessageBox.Show("排他テーブルの削除に失敗しました。", "エラー"); return false; } return true; } /// <summary> /// パスワードハッシュ化 /// </summary> /// <param name="password"></param> /// <param name="userId"></param> /// <returns></returns> public string GetHashedPassword(string passwd) { // パスワードをUTF-8エンコードでバイト配列として取り出す byte[] byteValues = Encoding.UTF8.GetBytes(passwd); // SHA256のハッシュ値を計算する SHA256 crypto256 = new SHA256CryptoServiceProvider(); byte[] hash256Value = crypto256.ComputeHash(byteValues); // SHA256の計算結果をUTF8で文字列として取り出す StringBuilder buf = new StringBuilder(); for (int i = 0; i < hash256Value.Length; i++) { // 16進の数値を文字列として取り出す buf.AppendFormat("{0:X2}", hash256Value[i]); } return buf.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdapterExample_CleanCodeBoundaries.FileLogger { class FakeFileLogger : IFileLogger { public string FileName { get; set; } public void InitFile(string filename) { this.FileName = filename; } public void LogIntoFile(string message, MessageType type = MessageType.Info) { Console.WriteLine("will write \"{0}\" into the file {1} with type {2}", message, this.FileName, type); } public void CloseFile() { Console.WriteLine("Close the file"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Character_Controller : FiniteStateMachine { Quaternion ogRotation; // Start is called before the first frame update void Awake() { ogRotation = transform.rotation; } // Update is called once per frame void LateUpdate() { transform.rotation = ogRotation; base.Update(); } }
using System; using System.Linq; using System.Globalization; namespace AssetTracking_EF { class DatabaseMethods { AssetTrackorContext _assetTrackorContext = new AssetTrackorContext(); static void ColorConsole(TimeSpan assetLifeSpan) { //1005 is 2 years and 9 months = (365*3)-(30*3) days TimeSpan soonEoLSpan3 = new TimeSpan(1005, 0, 0, 0, 0); //915 is 2 years and 6 months = (365*3)-(30*6) days TimeSpan soonEoLSpan6 = new TimeSpan(915, 0, 0, 0, 0); if (assetLifeSpan > soonEoLSpan3) { Console.ForegroundColor = ConsoleColor.Red; } else if (assetLifeSpan > soonEoLSpan6) { Console.ForegroundColor = ConsoleColor.Yellow; } else { Console.ForegroundColor = ConsoleColor.White; } } static void WriteHeadingToConsole() { Console.WriteLine("Type ModelName Price PurchaseDate Location"); Console.WriteLine("---------- ---------- ----- ------------ --------"); } static void WriteItemToConsole(CompanyAsset item, string price) { if (price == "") { // Convert CompanyAsset price to a string price = item.Price.ToString(); } Console.WriteLine( item.AssetType.PadRight(10) + " " + item.ModelName.PadRight(11) + price.PadLeft(14) + " " + item.PurchaseDate.ToString("MM/dd/yyyy").PadRight(10) + " " + item.Office.PadRight(10)); } public void Create() { LaptopComputer pc1 = new LaptopComputer("MacBook", 3341, new DateTime(2018, 12, 12), "Uganda"); LaptopComputer pc2 = new LaptopComputer("Asus", 2950, new DateTime(2018, 1, 12), "Sweden"); LaptopComputer pc3 = new LaptopComputer("Lenovo", 999, new DateTime(2019, 12, 12), "USA"); MobilePhone phone1 = new MobilePhone("Iphone", 1099, new DateTime(2011, 12, 12), "Uganda"); MobilePhone phone2 = new MobilePhone("Samsung", 1299, new DateTime(2018, 3, 12), "USA"); MobilePhone phone3 = new MobilePhone("Nokia", 699, new DateTime(2018, 4, 12), "Sweden"); _assetTrackorContext.CompanyAssets.Add(pc1); _assetTrackorContext.SaveChanges(); _assetTrackorContext.CompanyAssets.Add(phone1); _assetTrackorContext.SaveChanges(); _assetTrackorContext.CompanyAssets.Add(pc3); _assetTrackorContext.SaveChanges(); _assetTrackorContext.CompanyAssets.Add(phone2); _assetTrackorContext.SaveChanges(); _assetTrackorContext.CompanyAssets.Add(pc2); _assetTrackorContext.SaveChanges(); _assetTrackorContext.CompanyAssets.Add(phone3); _assetTrackorContext.SaveChanges(); } public void ReadAndReportLevel2() { var query = from item in _assetTrackorContext.CompanyAssets orderby item.AssetType ascending select item; WriteHeadingToConsole(); foreach (var item in query) { WriteItemToConsole(item, ""); } query = from item in _assetTrackorContext.CompanyAssets orderby item.PurchaseDate ascending select item; Console.WriteLine("\nOrder by Purchase Date"); WriteHeadingToConsole(); DateTime nowDate = DateTime.Now; TimeSpan assetLifeSpan; foreach (var item in query) { assetLifeSpan = nowDate - item.PurchaseDate; ColorConsole(assetLifeSpan); WriteItemToConsole(item, ""); } // Restore console to normal Console.ForegroundColor = ConsoleColor.White; } public void ReadAndReportLevel3() { DateTime nowDate = DateTime.Now; TimeSpan assetLifeSpan; string price; var query = from item in _assetTrackorContext.CompanyAssets orderby item.Office ascending select item; WriteHeadingToConsole(); foreach (var item in query) { assetLifeSpan = nowDate - item.PurchaseDate; if (item.Office == "Sweden") { // Convert dollars to SEK first price = (item.Price * 8.23).ToString("C", CultureInfo.CreateSpecificCulture("sv-SE")); } else if (item.Office == "Uganda") { // Convert dollars to Ugx first price = (item.Price * 3700).ToString("C", CultureInfo.CreateSpecificCulture("en-UG")); } else { // Default price in dollars price = item.Price.ToString("C", CultureInfo.CreateSpecificCulture("en-US")); } ColorConsole(assetLifeSpan); WriteItemToConsole(item, price); } // Restore console to normal Console.ForegroundColor = ConsoleColor.White; } public void Update() { // Returns first element that was added to database (Lowest ID), in this case MacBook CompanyAsset assetUpdate = _assetTrackorContext.CompanyAssets.FirstOrDefault(); assetUpdate.Office = "Sweden"; _assetTrackorContext.SaveChanges(); } public void Delete() { // Returns first element called Nokia to database CompanyAsset assetDelete = _assetTrackorContext.CompanyAssets.Where(asset => asset.ModelName == "Nokia").FirstOrDefault(); _assetTrackorContext.CompanyAssets.Remove(assetDelete); _assetTrackorContext.SaveChanges(); } } }
namespace FiiiCoin.DTO { public class ListSinceBlockOM { public string LastBlock { get; set; } public SinceBlock[] Transactions { get; set; } } public class SinceBlock { public string Account { get; set; } public string Address { get; set; } public string Category { get; set; } public long amount { get; set; } public long Vout { get; set; } public long Fee { get; set; } public long Confirmations { get; set; } public string BlockHash { get; set; } public long BlockTime { get; set; } public string TxId { get; set; } public string Label { get; set; } public bool IsSpent { get; set; } public long LockTime { get; set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace DiosesModernos { public class Grid : MonoBehaviour { #region Properties [Header ("Configuration")] [SerializeField] [Tooltip ("Number of columns (must be odd)")] [Range (1, 12)] int _nbColumns = 7; [SerializeField] [Tooltip ("Number of lines (must be odd)")] [Range (1, 12)] int _nbLines = 7; [Header ("Links")] [SerializeField] GameObject _tilePrefab; [SerializeField] Material _greyTileMaterial; [SerializeField] Material _redTileMaterial; [SerializeField] Material _yellowTileMaterial; [SerializeField] Material _blueTileMaterial; [SerializeField] Material _orangeTileMaterial; [SerializeField] Material _purpleTileMaterial; [SerializeField] Material _greenTileMaterial; [SerializeField] Material _blackTileMaterial; [SerializeField] Material _whiteTileMaterial; #endregion #region Getters public int nbColumns { get { return _nbColumns; } } public int nbLines { get { return _nbLines; } } public Dictionary<Vector2, Tile> tiles { get { return _tiles; } set { _tiles = value; } } #endregion #region API public Tile GetRandomTileByColor (string color, bool mustBeEmpty = false) { if (0 == NbTilesByColor (color) || mustBeEmpty && 0 == NbEmptyTiles ("grey")) return null; Tile tile = null; Vector2 pos = Vector2.zero; do { pos = new Vector2 (Random.Range ((int)(-nbColumns / 2), (int)(nbColumns / 2) + 1), Random.Range ((int)(-nbLines / 2), (int)(nbLines / 2) + 1)); tiles.TryGetValue (pos, out tile); } while (null == tile || color != tile.color || mustBeEmpty && null != tile.unit); return tile; } public IEnumerator MergeTilesCoroutine (Tile currentTile) { do { yield return new WaitForSeconds (1); MergeTiles (currentTile); } while (0 == NbTilesByColor ("grey")); GameManager.instance.NewTurn (); } // Return the number of tiles that have no unit on them. If a color is specified, only check the tiles of this color public int NbEmptyTiles (string color = "") { int n = 0; for (int x = -_nbColumns / 2; x <= _nbColumns / 2; ++x) { for (int y = -_nbLines / 2; y <= _nbLines / 2; ++y) { Tile tile; tiles.TryGetValue (new Vector2 (x, y), out tile); if (null != tile && null == tile.unit && ("" == color || tile.color == color)) n++; } } return n; } public int NbTilesByColor (string color) { int n = 0; for (int x = -_nbColumns / 2; x <= _nbColumns / 2; ++x) { for (int y = -_nbLines / 2; y <= _nbLines / 2; ++y) { Tile tile; tiles.TryGetValue (new Vector2 (x, y), out tile); if (null != tile && tile.color == color) n++; } } return n; } public int NbTilesByUnit (string unitName) { int n = 0; for (int x = -_nbColumns / 2; x <= _nbColumns / 2; ++x) { for (int y = -_nbLines / 2; y <= _nbLines / 2; ++y) { Tile tile; tiles.TryGetValue (new Vector2 (x, y), out tile); if (null != tile && null != tile.unit && unitName == tile.unit.name) n++; } } return n; } // Remove all units on the tiles. If a color is specified, only remove units on tiles of the specified color public void RemoveUnits (string color = "") { for (int x = -_nbColumns / 2; x <= _nbColumns / 2; ++x) { for (int y = -_nbLines / 2; y <= _nbLines / 2; ++y) { Tile tile; tiles.TryGetValue (new Vector2 (x, y), out tile); if (null != tile && null != tile.unit && ("" == color || color == tile.color)) { tile.unit.Recycle (); tile.unit = null; } } } } public void ResetRandomTile (string color = "grey") { if (NbTilesByColor (color) == tiles.Count) return; Tile tile = null; Vector2 pos = Vector2.zero; do { pos = new Vector2 (Random.Range ((int)(-nbColumns / 2), (int)(nbColumns / 2) + 1), Random.Range ((int)(-nbLines / 2), (int)(nbLines / 2) + 1)); tiles.TryGetValue (pos, out tile); } while (null == tile || color == tile.color); tile.color = color; switch (color) { case "grey": tile.modelRenderer.material = _greyTileMaterial; break; case "red": tile.modelRenderer.material = _redTileMaterial; break; case "yellow": tile.modelRenderer.material = _yellowTileMaterial; break; case "blue": tile.modelRenderer.material = _blueTileMaterial; break; case "orange": tile.modelRenderer.material = _orangeTileMaterial; break; case "purple": tile.modelRenderer.material = _purpleTileMaterial; break; case "green": tile.modelRenderer.material = _greenTileMaterial; break; case "white": tile.modelRenderer.material = _whiteTileMaterial; break; case "black": tile.modelRenderer.material = _blackTileMaterial; break; } } public Tile RevealTile (Vector2 pos) { Tile tile = null; _tiles.TryGetValue (pos, out tile); if (null != tile && "grey" == tile.color) { Material newMaterial = null; string color = null; int rnd = Random.Range (0, 3); // Hack/ //rnd = 1; // /Hack switch (rnd) { case 0: newMaterial = _redTileMaterial; color = "red"; tile.color = color; GameManager.instance.Attack (NbAdjacentSameTiles (tile)); break; case 1: newMaterial = _yellowTileMaterial; color = "yellow"; tile.color = color; GameManager.instance.Energize (NbAdjacentSameTiles (tile)); break; case 2: newMaterial = _blueTileMaterial; color = "blue"; tile.color = color; GameManager.instance.Heal (NbAdjacentSameTiles (tile)); break; } tile.modelRenderer.material = newMaterial; // Skill : mine if (null != tile.unit && "Mine" == tile.unit.name) { string log = "Mine revealed ! "; tile.unit.SetActive (true); Cyborg active = GameManager.instance.activeCyborg; if (Cyborg.Passive.MINE_INVULNERABLE != active.passive) { log += active.name + " take 5 damage !"; active.health -= 5; } else log += active.name + " is invulnerable to the mines !"; GuiManager.instance.Log (log); } } else tile = null; return tile; } #endregion #region Unity void Start () { // Create tiles _tiles = new Dictionary<Vector2, Tile> (_nbColumns * _nbLines); for (int c = -_nbColumns / 2; c <= _nbColumns / 2; ++c) { for (int l = -_nbLines / 2; l <= _nbLines / 2; ++l) { Vector2 pos = new Vector2 (c, l); GameObject tileObject = ObjectPool.Spawn (_tilePrefab, transform, pos); Tile tile = tileObject.GetComponent<Tile> (); //tile.transform.position = pos; tileObject.transform.position = pos; _tiles.Add (pos, tile); } } } #endregion #region Private properties Dictionary<Vector2, Tile> _tiles; //bool _isInteractive = true; #endregion #region Private methods void MergeTiles (Tile currentTile, string color = "") { if (0 == NbTilesByColor ("grey")) { for (int x = -_nbColumns / 2; x <= _nbColumns / 2; ++x) { for (int y = -_nbLines / 2; y <= _nbLines / 2; ++y) { Tile tile = null; tiles.TryGetValue (new Vector2 (x, y), out tile); tile.color = "grey"; tile.modelRenderer.material = _greyTileMaterial; if (null != tile.unit) { tile.unit.Recycle (); tile.unit = null; } } } return; } if ("" == color) { // First tile string colorFound = ""; for (int y = currentTile.y - 1; y <= currentTile.y + 1; ++y) { for (int x = currentTile.x - 1; x <= currentTile.x + 1; ++x) { // If the tile is the current tile or if it's in diagonale → continue if (!(0 == x - currentTile.x ^ 0 == y - currentTile.y)) continue; Tile tile = null; tiles.TryGetValue (new Vector2 (x, y), out tile); if (null == tile || currentTile.color == tile.color) continue; if ("red" == currentTile.color && "yellow" == tile.color || "yellow" == currentTile.color && "red" == tile.color) { if ("" == colorFound) { color = "orange"; colorFound = tile.color; } else if (tile.color != colorFound) color = "white"; } else if ("red" == currentTile.color && "blue" == tile.color || "blue" == currentTile.color && "red" == tile.color) { if ("" == colorFound) { color = "purple"; colorFound = tile.color; } else if (tile.color != colorFound) color = "white"; } else if ("yellow" == currentTile.color && "blue" == tile.color || "blue" == currentTile.color && "yellow" == tile.color) { if ("" == colorFound) { color = "green"; colorFound = tile.color; } else if (tile.color != colorFound) color = "white"; } } } if ("" == color) return; } currentTile.color = color; Material newColorMaterial; switch (color) { case "orange": newColorMaterial = _orangeTileMaterial; break; case "purple": newColorMaterial = _purpleTileMaterial; break; case "green": newColorMaterial = _greenTileMaterial; break; default: newColorMaterial = _whiteTileMaterial; break; } currentTile.modelRenderer.material = newColorMaterial; for (int y = currentTile.y - 1; y <= currentTile.y + 1; ++y) { for (int x = currentTile.x - 1; x <= currentTile.x + 1; ++x) { // If the tile is the current tile or if it's in diagonale → continue if (!(0 == x - currentTile.x ^ 0 == y - currentTile.y)) continue; Tile tile = null; tiles.TryGetValue (new Vector2 (x, y), out tile); if (null == tile) continue; if ("red" == tile.color || "yellow" == tile.color || "blue" == tile.color) { MergeTiles (tile, color); } } } } int NbAdjacentSameTiles (Tile currentTile, ArrayList visited = null) { if (null == visited) visited = new ArrayList (); int n = 1; visited.Add (currentTile); for (int y = currentTile.y - 1; y <= currentTile.y + 1; ++y) { for (int x = currentTile.x - 1; x <= currentTile.x + 1; ++x) { // If the tile is the current tile or if it's in diagonale → continue if (!(0 == x - currentTile.x ^ 0 == y - currentTile.y)) continue; Tile tile = null; tiles.TryGetValue (new Vector2 (x, y), out tile); if (null == tile || visited.Contains (tile) || currentTile.color != tile.color) continue; n += NbAdjacentSameTiles (tile, visited); } } return n; } #endregion } }
using Modulus2D.Input; using System.Diagnostics; using NLog; using Modulus2D.Graphics; using System; using Modulus2D.Math; namespace Modulus2D.Core { public class Game { private static Logger logger = LogManager.GetCurrentClassLogger(); // Current state private State state; // Input private InputManager input; // Window private Window window; // Time private Stopwatch stopwatch; public Game() { stopwatch = new Stopwatch(); stopwatch.Start(); input = new InputManager(); } public State State { get => state; set { state = value; state.Graphics = window; state.Input = input; } } public void Start(State state, string name, int width, int height) { // Create window window = new Window(name, width, height) { ClearColor = new Color(0.1f, 0.1f, 0.1f) }; // Set input manager window.SetInput(input); // Set state State = state; state.Start(); while (window.Open) { window.Dispatch(); window.Clear(); Update(); window.Swap(); } state.Close(); } public void Update() { float dt = (float)stopwatch.Elapsed.TotalSeconds; stopwatch.Restart(); // Update state State.Update(dt); } } }
using Xunit; using ZKCloud.Datas.Sql.Queries.Builders.Conditions; namespace ZKCloud.Test.Datas.Sql.Conditions { /// <summary> /// Is Null查询条件测试 /// </summary> public class IsNullConditionTest { /// <summary> /// 获取条件 /// </summary> [Fact] public void Test_1() { var condition = new IsNullCondition("Email"); Assert.Equal("Email Is Null", condition.GetCondition()); } /// <summary> /// 获取条件 - 验证列为空 /// </summary> [Fact] public void Test_2() { var condition = new IsNullCondition(""); Assert.Null(condition.GetCondition()); } } }
using UnityEngine; using System.Collections.Generic; using UnityEditor; public class Amendment : Editor { [MenuItem("Tools/Amendment &Q")] static void Change() { List<GameObject> shoulijian_List = new List<GameObject>(); GameObject[] selectedObjects = Selection.gameObjects; foreach (GameObject selectedObject in selectedObjects) { if (selectedObject.name.Contains("shoulijian")) { shoulijian_List.Add(selectedObject); } } for (int i = 0; i < shoulijian_List.Count; i++) { for (int j = i; j < shoulijian_List.Count; j++) { if (shoulijian_List[i].transform.position.y > shoulijian_List[j].transform.position.y) { var temp = shoulijian_List[i]; shoulijian_List[i] = shoulijian_List[j]; shoulijian_List[j] = temp; } } } if (shoulijian_List.Count > 2) { float different_X = shoulijian_List[1].transform.position.x - shoulijian_List[0].transform.position.x; float different_Y = shoulijian_List[1].transform.position.y - shoulijian_List[0].transform.position.y; for (int i = 2; i < shoulijian_List.Count; i++) { shoulijian_List[i].transform.position = shoulijian_List[i - 1].transform.position + Vector3.right*different_X + Vector3.up*different_Y; } } } }
using Bucket_Opdracht_Version2.DAL; using Bucket_Opdracht_Version2.Interfaces; using Bucket_Opdracht_Version2.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Security.Cryptography.X509Certificates; using System.Text; namespace Bucket_Opdracht_Version2.EventHandlers { public class ContainerEventHandlers { private IDataService _dataService = MockDataService.GetMockDataService(); public delegate bool TransformDelegate(); public event TransformDelegate TransformEventHandler; #nullable enable public delegate ContainerModel? ChooseDelegate(); #nullable disable public event ChooseDelegate ChooseEventHandler; public ContainerEventHandlers item; public ContainerEventHandlers(ContainerEventHandlers initmodel) { item = initmodel; } public ContainerEventHandlers() { } public void AddContainer() { var item2 = new TransformDelegate(_dataService.AddContainer); item.TransformEventHandler += item2; item.TransformEventHandler(); item.TransformEventHandler -= item2; } #nullable enable public ContainerModel? ChooseContainer() { var item2 = new ChooseDelegate(_dataService.chooseContainer); item.ChooseEventHandler += item2; var returnvalue = item.ChooseEventHandler(); item.ChooseEventHandler -= item2; return returnvalue; } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; using Newtonsoft.Json; namespace Server_CS { internal class JsonWorker { /// <summary> /// Файл для сохранения сообщений в виде json массива /// </summary> private const string MessagesPath = @"messages.json"; private const string RegDataPath = @"regData.json"; /// <summary> /// Функция сохранения в файл /// </summary> /// <param name="messages">Массив сообщений</param> public static async void Save(List<Message> messages) { var NumberOfRetries = 3; var DelayOnRetry = 1000; for (var i = 1; i <= NumberOfRetries; ++i) try { await using var streamWriter = new StreamWriter(MessagesPath); await streamWriter.WriteAsync(JsonConvert.SerializeObject(messages)); break; } catch (IOException e) when (i <= NumberOfRetries) { Thread.Sleep(DelayOnRetry); } } /// <summary> /// Функция сохранения в файл /// </summary> /// <param name="regDatas">массив связок логин/пароль</param> public static async void Save(List<RegData> regDatas) { await using var streamWriter = new StreamWriter(RegDataPath); await streamWriter.WriteAsync(JsonConvert.SerializeObject(regDatas)); } /// <summary> /// Функция загрузки сообщений из файла, десирилизованный из json в List <Message> объект /// </summary> public static async void Load() { if (!File.Exists(MessagesPath)) return; try { using var streamReader = new StreamReader(MessagesPath); Program.Messages = JsonConvert.DeserializeObject<List<Message>>(await streamReader.ReadToEndAsync()); } catch (Exception) { } if (!File.Exists(RegDataPath)) return; try { using var streamReader = new StreamReader(RegDataPath); Program.RegDatas = JsonConvert.DeserializeObject<List<RegData>>(await streamReader.ReadToEndAsync()); } catch (Exception) { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Empresa.Investimentos.Investimentos { public interface Investimento { double Calcula(double valor); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PistonTrap : MonoBehaviour { public Vector2 destination; public float speed = 3; public float backSpeed = 3; public float waitTime = 1.5f; private Vector2[] point = new Vector2[2]; // 0 - Start | 1 - End private bool isArrive; private float timer; private int number; void Start() { point[0] = transform.position; point[1] = point[0]; point[1] += destination; isArrive = true; number = 1; timer = waitTime; } void Update() { if (destination.y > 0) { if (transform.position.y >= point[1].y && timer <= 0) { number = 0; isArrive = true; timer = waitTime; } else if (transform.position.y <= point[0].y && timer <= 0) { number = 1; isArrive = true; timer = waitTime; } } else { if (transform.position.y <= point[1].y && timer <= 0) { number = 0; isArrive = true; timer = waitTime; } else if (transform.position.y >= point[0].y && timer <= 0) { number = 1; isArrive = true; timer = waitTime; } } if (timer > 0 && isArrive) timer -= Time.deltaTime; if (timer <= 0) { if (number == 1) transform.position = Vector2.MoveTowards(transform.position, point[number], speed * Time.deltaTime); else transform.position = Vector2.MoveTowards(transform.position, point[number], backSpeed * Time.deltaTime); isArrive = false; } } }
using System.ComponentModel; using DelftTools.Utils; namespace DelftTools.Tests.Core.Mocks { public class ClassWithNameButNotINameable : INotifyPropertyChange { private string name; public string Name { get { return name; } set { name = value; if (PropertyChanged != null) { PropertyChanged(this,new PropertyChangedEventArgs("Name")); } } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; } }
using System; using System.ComponentModel; using System.Windows.Forms; namespace Com.Colin.Win.Customized { /// <summary> /// Summary description for YaTabPage. /// </summary> [ToolboxItem(false)] [Designer(typeof(YaTabPageDesigner))] public class YaTabPage : ContainerControl { /// <summary> /// Creates an instance of the <see cref="YaTabPage"/> class. /// </summary> public YaTabPage() { base.Dock = DockStyle.Fill; imgIndex = -1; } /// <summary> /// Gets or sets the index to the image displayed on this tab. /// </summary> /// <value> /// The zero-based index to the image in the <see cref="TabControl.ImageList"/> /// that appears on the tab. The default is -1, which signifies no image. /// </value> /// <exception cref="ArgumentException"> /// The <see cref="ImageIndex"/> value is less than -1. /// </exception> public int ImageIndex { get { return imgIndex; } set { imgIndex = value; } } /// <summary> /// Overridden from <see cref="Panel"/>. /// </summary> /// <remarks> /// Since the <see cref="YaTabPage"/> exists only /// in the context of a <see cref="YaTabControl"/>, /// it makes sense to always have it fill the /// <see cref="YaTabControl"/>. Hence, this property /// will always return <see cref="DockStyle.Fill"/> /// regardless of how it is set. /// </remarks> public override DockStyle Dock { get { return base.Dock; } set { base.Dock = DockStyle.Fill; } } /// <summary> /// Only here so that it shows up in the property panel. /// </summary> public override string Text { get { return base.Text; } set { base.Text = value; } } /// <summary> /// Overriden from <see cref="Control"/>. /// </summary> /// <returns> /// A <see cref="YaTabPage.ControlCollection"/>. /// </returns> protected override System.Windows.Forms.Control.ControlCollection CreateControlsInstance() { return new YaTabPage.ControlCollection( this ); } /// <summary> /// The index of the image to use for the tab that represents this /// <see cref="YaTabPage"/>. /// </summary> private int imgIndex; /// <summary> /// A <see cref="YaTabPage"/>-specific /// <see cref="Control.ControlCollection"/>. /// </summary> public new class ControlCollection : Control.ControlCollection { /// <summary> /// Creates a new instance of the /// <see cref="YaTabPage.ControlCollection"/> class with /// the specified <i>owner</i>. /// </summary> /// <param name="owner"> /// The <see cref="YaTabPage"/> that owns this collection. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown if <i>owner</i> is <b>null</b>. /// </exception> /// <exception cref="ArgumentException"> /// Thrown if <i>owner</i> is not a <see cref="YaTabPage"/>. /// </exception> public ControlCollection( Control owner ) : base( owner ) { if( owner == null ) { throw new ArgumentNullException( "owner", "Tried to create a YaTabPage.ControlCollection with a null owner." ); } YaTabPage c = owner as YaTabPage; if( c == null ) { throw new ArgumentException( "Tried to create a YaTabPage.ControlCollection with a non-YaTabPage owner.", "owner" ); } } /// <summary> /// Overridden. Adds a <see cref="Control"/> to the /// <see cref="YaTabPage"/>. /// </summary> /// <param name="value"> /// The <see cref="Control"/> to add, which must not be a /// <see cref="YaTabPage"/>. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown if <i>value</i> is <b>null</b>. /// </exception> /// <exception cref="ArgumentException"> /// Thrown if <i>value</i> is a <see cref="YaTabPage"/>. /// </exception> public override void Add( Control value ) { if( value == null ) { throw new ArgumentNullException( "value", "Tried to add a null value to the YaTabPage.ControlCollection." ); } YaTabPage p = value as YaTabPage; if( p != null ) { throw new ArgumentException( "Tried to add a YaTabPage control to the YaTabPage.ControlCollection.", "value" ); } base.Add( value ); } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GridItem : BasePanel { Button Button_Eqp; Button Button_eqpIntensify; int level; int atk; int def; int hp; string eqpName; string type; string imagePath; Equipment _equipment; public void Init(Equipment equipment) { _equipment = equipment; this.level = equipment.level; this.atk = equipment.atk; this.def = equipment.def; this.hp = equipment.hp; this.eqpName = equipment.name; this.type = equipment.type; this.imagePath = equipment.imagePath; Button_Eqp = GetControl<Button>("Button_eqpOn"); Button_eqpIntensify = GetControl<Button>("Button_eqpIntensify"); UpdateInfo(); Button_Eqp.onClick.RemoveAllListeners(); Button_Eqp.onClick.AddListener(EqpOn); Button_eqpIntensify.onClick.RemoveAllListeners(); Button_eqpIntensify.onClick.AddListener(Intensify); //EventCenter.GetInstance().AddEventListener<Equipment>("eqp", Init); } private void Intensify() { if (_equipment.level < 5) { bool tempBool = false; Init(PlayerModelController.GetInstance().EqpIntensify(_equipment,out tempBool)); if (tempBool == false) { return; } else { //Debug.Log(this.atk+"11"); GetControl<Text>("Text_atk").text = this.atk.ToString(); GetControl<Text>("Text_def").text = this.def.ToString(); GetControl<Text>("Text_hp").text = this.hp.ToString(); UpdateInfo(); //var temp = GameRoot.instance.playerModel.equipmentList.Find(x => x.id == _equipment.id); //CoinChangeSvc.GetInstance().Show(-(_equipment.upgrade_gold)); } } else { TipsSvc.GetInstance().ShowTip("µÈ¼¶×î´ó"); } EqpOn(); EventCenter.GetInstance().EventTrigger(EventDic.PlayerModelUpdate); //Debug.Log(GameRoot.instance.playerModel.eqp_weapon.atk); PlayerPrefsDataMgr.Instance.SaveData(GameRoot.instance.playerModel, GameConfig.dataStr); //throw new NotImplementedException(); } private void EqpOn() { switch (_equipment.type) { case "defense": PlayerModelController.GetInstance().Eqp_defense(_equipment); break; case "other": PlayerModelController.GetInstance().Eqp_other(_equipment); break; case "decorate": PlayerModelController.GetInstance().Eqp_decorate(_equipment); break; case "weapon": PlayerModelController.GetInstance().Eqp_weapon(_equipment); break; } try { GameObject.FindGameObjectWithTag("Player").GetComponent<Animator>().SetTrigger("attack"); } catch { } EventCenter.GetInstance().EventTrigger(EventDic.PlayerModelUpdate); //TipsSvc.GetInstance().ShowTip(_equipment.id + " :" + " " + _equipment.atk + " :"); //Eqp.enabled = false; //throw new NotImplementedException(); } private void UpdateInfo() { GetControl<Image>("Image_eqpIcon").sprite= ResMgr.GetInstance().Load<Sprite>(imagePath); GetControl<Text>("Text_eqpName").text = eqpName+"+"+level; GetControl<Text>("Text_atk").text = atk.ToString(); GetControl<Text>("Text_def").text = def.ToString(); GetControl<Text>("Text_hp").text = hp.ToString(); //throw new NotImplementedException(); //EventCenter.GetInstance().EventTrigger(EventDic.PlayerModelUpdate); } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
namespace com.Sconit.WebService { using System.Collections.Generic; using System.Web.Services; using System.Web.Services.Protocols; using com.Sconit.Entity; using System; using System.Xml.Serialization; using System.Collections; using com.Sconit.Service.SI; [WebService(Namespace = "http://com.Sconit.WebService.EDI.ScheduleService/")] public class EDI_ScheduleService : BaseWebService { #region public properties private IEDI_ScheduleMgr scheduleMgr { get { return GetService<IEDI_ScheduleMgr>(); } } #endregion [WebMethod] public void LoadEDI() { scheduleMgr.LoadEDI(); } [WebMethod] public void EDI2Plan(string userCode) { SecurityContextHolder.Set(securityMgr.GetUser(userCode)); scheduleMgr.EDI2Plan(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbstractsInterfaces { interface IMyInterfaceExc05 { int Method01(char s); } interface IMyInterfaceExc051 { char Method02(int n); } internal class MyClassExc05 : IMyInterfaceExc05, IMyInterfaceExc051 { public int Number; public char Symb; public int Method01(char s) { Number = (int)s; return Number; } public char Method02(int n) { Symb = (char)n; return Symb; } } internal class Exc05 { public static void Main05() { MyClassExc05 A = new MyClassExc05(); A.Method02(65); MyClassExc05 B = new MyClassExc05(); B.Method01('D'); Console.WriteLine(A.Symb); Console.WriteLine(A.Number); Console.WriteLine(B.Symb); Console.WriteLine(B.Number); IMyInterfaceExc05 R = A; IMyInterfaceExc051 R1 = A; IMyInterfaceExc05 R2 = B; IMyInterfaceExc051 R3 = B; R.Method01('M'); R1.Method02(88); R2.Method01('P'); R3.Method02(99); } } }
namespace BikeDistributor.Interfaces.Services { public interface IReceiptContentService { string Generate( int orderId, string classForOrderLineContainer, string classForOrderLine, string classForSubTotalContainer, string classForSubTotalLines); } }
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Java.Interop; namespace Lollipop { [Activity(Label = "Lollipop", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { private Spinner typeSpinner; private SeekBar delaySeekBar; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); typeSpinner = FindViewById<Spinner>(Resource.Id.type); ArrayAdapter<string> typesAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, Resources.GetStringArray(Resource.Array.types)); typesAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); typeSpinner.Adapter = typesAdapter; delaySeekBar = FindViewById<SeekBar>(Resource.Id.delay); } [Export("NotifyMe")] public void NotifyMe(View view) { Intent i = new Intent(this, typeof(AlarmReceiver)).PutExtra(AlarmReceiver.EXTRA_TYPE, typeSpinner.SelectedItemPosition); PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, i, PendingIntentFlags.UpdateCurrent); AlarmManager manager = (AlarmManager)GetSystemService(Application.AlarmService); manager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + (1000 * delaySeekBar.Progress), pendingIntent); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Vuforia; public class Slow : MonoBehaviour { public GameObject slow; Controller controller; //public Controller controller; // Start is called before the first frame update void Start() { slow = GameObject.Find("SlowDownButton"); slow.GetComponent<VirtualButtonBehaviour>().RegisterOnButtonPressed(OnButtonPressed); slow.gameObject.GetComponent<VirtualButtonBehaviour>().RegisterOnButtonReleased(OnButtonReleased); controller = GameObject.FindGameObjectWithTag("GameController").GetComponent<Controller>(); } public void OnButtonPressed(VirtualButtonBehaviour vb) { //Add slow code here controller.slowDown(); print("Slowing"); Debug.Log("Slowing"); } public void OnButtonReleased(VirtualButtonBehaviour vb) { print("Not Slowing"); Debug.Log("Not Slowing"); } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BudgetApp.Domain.Entities { public class CreditEntry { [HiddenInput(DisplayValue=false)] public int CreditEntryId { get; set; } [DataType(DataType.Date)] [Display(Name="The Date")] public DateTime Date { get; set; } [DataType(DataType.Date)] public DateTime? PayDate { get; set; } public String Description { get; set; } //public String Card { get; set; } public CardEntry Card { get; set; } [DataType(DataType.Currency)] public decimal PurchaseTotal { get; set; } [DataType(DataType.Currency)] public decimal AmountPaid { get; set; } [DataType(DataType.Currency)] public decimal AmountRemaining { get; set; } [Column("Party")] public virtual PartyEntry ResponsibleParty { get; set; } //public String ResponsibleParty { get; set; } //[ForeignKey("id")] //public virtual PaymentPlanCharge PaymentPlanCharge { get; set; } } }
using Cs_Gerencial.Aplicacao.Interfaces; using Cs_Gerencial.Dominio.Entities; using Cs_Notas.Aplicacao.Interfaces; using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Cs_Notas.Windows.Escritura { /// <summary> /// Interaction logic for ImovelEscritura.xaml /// </summary> public partial class ImovelEscritura : Window { DigitarEscritura _digitarEscritura; public Imovel imovel; List<string> Ufs = new List<string>(); string _tipoBem; public List<ServentiasOutras> serventiasOutras; int ordemImovel; public ServentiasOutras serventiasOutrasSelecionada; private readonly IAppServicoMunicipios _AppServicoMunicipios = BootStrap.Container.GetInstance<IAppServicoMunicipios>(); private readonly IAppServicoServentia _AppServicoServentia = BootStrap.Container.GetInstance<IAppServicoServentia>(); private readonly IAppServicoServentiasOutras _AppServicoServentiasOutras = BootStrap.Container.GetInstance<IAppServicoServentiasOutras>(); private readonly IAppServicoImovel _AppServicoImovel = BootStrap.Container.GetInstance<IAppServicoImovel>(); private readonly IAppServicoBensAtosConjuntos _AppServicoBensAtosConjuntos = BootStrap.Container.GetInstance<IAppServicoBensAtosConjuntos>(); public string estado; public ImovelEscritura(DigitarEscritura digitarEscritura, string tipoBem) { _digitarEscritura = digitarEscritura; _tipoBem = tipoBem; estado = _digitarEscritura.estado; InitializeComponent(); } private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { this.Close(); } private void Window_Loaded(object sender, RoutedEventArgs e) { CarregarUF(); serventiasOutras = _AppServicoServentiasOutras.GetAll().ToList(); cmbZonaImovel.SelectedIndex = 0; cmbZonaImovel.Focus(); if (_digitarEscritura.estado == "adicionando imovel") { if (_digitarEscritura.listaImoveis.Count > 0) ordemImovel = _digitarEscritura.listaImoveis.Max(p => p.Ordem) + 1; else ordemImovel = 1; } else { ordemImovel = _digitarEscritura.listaImoveis[_digitarEscritura.dataGridImovel.SelectedIndex].Ordem; imovel = _digitarEscritura.listaImoveis.Where(p => p.ImovelId == ((Imovel)_digitarEscritura.dataGridImovel.SelectedItem).ImovelId).FirstOrDefault(); } if (imovel != null) CarregarImovel(); else imovel = new Imovel(); if (_digitarEscritura.estado == "adicionando imovel") { lblTexto.Content = string.Format("Incluindo novo imóvel Nº {0}", ordemImovel); } else { lblTexto.Content = string.Format("Alterando imóvel Nº {0}", ordemImovel); } dataGridAtoConjunto.ItemsSource = _digitarEscritura.listaAtos; CarregarBensConjuntosNaLista(); } private void CarregarImovel() { switch (imovel.TipoRecolhimento) { case "N": cmbRecolhimentoImovel.SelectedIndex = 0; break; case "I": cmbRecolhimentoImovel.SelectedIndex = 1; break; case "F": cmbRecolhimentoImovel.SelectedIndex = 2; break; default: break; } if (imovel.SubTipo == "1") cmbTipoImovel.SelectedIndex = 0; if (imovel.SubTipo == "2") cmbTipoImovel.SelectedIndex = 1; if (imovel.TipoImovel == "U") { cmbZonaImovel.SelectedIndex = 0; } if (imovel.TipoImovel == "R") { cmbZonaImovel.SelectedIndex = 1; } txtCepImovel.Text = imovel.Cep; txtNumeroImovel.Text = imovel.Numero.ToString(); txtInscricaoImobiliaria.Text = imovel.InscricaoImobiliaria; txtInscricaoIncraImovel.Text = imovel.Incra; txtAreaImovel.Text = imovel.Area; txtValorAlienadoImovel.Text = string.Format("{0:n2}", imovel.ValorAlienacao); txtDenominacaoImovel.Text = imovel.Denominacao; txtInscricaoSRFImovel.Text = imovel.SRF; txtEnderecoImovel.Text = imovel.Endereco; txtBairro.Text = imovel.Bairro; cmbMunicipio.Text = imovel.Municipio; cmbUfImovel.Text = imovel.Uf; txtGuiaImpostoImovel.Text = imovel.Guia; txtCpfCnpjAdquirente.Text = imovel.Adquirente; txtCpfCnpjCedente.Text = imovel.Cedente; txtMaiorPorcaoImovel.Text = imovel.MaiorPorcao; txtValorBemImovel.Text = string.Format("{0:N2}", imovel.Valor); txtParteTransferidaImovel.Text = imovel.ParteTranferida; txtMatriculaImovel.Text = imovel.Matricula; txtComplementoImovel.Text = imovel.Complemento; txtServentia.Text = imovel.Rgi; txtLocalImovel.Text = imovel.LocalTerreno; txtValorGuiaImpostoImovel.Text = string.Format("{0:N2}", imovel.ValorGuia); cmbMunicipio.SelectedValue = imovel.CodigoMunicipio; txtCodigo.Text = imovel.Serventia.ToString(); cmbTipoImpostoImovel.Text = imovel.TipoImposto; if (txtAreaImovel.Text != "") ckbNaoConstaAreaImovel.IsChecked = false; else ckbNaoConstaAreaImovel.IsChecked = true; _tipoBem = imovel.TipoBem; cmbZonaImovel.Focus(); } private void CarregarBensConjuntosNaLista() { var bensConjuntos = _digitarEscritura.listaBensAtosConjuntos.Where(p => p.IdImovel == imovel.ImovelId).ToList(); foreach (var item in _digitarEscritura.listaAtos) { item.IsChecked = false; if (imovel.Principal == "S") _digitarEscritura.listaAtos[0].IsChecked = true; if (_digitarEscritura.estado == "alterando imovel") for (int i = 0; i < bensConjuntos.Count; i++) { if (item.ConjuntoId == bensConjuntos[i].IdAtoConjunto) item.IsChecked = true; } else item.IsChecked = true; } } private void CarregarUF() { Ufs = _AppServicoMunicipios.ObterUfsDosMunicipios(); cmbUfImovel.ItemsSource = Ufs; } private void cmbZona_SelectionChanged(object sender, SelectionChangedEventArgs e) { AbilitarDesabilitarUrbano(cmbZonaImovel.SelectedIndex); AbilitarDesabilitarRural(cmbZonaImovel.SelectedIndex); } private void AbilitarDesabilitarUrbano(int indice) { if (indice == 0) { GridZonaUrbana.IsEnabled = true; } else { txtCepImovel.Text = ""; txtEnderecoImovel.Text = ""; txtNumeroImovel.Text = ""; txtComplementoImovel.Text = ""; txtBairro.Text = ""; GridZonaUrbana.IsEnabled = false; } } private void AbilitarDesabilitarRural(int indice) { if (indice == 1) { GridZonaRural.IsEnabled = true; } else { txtLocalImovel.Text = ""; txtDenominacaoImovel.Text = ""; txtInscricaoIncraImovel.Text = ""; txtInscricaoSRFImovel.Text = ""; txtAreaImovel.Text = ""; ckbNaoConstaAreaImovel.IsChecked = true; GridZonaRural.IsEnabled = false; } } private void cmbZona_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void btnConsultarServentia_Click(object sender, RoutedEventArgs e) { var consultarServentia = new ConsultaServentias(this); consultarServentia.Owner = this; consultarServentia.ShowDialog(); if (serventiasOutrasSelecionada != null) { txtCodigo.Text = serventiasOutrasSelecionada.Codigo.ToString(); txtServentia.Text = serventiasOutrasSelecionada.Descricao; } } private void txtCodigo_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); PassarDeUmCoponenteParaOutro(sender, e); } private void txtCodigo_TextChanged(object sender, TextChangedEventArgs e) { if (txtCodigo.Text.Length > 0) PesquisarServentia(); else txtServentia.Text = ""; } private void PesquisarServentia() { var codigo = Convert.ToInt32(txtCodigo.Text); serventiasOutrasSelecionada = serventiasOutras.Where(p => p.Codigo == codigo).FirstOrDefault(); if (serventiasOutrasSelecionada != null) txtServentia.Text = serventiasOutrasSelecionada.Descricao; else txtServentia.Text = ""; } private void cmbMunicipio_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void cmbMunicipio_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void DigitarSomenteNumeros(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key >= 34 && key <= 43 || key >= 74 && key <= 83 || key == 2 || key == 3 || key == 23 || key == 25 || key == 32); } private void DigitarSemNumeros(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key == 2 || key == 3 || key == 23 || key == 25 || key == 32); } private void DigitarSomenteNumerosEmReaisComVirgual(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key >= 34 && key <= 43 || key >= 74 && key <= 83 || key == 2 || key == 3 || key == 23 || key == 25 || key == 32 || key == 142 || key == 88); } private void DigitarSomenteLetras(object sender, KeyEventArgs e) { int key = (int)e.Key; e.Handled = !(key == 2 || key == 3 || key == 23 || key == 25 || key == 32 || key >= 44 && key <= 69); } private void dataGridAtoConjunto_MouseDoubleClick(object sender, MouseButtonEventArgs e) { var quant = 0; foreach (var item in _digitarEscritura.listaAtos) { if (item.IsChecked == true) { quant++; } } if (((AtoConjuntos)dataGridAtoConjunto.SelectedItem).IsChecked == true && quant > 1) { _digitarEscritura.listaAtos[dataGridAtoConjunto.SelectedIndex].IsChecked = false; } else { _digitarEscritura.listaAtos[dataGridAtoConjunto.SelectedIndex].IsChecked = true; } dataGridAtoConjunto.Items.Refresh(); } private void MenuItemMarcarTodos_Click(object sender, RoutedEventArgs e) { MarcarTodosCheckes(); } private void MenuItemDesmarcarTodos_Click(object sender, RoutedEventArgs e) { DesmarcarTodosCheckes(); } private void DesmarcarTodosCheckes() { try { foreach (var item in _digitarEscritura.listaAtos) { item.IsChecked = false; } _digitarEscritura.listaAtos[0].IsChecked = true; dataGridAtoConjunto.Items.Refresh(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void MarcarTodosCheckes() { try { foreach (var item in _digitarEscritura.listaAtos) { item.IsChecked = true; dataGridAtoConjunto.Items.Refresh(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnSalvarImovel_Click(object sender, RoutedEventArgs e) { SalvarImovel(); SalvarBensConjuntosNaLista(); _digitarEscritura.dataGridImovel.Items.Refresh(); if (imovel != null) { _digitarEscritura.dataGridImovel.ItemsSource = null; _digitarEscritura.dataGridImovel.ItemsSource = _digitarEscritura.listaImoveis; _digitarEscritura.dataGridImovel.SelectedItem = imovel; _digitarEscritura.dataGridImovel.ScrollIntoView(imovel); _digitarEscritura.dataGridImovel.Items.Refresh(); } this.Close(); } private void SalvarBensConjuntosNaLista() { var bensConjuntos = new BensAtosConjuntos(); if (_digitarEscritura.estado == "alterando imovel") { var listaBensConjuntos = _digitarEscritura.listaBensAtosConjuntos.Where(p => p.IdImovel == imovel.ImovelId).ToList(); foreach (var item in listaBensConjuntos) { if (item.IdAtoConjunto != 0) { var excluirBanco = _AppServicoBensAtosConjuntos.GetById(item.BensAtosConjuntosID); _AppServicoBensAtosConjuntos.Remove(excluirBanco); } _digitarEscritura.listaBensAtosConjuntos.Remove(item); } } for (int i = 0; i < _digitarEscritura.listaAtos.Count; i++) { if (_digitarEscritura.listaAtos[i].IsChecked == true) { bensConjuntos = new BensAtosConjuntos(); bensConjuntos.IdEscritura = _digitarEscritura.listaAtos[i].IdEscritura; bensConjuntos.IdImovel = imovel.ImovelId; bensConjuntos.IdAtoConjunto = _digitarEscritura.listaAtos[i].ConjuntoId; if (i > 0) _AppServicoBensAtosConjuntos.Add(bensConjuntos); _digitarEscritura.listaBensAtosConjuntos.Add(bensConjuntos); } } } private void SalvarImovel() { imovel.IdEscritura = _digitarEscritura._escrituras.EscriturasId; imovel.Ordem = ordemImovel; switch (cmbRecolhimentoImovel.SelectedIndex) { case 0: imovel.TipoRecolhimento = "N"; break; case 1: imovel.TipoRecolhimento = "I"; break; case 2: imovel.TipoRecolhimento = "F"; break; default: imovel.TipoRecolhimento = null; break; } if (_digitarEscritura.listaAtos[0].IsChecked == true) imovel.Principal = "S"; else imovel.Principal = "N"; if (cmbZonaImovel.SelectedIndex == 0) { imovel.TipoImovel = "U"; } else { imovel.TipoImovel = "R"; } if (cmbTipoImovel.SelectedIndex == 0) imovel.SubTipo = "1"; if (cmbTipoImovel.SelectedIndex == 1) imovel.SubTipo = "2"; imovel.InscricaoImobiliaria = txtInscricaoImobiliaria.Text.Trim(); imovel.Incra = txtInscricaoIncraImovel.Text.Trim(); imovel.Area = txtAreaImovel.Text; imovel.Denominacao = txtDenominacaoImovel.Text.Trim(); imovel.SRF = txtInscricaoSRFImovel.Text.Trim(); imovel.Endereco = txtEnderecoImovel.Text.Trim(); imovel.Bairro = txtBairro.Text.Trim(); imovel.Municipio = cmbMunicipio.Text; imovel.Uf = cmbUfImovel.Text; imovel.Guia = txtGuiaImpostoImovel.Text.Trim(); imovel.Adquirente = txtCpfCnpjAdquirente.Text; imovel.Cedente = txtCpfCnpjCedente.Text; imovel.MaiorPorcao = txtMaiorPorcaoImovel.Text; if (txtValorBemImovel.Text.Length > 0) imovel.Valor = Convert.ToDecimal(txtValorBemImovel.Text); imovel.ParteTranferida = txtParteTransferidaImovel.Text; if (txtValorAlienadoImovel.Text != "") imovel.ValorAlienacao = Convert.ToDecimal(txtValorAlienadoImovel.Text); imovel.Matricula = txtMatriculaImovel.Text.Trim(); imovel.Complemento = txtComplementoImovel.Text.Trim(); imovel.Rgi = txtServentia.Text.Trim(); imovel.LocalTerreno = txtLocalImovel.Text; if (txtValorGuiaImpostoImovel.Text.Length > 0) imovel.ValorGuia = Convert.ToDecimal(txtValorGuiaImpostoImovel.Text); imovel.CodigoMunicipio = Convert.ToInt32(cmbMunicipio.SelectedValue); if (txtCodigo.Text.Length > 0) imovel.Serventia = Convert.ToInt32(txtCodigo.Text); if (cmbTipoImpostoImovel.SelectedIndex > -1) imovel.TipoImposto = cmbTipoImpostoImovel.Text; if (txtNumeroImovel.Text != "") imovel.Numero = Convert.ToInt32(txtNumeroImovel.Text); imovel.Cep = txtCepImovel.Text; imovel.TipoBem = _tipoBem; if (_digitarEscritura.estado == "adicionando imovel") { _AppServicoImovel.Add(imovel); _digitarEscritura.listaImoveis.Add(imovel); } else { var imovelAlterar = (Imovel)_digitarEscritura.dataGridImovel.SelectedItem; imovelAlterar = imovel; _AppServicoImovel.Update(imovel); } } private void txtNumeroImovel_PreviewKeyDown(object sender, KeyEventArgs e) { DigitarSomenteNumeros(sender, e); PassarDeUmCoponenteParaOutro(sender, e); } private void txtMatriculaImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtInscricaoImobiliaria_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void cmbUfImovel_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (cmbUfImovel.SelectedIndex > -1) { cmbMunicipio.ItemsSource = _AppServicoMunicipios.ObterMunicipiosPorUF(Ufs[cmbUfImovel.SelectedIndex]).OrderBy(p => p.Nome); cmbMunicipio.DisplayMemberPath = "Nome"; cmbMunicipio.SelectedValuePath = "Codigo"; } } private void cmbUfImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtCepImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); DigitarSomenteNumeros(sender, e); } private void txtComplementoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtBairro_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtLocalImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtDenominacaoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtInscricaoIncraImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtInscricaoSRFImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtAreaImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); if (!txtAreaImovel.Text.Contains(",")) DigitarSomenteNumerosEmReaisComVirgual(sender, e); else { int indexVirgula = txtAreaImovel.Text.IndexOf(","); if (indexVirgula + 3 == txtAreaImovel.Text.Length) DigitarSemNumeros(sender, e); else DigitarSomenteNumeros(sender, e); } } private void cmbRecolhimentoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void cmbTipoImpostoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtGuiaImpostoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtValorGuiaImpostoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); if (txtValorGuiaImpostoImovel.SelectionLength == txtValorGuiaImpostoImovel.Text.Length) { txtValorGuiaImpostoImovel.Text = ""; } if (!txtValorGuiaImpostoImovel.Text.Contains(",")) DigitarSomenteNumerosEmReaisComVirgual(sender, e); else { int indexVirgula = txtValorGuiaImpostoImovel.Text.IndexOf(","); if (indexVirgula + 3 == txtValorGuiaImpostoImovel.Text.Length) DigitarSemNumeros(sender, e); else DigitarSomenteNumeros(sender, e); } } private void txtValorBemImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); if (txtValorBemImovel.SelectionLength == txtValorBemImovel.Text.Length) { txtValorBemImovel.Text = ""; } if (!txtValorBemImovel.Text.Contains(",")) DigitarSomenteNumerosEmReaisComVirgual(sender, e); else { int indexVirgula = txtValorBemImovel.Text.IndexOf(","); if (indexVirgula + 3 == txtValorBemImovel.Text.Length) DigitarSemNumeros(sender, e); else DigitarSomenteNumeros(sender, e); } } private void txtValorAlienadoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); if (txtValorAlienadoImovel.SelectionLength == txtValorAlienadoImovel.Text.Length) { txtValorAlienadoImovel.Text = ""; } if (!txtValorAlienadoImovel.Text.Contains(",")) DigitarSomenteNumerosEmReaisComVirgual(sender, e); else { int indexVirgula = txtValorAlienadoImovel.Text.IndexOf(","); if (indexVirgula + 3 == txtValorAlienadoImovel.Text.Length) DigitarSemNumeros(sender, e); else DigitarSomenteNumeros(sender, e); } } private void txtMaiorPorcaoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtParteTransferidaImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtCpfCnpjAdquirente_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); DigitarSomenteNumeros(sender, e); } private void txtCpfCnpjCedente_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); DigitarSomenteNumeros(sender, e); } private void ckbNaoConstaAreaImovel_Checked(object sender, RoutedEventArgs e) { txtAreaImovel.Text = ""; } private void ckbNaoConstaAreaImovel_Unchecked(object sender, RoutedEventArgs e) { txtAreaImovel.Focus(); } private void txtAreaImovel_LostFocus(object sender, RoutedEventArgs e) { if (txtAreaImovel.Text != "" && txtAreaImovel.Text != ",") txtAreaImovel.Text = string.Format("{0:n2}", Convert.ToDecimal(txtAreaImovel.Text)); else txtAreaImovel.Text = ""; imovel.Area = txtAreaImovel.Text; } private void txtValorGuiaImpostoImovel_LostFocus(object sender, RoutedEventArgs e) { if (txtValorGuiaImpostoImovel.Text != "" && txtValorGuiaImpostoImovel.Text != ",") txtValorGuiaImpostoImovel.Text = string.Format("{0:n2}", Convert.ToDecimal(txtValorGuiaImpostoImovel.Text)); else txtValorGuiaImpostoImovel.Text = "0,00"; if (txtValorGuiaImpostoImovel.Text.Length > 0) imovel.ValorGuia = Convert.ToDecimal(txtValorGuiaImpostoImovel.Text); } private void txtValorBemImovel_LostFocus(object sender, RoutedEventArgs e) { if (txtValorBemImovel.Text != "" && txtValorBemImovel.Text != ",") txtValorBemImovel.Text = string.Format("{0:n2}", Convert.ToDecimal(txtValorBemImovel.Text)); else txtValorBemImovel.Text = "0,00"; if (txtValorBemImovel.Text.Length > 0) imovel.Valor = Convert.ToDecimal(txtValorBemImovel.Text); } private void txtValorAlienadoImovel_LostFocus(object sender, RoutedEventArgs e) { if (txtValorAlienadoImovel.Text != "" && txtValorAlienadoImovel.Text != ",") txtValorAlienadoImovel.Text = string.Format("{0:n2}", Convert.ToDecimal(txtValorAlienadoImovel.Text)); else txtValorAlienadoImovel.Text = "0,00"; if (txtValorAlienadoImovel.Text != "") imovel.ValorAlienacao = Convert.ToDecimal(txtValorAlienadoImovel.Text); } private void btnImporarImovel_Click(object sender, RoutedEventArgs e) { if (_digitarEscritura.listaNomes.Count > 0) { var alienante = _digitarEscritura.listaNomes.Where(p => p.Tipo == "AL").FirstOrDefault(); var adiquirente = _digitarEscritura.listaNomes.Where(p => p.Tipo == "AD").FirstOrDefault(); if (adiquirente != null) txtCpfCnpjAdquirente.Text = adiquirente.Documento; if (alienante != null) txtCpfCnpjCedente.Text = alienante.Documento; } } private void PassarDeUmCoponenteParaOutro(object sender, KeyEventArgs e) { var uie = e.OriginalSource as UIElement; if (e.Key == Key.Enter) { e.Handled = true; uie.MoveFocus( new TraversalRequest( FocusNavigationDirection.Next)); } } private void cmbTipoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtServentia_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void txtEnderecoImovel_PreviewKeyDown(object sender, KeyEventArgs e) { PassarDeUmCoponenteParaOutro(sender, e); } private void btnDoi_Click(object sender, RoutedEventArgs e) { var doi = new ImovelDoi(this, _digitarEscritura.dtDataAto.SelectedDate.Value, estado); doi.Owner = this; doi.ShowDialog(); } private void txtAreaImovel_TextChanged(object sender, TextChangedEventArgs e) { if (txtAreaImovel.Text.Length > 0) { ckbNaoConstaAreaImovel.IsChecked = false; } else ckbNaoConstaAreaImovel.IsChecked = true; } private void txtNumeroImovel_GotFocus(object sender, RoutedEventArgs e) { if (txtNumeroImovel.Text == "0") txtNumeroImovel.Text = ""; } private void txtValorGuiaImpostoImovel_GotFocus(object sender, RoutedEventArgs e) { if (txtValorGuiaImpostoImovel.Text == "0,00") txtValorGuiaImpostoImovel.Text = ""; } private void txtValorBemImovel_GotFocus(object sender, RoutedEventArgs e) { if (txtValorBemImovel.Text == "0,00") txtValorBemImovel.Text = ""; } private void txtValorAlienadoImovel_GotFocus(object sender, RoutedEventArgs e) { if (txtValorAlienadoImovel.Text == "0,00") txtValorAlienadoImovel.Text = ""; } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; namespace TexturePacker.Editor.Transformation { public class TextureImporterWrapper : IDisposable { private readonly TextureImporter _textureImporter; private readonly string _path; private readonly List<SpriteMetaData> _spritesMetaData; private readonly List<Sprite> _sprites; public List<Sprite> Sprites{get { return _sprites; }} public TextureImporterWrapper(string path, bool resetSprites = true) { _path = path; _textureImporter = (TextureImporter)AssetImporter.GetAtPath(path); if (resetSprites) { _textureImporter.spriteImportMode = SpriteImportMode.Single; AssetDatabase.ImportAsset(_path, ImportAssetOptions.ForceUpdate); } _textureImporter.isReadable = true; _textureImporter.spriteImportMode = SpriteImportMode.Multiple; _spritesMetaData = _textureImporter.spritesheet.ToList(); _sprites = AssetDatabase.LoadAllAssetsAtPath(path).OfType<Sprite>().ToList(); } public void ClearSpritesMetaData() { _spritesMetaData.Clear(); } public void AddSpriteMetaData(string name, Rect rect, Vector2 pivot, Vector4 border) { var smd = new SpriteMetaData() { alignment = 9, //Custom pivot pivot = pivot, rect = rect, name = name, border = border, }; _spritesMetaData.Add(smd); } public Sprite GetSprite(string name) { return _sprites.SingleOrDefault(x => x.name.Equals(name)); } public void Dispose() { _textureImporter.spritesheet = _spritesMetaData.ToArray(); AssetDatabase.ImportAsset(_path, ImportAssetOptions.ForceUpdate); } } }
using NUnit.Framework; using NUnit.Framework.Constraints; using HomeWorkArrayList; namespace HomeworkArrayList.Test { public class ArrayListTest { int[] array; int[] array2; ArrayList ArrayList; [SetUp] public void Setup() { array = new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 }; ArrayList = new ArrayList(array); } [Test] [TestCase(30, new int[] { 30, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(15, new int[] { 15, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(0, new int[] { 0, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(-40, new int[] { -40, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(123456, new int[] { 123456, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] public void AddFirsttest(int value, int[] expected) { int[] actual = ArrayList.AddFirst(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2 }, new int[] { 1, 2, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(new int[] { 0, 0, 0 }, new int[] { 0, 0, 0, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(new int[] { -1, -2, -3 }, new int[] { -1, -2, -3, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(new int[] { }, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] public void AddFirstArrtest(int[] value, int[] expected) { int[] actual = ArrayList.AddFirst(value); Assert.AreEqual(expected, actual); } [TestCase(1, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, 1 })] [TestCase(0, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, 0 })] [TestCase(-15, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, -15 })] [TestCase(12, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, 12 })] [TestCase(59874, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, 59874 })] public void AddLastTest(int value, int[] expected) { int[] actual = ArrayList.AddLast(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { }, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(new int[] { 1, 2 }, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, 1, 2 })] [TestCase(new int[] { 0, 0 }, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, 0, 0 })] [TestCase(new int[] { -12, -5 }, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, -12, -5 })] [TestCase(new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1, 9, 8, 7, 6, 5, 4, 3, 2, 1 })] public void AddLastArrArrtest(int[] value, int[] expected) { int[] actual = ArrayList.AddLast(value); Assert.AreEqual(expected, actual); } [TestCase(1, 59874, new int[] { 1, 59874, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(0, 59874, new int[] { 59874, 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(-1, 59874, new int[] { })] [TestCase(4, 59874, new int[] { 1, 2, 3, 6, 59874, 9, 13, 56, -1, 0, 1 })] [TestCase(15, 59874, new int[] { })] public void AddAtTest(int index, int value, int[] expected) { int[] actual = ArrayList.AddAt(value, index); Assert.AreEqual(expected, actual); } [TestCase(-1, new int[] { 1, 2, 4 }, new int[] { })] [TestCase(4, new int[] { 1, 2, 4 }, new int[] { 1, 2, 3, 6, 1, 2, 4, 9, 13, 56, -1, 0, 1 })] [TestCase(7, new int[] { 1, 2, 4 }, new int[] { 1, 2, 3, 6, 9, 13, 56, 1, 2, 4, -1, 0, 1 })] [TestCase(1, new int[] { 1, 2, 4 }, new int[] { 1, 1, 2, 4, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(2, new int[] { }, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] public void AddAtArrtest(int index, int[] value, int[] expected) { int[] actual = ArrayList.AddAt(value, index); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 3)] [TestCase(new int[] { }, 0)] [TestCase(new int[] { 1 }, 1)] public void GetSizetest(int[] value, int expected) { int actual = ArrayList.GetSize(value); Assert.AreEqual(expected, actual); } [TestCase(2, 1, new int[] { 1, 2, 1, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(-1, 1, new int[] { })] [TestCase(0, 1, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(5, 92, new int[] { 1, 2, 3, 6, 9, 92, 56, -1, 0, 1 })] [TestCase(15, 5, new int[] { })] public void Settest(int index, int value, int[] expected) { int[] actual = ArrayList.Set(index, value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3, 4, 5 }, new int[] { 2, 3, 4, 5 })] [TestCase(new int[] { }, new int[] { })] [TestCase(new int[] { 1 }, new int[] { })] public void RemoveFirstTest(int[] value, int[] expected) { int[] actual = ArrayList.RemoveFirst(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3, 4, 5 }, new int[] { 1, 2, 3, 4 })] [TestCase(new int[] { }, new int[] { })] [TestCase(new int[] { 1 }, new int[] { })] public void RemoveLastTest(int[] value, int[] expected) { int[] actual = ArrayList.RemoveLast(value); Assert.AreEqual(expected, actual); } [TestCase(0, new int[] { 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(-1, new int[] { })] [TestCase(20, new int[] { })] [TestCase(2, new int[] { 1, 2, 6, 9, 13, 56, -1, 0, 1 })] public void RemoveAttTest(int index, int[] expected) { int[] actual = ArrayList.RemoveAtt(index); Assert.AreEqual(expected, actual); } [TestCase(15, 5, new int[] { })] public void Settet(int index, int value, int[] expected) { int[] actual = ArrayList.Set(index, value); Assert.AreEqual(expected, actual); } [TestCase(30, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 0, 1 })] [TestCase(0, new int[] { 1, 2, 3, 6, 9, 13, 56, -1, 1 })] [TestCase(1, new int[] { 2, 3, 6, 9, 13, 56, -1, 0 })] [TestCase(56, new int[] { 1, 2, 3, 6, 9, 13, -1, 0, 1 })] public void RemoveAllTest(int value, int[] expected) { int[] actual = ArrayList.RemoveAll(value); Assert.AreEqual(expected, actual); } [TestCase(56, true)] [TestCase(23, false)] public void ContainsTest(int value, bool expected) { bool actual = ArrayList.Contains(value); Assert.AreEqual(expected, actual); } [TestCase(56, 6)] [TestCase(23, -1)] public void IndexOfTest(int value, int expected) { int actual = ArrayList.IndexOf(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })] [TestCase(new int[] { }, new int[] { })] public void ToArrayTest(int[] value, int[] expected) { int[] actual = ArrayList.ToArray(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 1)] [TestCase(new int[] { }, 0)] public void GetFirstTest(int[] value, int expected) { int actual = ArrayList.GetFirst(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 3)] [TestCase(new int[] { }, 0)] public void GetLastTest(int[] value, int expected) { int actual = ArrayList.GetLast(value); Assert.AreEqual(expected, actual); } [TestCase(0, 1)] [TestCase(-1, 0)] [TestCase(1, 2)] [TestCase(15, 0)] public void GetTest(int index, int expected) { int actual = ArrayList.Get(index); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, new int[] { 3, 2, 1 })] [TestCase(new int[] { 1, 2, 3, 4 }, new int[] { 4, 3, 2, 1 })] [TestCase(new int[] { }, new int[] { })] public void ReversTest(int[] value, int[] expected) { int[] actual = ArrayList.Reverse(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 3)] [TestCase(new int[] { }, 0)] public void MaxTest(int[] value, int expected) { int actual = ArrayList.Max(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 1)] [TestCase(new int[] { }, 0)] public void MinTest(int[] value, int expected) { int actual = ArrayList.Min(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 2)] [TestCase(new int[] { }, -1)] public void IndexOfMaxTest(int[] value, int expected) { int actual = ArrayList.IndexOfMax(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 0)] [TestCase(new int[] { }, -1)] public void IndexOfMinTest(int[] value, int expected) { int actual = ArrayList.IndexOfMin(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })] [TestCase(new int[] { 3, 2, 1, 3, 5, 7, 1 }, new int[] { 1, 1, 2, 3, 3, 5, 7 })] [TestCase(new int[] { }, new int[] { })] public void SortTest(int[] value, int[] expected) { int[] actual = ArrayList.Sort(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 2, 1 }, new int[] { 3, 2, 1 })] [TestCase(new int[] { 3, 2, 1, 3, 5, 7, 1 }, new int[] { 7, 5, 3, 3, 2, 1, 1 })] [TestCase(new int[] { }, new int[] { })] public void SortDescTest(int[] value, int[] expected) { int[] actual = ArrayList.SortDesc(value); Assert.AreEqual(expected, actual); } } }
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.Runtime.InteropServices; namespace UseFul.Forms.Welic { public partial class FormMensagem : Form { //Para criar o formulario com cantos arredondados: //http://bytes.com/topic/c-sharp/answers/256570-how-do-i-create-windows-forms-rounded-corners //a propriedade Opacity varia de 0.00 a 1.00 //menos opacidade significa maior transparência private const double ValorDecrescimentoOpacidade = 0.02; //tempo em milisegundos para diminuir a opacidade do form private const int FrequenciaDecrescimentoOpacidade = 40; //tempo a ser aguardado antes de começar a diminuir a opacidade do form (em milisegundos) private const int DelayInicial = 1000; private bool PosicionarFormNoCursor { get; set; } private string mensagem; public Icon icone { get; set; } public Color? backColor { get; set; } public Color? foreColor { get; set; } public Font FonteMensagem { get; set; } public FormMensagem(string mensagem) { InitializeComponent(); PosicionarFormNoCursor = true; this.mensagem = mensagem; } [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")] private static extern IntPtr CreateRoundRectRgn ( int nLeftRect, // x-coordinate of upper-left corner int nTopRect, // y-coordinate of upper-left corner int nRightRect, // x-coordinate of lower-right corner int nBottomRect, // y-coordinate of lower-right corner int nWidthEllipse, // height of ellipse int nHeightEllipse // width of ellipse ); Timer tmrDelayInicial; Timer tmrDecaimentoOpacidade; private void FormMensagem_Load(object sender, EventArgs e) { this.Opacity = 1.00; this.ShowInTaskbar = false; if (PosicionarFormNoCursor) this.Location = Cursor.Position; if (this.icone == null) icone = SystemIcons.Information; if (this.backColor == null) this.backColor = Color.FromArgb(192, 255, 192); if (this.foreColor == null) this.foreColor = Color.FromArgb(0, 64, 0); if (this.FonteMensagem == null) this.FonteMensagem = lblMensagem.Font; lblMensagem.Text = mensagem; pictureBoxPersonalizado1.Image = this.icone.ToBitmap(); this.BackColor = this.backColor.Value; lblMensagem.ForeColor = this.foreColor.Value; lblMensagem.Font = this.FonteMensagem; this.Size = new System.Drawing.Size(pictureBoxPersonalizado1.Width + lblMensagem.Width + 45, this.Size.Height); Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width - 10, Height - 10, 20, 20)); // adjust these parameters to get the look you want. tmrDelayInicial = new Timer(); tmrDelayInicial.Tick += new EventHandler(tmrDelayInicial_Tick); tmrDelayInicial.Interval = DelayInicial; tmrDelayInicial.Enabled = true; } void tmrDelayInicial_Tick(object sender, EventArgs e) { //chama o outro timer (para iniciar o desaparecimento do form) tmrDecaimentoOpacidade = new Timer(); tmrDecaimentoOpacidade.Tick += new EventHandler(tmrDecaimentoOpacidade_Tick); tmrDecaimentoOpacidade.Interval = FrequenciaDecrescimentoOpacidade; tmrDecaimentoOpacidade.Enabled = true; //desabilita o timer inicial tmrDelayInicial.Enabled = false; } void tmrDecaimentoOpacidade_Tick(object sender, EventArgs e) { if (!this.Bounds.Contains(Cursor.Position)) { //quando a opacidade chegar no valor minimo, fecha o form if (this.Opacity > ValorDecrescimentoOpacidade) { this.Opacity -= ValorDecrescimentoOpacidade; } else { this.Dispose(); } } } private void FormMensagem_MouseEnter(object sender, EventArgs e) { //cancela o desaparecimento if (tmrDecaimentoOpacidade != null) { tmrDecaimentoOpacidade.Enabled = false; Opacity = 1.00; } } private void FormMensagem_MouseLeave(object sender, EventArgs e) { //reinicia o processo PosicionarFormNoCursor = false; if (tmrDelayInicial != null) tmrDelayInicial.Enabled = false; if (tmrDecaimentoOpacidade != null) tmrDecaimentoOpacidade.Enabled = false; FormMensagem_Load(null, null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace XH.APIs.WebAPI.Models.Assets { public class BlobInfoReponseModel { public string RelativeUrl { get; set; } public string Url { get; set; } public string Name { get; set; } public string Size { get; set; } public string MimeType { get; set; } public DateTime? UtcModifiedDate { get; set; } } }
using ReceptiAPI.Modeli; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ReceptiAPI.PristupPodacima.Interfejsi { public interface IRepozitorijum<T> where T : class { Task<List<T>> PronadjiSve(string poljeFiltera, string vrednostFiltera, bool filterirajDeoVrednosti, int brojStrane, int velicinaStrane); Task<List<T>> PronadjiSve(string poljeFiltera, List<string> vrednostFiltera, int brojStrane, int velicinaStrane); Task<(List<T>, Paginacija)> PronadjiSveSaPaginacijom(string poljeFiltera = null, string vrednostFiltera = null, bool filterirajDeoVrednosti = false, int brojStrane = 1, int velicinaStrane = 10); Task<T> PronadjiJedan(string id); Task<T> Kreiraj(T objekat); Task<T> Azuriraj(T objekat); Task Obrisi(string id); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UnityStandardAssets.CrossPlatformInput { public class GetItemObject : Photon.MonoBehaviour { float v; float h; private Vector3 velocity; bool _isGet = false; PhotonView photonView; GameObject targetObj; public string[] item_name; public PhotonView target_photonView; public int view_ID_target; float lifeTime; // Use this for initialization void Start() { this.gameObject.GetPhotonView().TransferOwnership(0); this.gameObject.name = this.gameObject.name.Replace("(Clone)", ""); photonView = GetComponent<PhotonView>(); } // Update is called once per frame void Update() { lifeTime += Time.deltaTime; if(lifeTime >= 50 && PhotonNetwork.isMasterClient){ photonView.RPC("OnDestroy", PhotonTargets.AllBufferedViaServer); } } void OnTriggerStay(Collider col) {/* if (col.gameObject.name == "MyPlayer") { if(!target_photonView){ return; } if (this.gameObject != PhotonNetwork.isMasterClient) { return; } transform.LookAt(targetObj.transform); velocity = new Vector3(h, 0, v); velocity = transform.TransformDirection(velocity); transform.localPosition += velocity * Time.fixedDeltaTime * 10; v += Time.deltaTime; }*/ } private void OnTriggerEnter(Collider col) { /* if(col.gameObject.tag == "Player"){ targetObj = col.gameObject; target_photonView = targetObj.GetPhotonView(); view_ID_target = target_photonView.viewID; targetObj = PhotonView.Find(view_ID_target).gameObject; }*/ } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "MyPlayer") { //破壊のためのオーナーID譲渡処理 //this.gameObject.GetPhotonView().TransferOwnership(collision.gameObject.GetPhotonView().ownerId); if(this.transform.gameObject.name == "WoodItem"){ collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().wooditem++; } if (this.transform.gameObject.name == "StoneItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().stoneitem++; } if (this.transform.gameObject.name == "MeatItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().meatitem++; } if (this.transform.gameObject.name == "BlueMetalItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().blueMetalitem++; } if (this.transform.gameObject.name == "NutsItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().nutsItem++; } if (this.transform.gameObject.name == "GlassItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().glassItem++; } if (this.transform.gameObject.name == "BottleItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().bottleItem++; } if (this.transform.gameObject.name == "WaterBottleItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().water_bottleItem++; } if (this.transform.gameObject.name == "NutsBottleItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().nuts_bottleItem++; } if (this.transform.gameObject.name == "MeatBakedItem") { collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().meat_baked_item++; } collision.gameObject.GetComponent<UnityChanControlScriptWithRgidBody>().GetEssence(); photonView.RPC("OnDestroy",PhotonTargets.All); //photonView.RPC("OnDestroy", PhotonTargets.All); } } [PunRPC] public void OnDestroy() { Destroy(this.gameObject); } void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { if (stream.isWriting) { // stream.SendNext(view_ID_target); //stream.SendNext(targetObj); } else { // view_ID_target = (int)stream.ReceiveNext(); //targetObj = (GameObject)stream.ReceiveNext(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MyClassLibrary; namespace Les3Exercise3 { class Program { //Ронжин Л. //3.*Описать класс дробей — рациональных чисел, являющихся отношением двух целых чисел. //Предусмотреть методы сложения, вычитания, умножения и деления дробей. //Написать программу, демонстрирующую все разработанные элементы класса. //* Добавить свойства типа int для доступа к числителю и знаменателю; //* Добавить свойство типа double только на чтение, чтобы получить десятичную дробь числа; //** Добавить проверку, чтобы знаменатель не равнялся 0. Выбрасывать исключение ArgumentException("Знаменатель не может быть равен 0"); //*** Добавить упрощение дробей. static void Main(string[] args) { string mes1 = "Введите числитель 1й дроби"; string mes2 = "Введите знаменатель 1й дроби"; Ratio ratio1 = new Ratio(MyMetods.ReadInt(mes1), MyMetods.ReadInt(mes2)); mes1 = "Введите числитель 2й дроби"; mes2 = "Введите знаменатель 2й дроби"; Ratio ratio2 = new Ratio(); ratio2.M = MyMetods.ReadInt(mes1); ratio2.N = MyMetods.ReadInt(mes2); MyMetods.Print($"У Вас есть 2 дроби:{ratio1} и {ratio2}."); MyMetods.Print($"В десятичной форме данные дроби имеют вид: {ratio1.Des} и {ratio2.Des}."); Ratio rez; rez = Ratio.Simplification(Ratio.Sum(ratio1, ratio2)); Console.WriteLine($"{ratio1} + {ratio2} = {rez}"); rez = Ratio.Simplification(Ratio.Minus(ratio1, ratio2)); Console.WriteLine($"{ratio1} - {ratio2} = {rez}"); rez = Ratio.Simplification(Ratio.Multi(ratio1, ratio2)); Console.WriteLine($"{ratio1} * {ratio2} = {rez}"); rez = Ratio.Simplification(Ratio.Div(ratio1, ratio2)); Console.WriteLine($"{ratio1} / {ratio2} = {rez}"); MyMetods.Pause(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; public class MainMenuManagement : MonoBehaviour { public GameObject loadPanel; // When we hit play game, load the game. public void PlayGame() { LoadingScreen.Instance.LoadScene("MightyKingdom"); } public void QuitGame() { // Once we click this, the game will stop running. Application.Quit(); } }
using System; using System.Collections.Generic; using System.Text; namespace ApplicationCore.Entities { public class Basket :BaseEntity { public string BuyerId { get; set; } public List<BasketItem> Items { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Principal; using System.Web.Security; namespace ScoreSquid.Web.Authentication { public class PlayerIdentity : IIdentity { private FormsAuthenticationTicket ticket; public PlayerIdentity(FormsAuthenticationTicket ticket) { this.ticket = ticket; } public string AuthenticationType { get { return "ScoreSquid"; } } public bool IsAuthenticated { get { return true; } } public string Name { get { return ticket.Name; } } public string FriendlyName { get { return ticket.UserData; } } } }
namespace OpenApiLib.Json.Models { public class PendingOrderJson : AbstractJson { public long OrderId { get; set; } public string SymbolName { get; set; } public string OrderType { get; set; } public string TradeSide { get; set; } public double Price { get; set; } public long Volume { get; set; } public double StopLoss { get; set; } public double TakeProfit { get; set; } public long CreateTimestamp { get; set; } public long ExpirationTimestamp { get; set; } public double CurrentPrice { get; set; } public double DistanceInPips { get; set; } public string Comment { get; set; } public string Channel { get; set; } public string Label { get; set; } } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using UnityEditor.Build.Reporting; using System; using System.Diagnostics; using System.IO; // On Unity 2018.3.7f1, I had to set Scripting Runtime Version to // .NET 4.0 Equivalent, and add a csc.rsp file as detailed here: // https://forum.unity.com/threads/extracting-zip-files.472537/#post-4371022 // for System.IO.Compression.ZipFile to be available. using System.IO.Compression; public class BuildHelper : Editor { // Makes 6 builds: Windows, Mac, Linux, with and without Steam included. [MenuItem("Tools/Build Win+Mac+Linux")] static void BuildWinMacLinux() { // Ask for the directory var defaultFolderName = "winmaclinux_" + System.DateTime.Today.ToString("yyyy-MM-dd"); var baseDir = EditorUtility.SaveFilePanel( "Build Win+Mac+Linux", "builds", defaultFolderName, ""); if (baseDir == "") return; // Cancelled the dialog if (Directory.Exists(baseDir)) { UnityEngine.Debug.LogError("Directory already exists: "+baseDir); return; } Directory.CreateDirectory(baseDir); var stopwatch = new Stopwatch(); stopwatch.Start(); // Set build options var options = new BuildPlayerOptions {scenes = new string[EditorBuildSettings.scenes.Length]}; for (var i = 0; i < options.scenes.Length; i++) { options.scenes[i] = EditorBuildSettings.scenes[i].path; } options.options = BuildOptions.None; string outputDir; /* // Steam PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, ""); // Steam Windows outputDir = baseDir+"/steam_windows/Patrick's Parabox"; options.target = BuildTarget.StandaloneWindows64; options.locationPathName = outputDir+"/Patrick's Parabox.exe"; Build(options, "Steam Windows"); ZipFile.CreateFromDirectory(outputDir, baseDir+"/steam_windows.zip"); // Steam Mac outputDir = baseDir+"/steam_mac/Patrick's Parabox.app"; options.target = BuildTarget.StandaloneOSX; options.locationPathName = outputDir; Build(options, "Steam Mac"); ZipFile.CreateFromDirectory(outputDir+"/..", baseDir+"/steam_mac.zip"); // Steam Linux outputDir = baseDir+"/steam_linux/Patrick's Parabox"; options.target = BuildTarget.StandaloneLinux64; options.locationPathName = outputDir+"/Patrick's Parabox.x86_64"; Build(options, "Steam Linux"); ZipFile.CreateFromDirectory(outputDir, baseDir+"/steam_linux.zip"); */ // Non-Steam PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, "DISABLESTEAMWORKS"); // Windows outputDir = baseDir+"/windows/Patrick's Parabox"; options.target = BuildTarget.StandaloneWindows64; options.locationPathName = outputDir+"/Patrick's Parabox.exe"; Build(options, "Windows"); ZipFile.CreateFromDirectory(outputDir+"/..", baseDir+"/Patrick's Parabox Windows.zip"); // Mac outputDir = baseDir+"/mac/Patrick's Parabox.app"; options.target = BuildTarget.StandaloneOSX; options.locationPathName = outputDir; Build(options, "Mac"); ZipFile.CreateFromDirectory(outputDir+"/..", baseDir+"/Patrick's Parabox Mac.zip"); // Linux outputDir = baseDir+"/linux/Patrick's Parabox"; options.target = BuildTarget.StandaloneLinux64; options.locationPathName = outputDir+"/Patrick's Parabox.x86_64"; Build(options, "Linux"); ZipFile.CreateFromDirectory(outputDir+"/..", baseDir+"/Patrick's Parabox Linux.zip"); // Reset settings to convenient defaults PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, "DISABLESTEAMWORKS"); EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64); stopwatch.Stop(); var ts = stopwatch.Elapsed; UnityEngine.Debug.Log($"Total build time: {ts.TotalSeconds} seconds"); } static void Build(BuildPlayerOptions options, string buildName) { var report = BuildPipeline.BuildPlayer(options); var summary = report.summary; switch (summary.result) { case BuildResult.Succeeded: UnityEngine.Debug.Log(buildName + " succeeded: " + summary.totalSize + " bytes"); break; case BuildResult.Failed: UnityEngine.Debug.LogError(buildName + " failed"); UnityEngine.Debug.LogError(summary); throw new Exception(); } } } // Copies the contents of the copy_files directory into build folders. // copy_files contains a readme plus a few other files I wish to bundle with builds. // https://docs.unity3d.com/ScriptReference/Callbacks.PostProcessBuildAttribute.html public class MyBuildPostprocessor { [PostProcessBuildAttribute(1)] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { //Debug.Log(pathToBuiltProject); var copyTo = ""; if (target == BuildTarget.StandaloneWindows || target == BuildTarget.StandaloneWindows64) { copyTo = pathToBuiltProject+"/.."; } else if (target == BuildTarget.StandaloneOSX) { copyTo = pathToBuiltProject+"/Contents"; } else if (target == BuildTarget.StandaloneLinux64) { copyTo = pathToBuiltProject+"/.."; } else { UnityEngine.Debug.LogWarning("Unrecognized target - don't know where to put copy_files/"); return; } // Application.dataPath is /Aseets when running in the editor DirectoryCopy(Application.dataPath+"/../copy_files", copyTo, true); //UnityEngine.Debug.Log("Copied copy_files/"); } // From https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { // Get the subdirectories for the specified directory. var dir = new DirectoryInfo(sourceDirName); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } DirectoryInfo[] dirs = dir.GetDirectories(); // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. var files = dir.GetFiles(); foreach (var file in files) { var temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (var subdir in dirs) { var temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } } #endif
using System; using Seterlund.CodeGuard.Internals; namespace Seterlund.CodeGuard { public static class IntegerValidatorExtensions { public static ValidatorBase<int> IsOdd(this ValidatorBase<int> validator) { if (!MathUtil.IsOdd(validator.Value)) { validator.ArgumentOutRangeMessage(); } return validator; } public static ValidatorBase<long> IsOdd(this ValidatorBase<long> validator) { if (!MathUtil.IsOdd(validator.Value)) { validator.ArgumentOutRangeMessage(); } return validator; } public static ValidatorBase<int> IsEven(this ValidatorBase<int> validator) { if (!MathUtil.IsEven(validator.Value)) { validator.ArgumentOutRangeMessage(); } return validator; } public static ValidatorBase<long> IsEven(this ValidatorBase<long> validator) { if (!MathUtil.IsEven(validator.Value)) { validator.ArgumentOutRangeMessage(); } return validator; } public static ValidatorBase<int> IsPrime(this ValidatorBase<int> validator) { if(!MathUtil.IsPrime(validator.Value)) { validator.ArgumentMessage("Not a prime number"); } return validator; } public static ValidatorBase<long> IsPrime(this ValidatorBase<long> validator) { if(!MathUtil.IsPrime(validator.Value)) { validator.ArgumentMessage("Not a prime number"); } return validator; } } }
using System.Linq; using System.Collections.Generic; using System; using System.Linq.Expressions; namespace SchemaObjectMapper { public class FixedWidthSchema<T> : ISchema { public FixedWidthSchema() { this.Mappings = new List<BaseMapping>(); } public void AddMapping(Expression<Func<T, object>> expr, int startIndex, int length, bool trim = true) { this.Mappings.Add(new FixedWidthMapping<T>(expr, startIndex, length, trim)); } public List<BaseMapping> Mappings { get; private set; } } }
using Microsoft.EntityFrameworkCore.Migrations; using System; namespace Detego.API.Migrations { public partial class Init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Characteristics", columns: table => new { Id = table.Column<Guid>(nullable: false), BackStore = table.Column<int>(nullable: false), FrontStore = table.Column<int>(nullable: false), ShopWindow = table.Column<int>(nullable: false), Accuracy = table.Column<float>(nullable: false), Availability = table.Column<float>(nullable: false), MeanAge = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Characteristics", x => x.Id); }); migrationBuilder.CreateTable( name: "Managers", columns: table => new { Id = table.Column<Guid>(nullable: false), FirstName = table.Column<string>(nullable: true), LastName = table.Column<string>(nullable: true), ContactEmail = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Managers", x => x.Id); }); migrationBuilder.CreateTable( name: "Stores", columns: table => new { Id = table.Column<Guid>(nullable: false), Name = table.Column<string>(nullable: true), CountryCode = table.Column<string>(nullable: true), ContactEmail = table.Column<string>(nullable: true), ManagerId = table.Column<Guid>(nullable: false), CharacteristicId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Stores", x => x.Id); table.ForeignKey( name: "FK_Stores_Characteristics_CharacteristicId", column: x => x.CharacteristicId, principalTable: "Characteristics", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Stores_Managers_ManagerId", column: x => x.ManagerId, principalTable: "Managers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Stores_CharacteristicId", table: "Stores", column: "CharacteristicId"); migrationBuilder.CreateIndex( name: "IX_Stores_ManagerId", table: "Stores", column: "ManagerId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Stores"); migrationBuilder.DropTable( name: "Characteristics"); migrationBuilder.DropTable( name: "Managers"); } } }
using UnityEngine; using System.Collections; public class GamePiece : MonoBehaviour { Vector3 boundXZ; public bool Stable = true; public Rigidbody myRigidbody; public bool whiteUp = true; // Use this for initialization void Start () { myRigidbody = GetComponent<Rigidbody>(); boundXZ = new Vector3(myRigidbody.position.x, 0, myRigidbody.position.z); } // Update is called once per frame void Update () { if (Input.GetMouseButtonUp(1)) { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if (Physics.Raycast (ray, out hit, 100)) { myRigidbody.AddExplosionForce(2000f, hit.point + Vector3.down/2, 8f); } } if(myRigidbody.velocity.magnitude < .0001 && myRigidbody.angularVelocity.magnitude < .00001) { //If we're not right-side up, flip if(whiteUp && myRigidbody.rotation.eulerAngles.z > 30 && myRigidbody.rotation.eulerAngles.z < 330) { StartCoroutine (flipTileCoroutine ()); return; } if(!whiteUp && myRigidbody.rotation.eulerAngles.z < 150) { StartCoroutine (flipTileCoroutine ()); return; } if (!EqualWithTolerance(myRigidbody.position.x, boundXZ.x)) { float xVal = 100 * (boundXZ.x - myRigidbody.position.x); myRigidbody.velocity += Vector3.up; myRigidbody.AddForce(new Vector3(xVal, 400, 0)); Stable = false; } else if (!EqualWithTolerance(myRigidbody.position.z, boundXZ.z)) { float zVal = 100 * (boundXZ.z - myRigidbody.position.z); myRigidbody.velocity += Vector3.up; myRigidbody.AddForce(new Vector3(0, 400, zVal)); Stable = false; } else { Stable = true; } } else { Stable = false; } } void FixedUpdate() { // if(myRigidbody.velocity.magnitude < .0001 && myRigidbody.angularVelocity.magnitude < .00001) // { // //If we're not right-side up, flip // if(whiteUp && myRigidbody.rotation.eulerAngles.z > 30 && myRigidbody.rotation.eulerAngles.z < 330) // { // StartCoroutine (flipTileCoroutine ()); // return; // } // if(!whiteUp && myRigidbody.rotation.eulerAngles.z < 150) // { // StartCoroutine (flipTileCoroutine ()); // return; // } // // if (!EqualWithTolerance(myRigidbody.position.x, boundXZ.x)) // { // float xVal = 100 * (boundXZ.x - myRigidbody.position.x); // myRigidbody.velocity += Vector3.up; // myRigidbody.AddForce(new Vector3(xVal, 400, 0)); // Stable = false; // } // else if (!EqualWithTolerance(myRigidbody.position.z, boundXZ.z)) // { // float zVal = 100 * (boundXZ.z - myRigidbody.position.z); // myRigidbody.velocity += Vector3.up; // myRigidbody.AddForce(new Vector3(0, 400, zVal)); // Stable = false; // } // else // { // Stable = true; // } // } // else // { // Stable = false; // } } bool EqualWithTolerance(float one, float two) { float tolerance = 0.05f; return (two < one + tolerance && two > one - tolerance); } void OnMouseUp() { //StartCoroutine (flipTileCoroutine ()); //flipTile (); } public void flipTile() { myRigidbody.velocity += Vector3.up; StartCoroutine (flipTileCoroutine ()); whiteUp = !whiteUp; } private IEnumerator flipTileCoroutine() { myRigidbody.useGravity = false; while (myRigidbody.position.y < 2) { myRigidbody.AddForce (Vector3.up * 50 * (2 - myRigidbody.position.y)); //myRigidbody.AddForce (Vector3.up * 560); yield return new WaitForSeconds(.05f); } yield return new WaitForSeconds(.15f); //myRigidbody.AddForce (Vector3.up * 100); myRigidbody.AddTorque (0, 0, 8); myRigidbody.useGravity = true; myRigidbody.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimationController: MonoBehaviour { public float waitTime = 5.0f; public float lerpSpeed = 1.0f; public float slerpSpeed = 1.0f; public float rotSpeed = 1.0f; public RightArmController rightArmController; public LeftArmController leftArmController; public RightHandController rightHandController; public LeftHandController leftHandController; public RightHandOrientationController rightHandOrientationController; public LeftHandOrientationController leftHandOrientationController; void Start() { rightArmController = GameObject.Find("RightArmTarget").GetComponent<RightArmController>(); leftArmController = GameObject.Find("RightArmTarget").GetComponent<LeftArmController>(); rightHandController = GameObject.Find("RightArmTarget").GetComponent<RightHandController>(); leftHandController = GameObject.Find("RightArmTarget").GetComponent<LeftHandController>(); rightHandOrientationController = GameObject.Find("RightArmTarget").GetComponent<RightHandOrientationController>(); leftHandOrientationController = GameObject.Find("RightArmTarget").GetComponent<LeftHandOrientationController>(); } private void Animate(UnitAnimation unit) { rightArmController.moveToTarget(unit.rightArmPosition, unit.rightArmPositionFinal, unit.rightHandTransition, lerpSpeed, slerpSpeed, waitTime); rightHandController.moveFinger(unit.rightHandConfigration, unit.rightHandConfigrationFinal, rotSpeed, waitTime); rightHandOrientationController.ReOrient(unit.rightHandOrientation, unit.rightHandOrientationFinal, rotSpeed, waitTime); } public void DisplayResult(FinalResult result) { //TO DO foreach (var anim in result.unit) { Animate(anim); StartCoroutine(Wait()); } } IEnumerator Wait() { yield return new WaitForSeconds(waitTime); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Cimletezes { class Program { static int huszas = 0, tizes = 0, otezres = 0, ketezres = 0, ezres = 0, otszaz = 0, ketszaz = 0, szaz = 0, otven = 0, husz = 0, tiz = 0, ot = 0, ketto = 0, egy = 0; static int penz = 0; static void Main(string[] args) { string[] szamok = File.ReadAllLines(@"szamok.txt"); for (int i = 0; i < szamok.Length; i++) { Szamol(int.Parse(szamok[i])); } Console.ReadKey(); } static void Szamol(int meh) { int szamol = meh; do { if (szamol - 20000 >= 0) { huszas++; szamol -= 20000; } else if (szamol - 10000 >= 0) { tizes++; szamol -= 10000; } else if (szamol - 5000 >= 0) { otezres++; szamol -= 5000; } else if (szamol - 2000 >= 0) { ketezres++; szamol -= 2000; } else if (szamol - 1000 >= 0) { ezres++; szamol -= 1000; } else if (szamol - 500 >= 0) { otszaz++; szamol -= 500; } else if (szamol - 200 >= 0) { ketszaz++; szamol -= 200; } else if (szamol - 100 >= 0) { szaz++; szamol -= 100; } else if (szamol - 50 >= 0) { otven++; szamol -= 50; } else if (szamol - 20 >= 0) { husz++; szamol -= 20; } else if (szamol - 10 >= 0) { tizes++; szamol -= 10; } else if (szamol - 5 >= 0) { ot++; szamol -= 5; } else if (szamol - 2 >= 0) { ketto++; szamol -= 2; } else if (szamol - 1 >= 0) { egy++; szamol -= 1; } } while (szamol != 0); kiir(meh); } static void kiir(int meh) { Console.WriteLine("Összeg: " + meh); Console.WriteLine("----------------------------"); Console.WriteLine("Húszezres: " + huszas); Console.WriteLine("Tízezres: " + tiz); Console.WriteLine("Ötezres: " + otezres); Console.WriteLine("Kétezres: " + ketezres); Console.WriteLine("Ezres: " + ezres); Console.WriteLine("Ötszázas: " + otszaz); Console.WriteLine("Kétszázas: " + ketszaz); Console.WriteLine("Százas: " + szaz); Console.WriteLine("Ötvenes: " + otven); Console.WriteLine("Huszas: " + husz); Console.WriteLine("Tizes: " + tizes); Console.WriteLine("Ötös: " + ot); Console.WriteLine("Kettes: " + ketto); Console.WriteLine("Egyes: " + egy); Console.WriteLine("----------------------------"); Nullaz(); } static void Nullaz() { huszas = 0; tizes = 0; otezres = 0; ketezres = 0; ezres = 0; otszaz = 0; ketszaz = 0; szaz = 0; otven = 0; husz = 0; tiz = 0; ot = 0; ketto = 0; egy = 0; } } }
using System; using Quark.Conditions; using Quark.Contexts; using Quark.Effects; using Quark.Utilities; using UnityEngine; namespace Quark.Buffs { public interface IBuff : IDisposable, Identifiable { /// <summary> /// Life ratio of this buff. /// </summary> float LifeRatio { get; } /// <summary> /// Total duration of this buff. /// </summary> float Duration { get; } /// <summary> /// This property stores how this buff should respond to stacking. /// </summary> StackBehavior StackBehavior { get; } /// <summary> /// This field stores the current stack count of this Buff. /// </summary> int CurrentStacks { get; set; } /// <summary> /// This field stores the maximum stack count of this Buff. /// </summary> int MaximumStacks { get; } /// <summary> /// This property determines whether this Buff should be hidden or not. /// </summary> bool Hidden { get; } /// <summary> /// This method determines whether this buff is ready for disposal. /// </summary> /// <returns>Whether this buff is ready for disposal.</returns> bool ShouldDispose(); /// <summary> /// Register proper events to the Messenger. /// This method should <b>not</b> contain any gameplay related logic /// Refer to the <c>OnPossess()</c> for gameplay logic on possession /// </summary> void Register(); /// <summary> /// Deregister pre registered events from the messenger. /// </summary> void Deregister(); /// <summary> /// This event handler is called right after the owning <c>BuffContainer</c> possesses this buff /// </summary> void OnPossess(); /// <summary> /// This event is raised when an existing Buff is attached again /// </summary> void OnStack(); /// <summary> /// Executes the finalization logic of this buff /// </summary> void OnDone(); /// <summary> /// Executes the termination logic of this buff /// </summary> void OnTerminate(); /// <summary> /// Handles the tick event /// </summary> void OnTick(); /// <summary> /// Begin the posession logic of this Buff /// </summary> /// <param name="possessor"></param> void Possess(Character possessor); /// <summary> /// Immediately terminates this Buff. /// Termination assures no other Tick will take place in this instance. /// </summary> void Terminate(); /// <summary> /// Resets the possession time of this Buff, practically resetting its lifetime /// </summary> void ResetBeginning(); } public interface IBuff<in T> : IBuff, IContextful<T> where T : IContext { } public class Buff<T> : IBuff<T>, ITagged where T : class, IContext { /// <summary> /// Name of this Buff. /// </summary> public virtual string Name { get { return GetType().Name; } } /// <summary> /// This field stores the interval of calling the Tick method in seconds. /// </summary> protected float Interval; public float Duration { get; set; } /// <summary> /// This flag determines whether the Tick method should be called every frame or not. /// </summary> protected bool Continuous; /// <summary> /// This flag determines whether this Buff ticks while its Possessor Character is suspended or not. /// </summary> protected bool TicksWhileSuspended; public bool Hidden { get; protected set; } /// <summary> /// This property stores the possessor of this Buff instance. /// </summary> protected Character Possessor { get; private set; } public int MaximumStacks { get; protected set; } public int CurrentStacks { get; set; } /// <summary> /// This field stores the stacking behavior of this Buff. /// See <see cref="Buffs.StackBehavior"/> /// </summary> public StackBehavior StackBehavior { get; set; } /// <summary> /// This flag stores whether this Buff is ready to be garbage collected /// </summary> public bool CleanedUp { get; protected set; } /// <summary> /// This ratio indicates the rate of its alive time to its total duration /// </summary> public float LifeRatio { get { return Duration > 0 ? Alive / Duration : 0; } } /// <summary> /// The time span in seconds where this Buff was running /// </summary> protected float Alive { get { return Time.timeSinceLevelLoad - _posessionTime; } } /// <summary> /// This variable is stored for calculating the alive time of the Buff instances /// </summary> private float _posessionTime; /// <summary> /// This variable is stored for checking whether the Tick method should be called or not in a given frame /// </summary> private float _lastTick; /// <summary> /// This flag stores whether this Buff got terminated in the last Tick /// </summary> private bool _terminated; public void Dispose() { Terminate(); } public Buff() { #if DEBUG Logger.GC("Buff::ctor"); #endif } ~Buff() { #if DEBUG Logger.GC("Buff::dtor"); #endif } public void Terminate() { _terminated = true; _lastTick = Mathf.Infinity; } public void ResetBeginning() { _posessionTime = Time.timeSinceLevelLoad; } /// <summary> /// This function controls the state of the buff for whether it should call the OnTick function in this frame or not and also it checks if it has completed its lifespan or not /// </summary> private void Tick() { /* * Tick logic: * * --- * Check for whether the custom OnTick logic should be executed or not: * * A buff should not tick if it is already cleaned up or terminated. * If the possessor is suspended and the buff is not explicitly flagged to tick, it should not tick. * --- * * --- * Check whether this buff should terminate or prematurely get to the done stage. * If either of the conditions met, finalize appropriately. * --- */ if (CleanedUp) return; if (_terminated) { Deregister(); OnTerminate(); return; } if (!Possessor.IsSuspended || TicksWhileSuspended) { if (Continuous) OnTick(); else if (Time.timeSinceLevelLoad - _lastTick >= Interval) { _lastTick = Time.timeSinceLevelLoad; OnTick(); } } ConditionCollection<T> collection = DoneConditions; bool isDone = false; collection.SetContext(Context); if (collection.Check(Possessor)) isDone = true; if ((LifeRatio >= 1 && !_terminated) || isDone) { Duration = 0.00000001f; Deregister(); OnDone(); return; } collection = TerminateConditions; collection.SetContext(Context); if (collection.Check(Possessor)) _terminated = true; } /// <summary> /// This method determines whether this Buff instance should get disposed in the current frame. /// </summary> /// <returns>Whether this buff should get disposed.</returns> public bool ShouldDispose() { return (LifeRatio >= 1 || _terminated) && CleanedUp; } public T Context { get; private set; } public virtual void SetContext(IContext context) { Context = (T)context; } public void Possess(Character possessor) { Possessor = possessor; _posessionTime = Time.timeSinceLevelLoad; _lastTick = Time.timeSinceLevelLoad; Register(); OnPossess(); } public virtual void Register() { Messenger.AddListener("Update", Tick); } public virtual void Deregister() { Messenger.RemoveListener("Update", Tick); } public virtual void OnPossess() { PossessEffects.Run(Possessor, Context); } public virtual void OnStack() { StackEffects.Run(Possessor, Context); } public virtual void OnTick() { TickEffects.Run(Possessor, Context); } public virtual void OnDone() { DoneEffects.Run(Possessor, Context); CleanedUp = true; } public virtual void OnTerminate() { Logger.Debug("Buff::OnTerminate"); CleanedUp = true; TerminateEffects.Run(Possessor, Context); } /// <summary> /// These effects are applied when this Buff is first possessed /// </summary> protected virtual EffectCollection<T> PossessEffects { get { return new EffectCollection<T>(); } } /// <summary> /// These effects are applied when another instance of this Buff is attached to the possessor /// </summary> protected virtual EffectCollection<T> StackEffects { get { return new EffectCollection<T>(); } } /// <summary> /// These effects are applied on every interval /// </summary> protected virtual EffectCollection<T> TickEffects { get { return new EffectCollection<T>(); } } /// <summary> /// These effects are applied when this Buff finishes its life time successfully /// </summary> protected virtual EffectCollection<T> DoneEffects { get { return new EffectCollection<T>(); } } /// <summary> /// These effeccts are applied when this Buff terminates (fails finish its life time) /// </summary> protected virtual EffectCollection<T> TerminateEffects { get { return new EffectCollection<T>(); } } /// <summary> /// These conditions are checked to determine whether this Buff should be done /// </summary> protected virtual ConditionCollection<T> DoneConditions { get { return new ConditionCollection<T> { new FalseCondition() }; } } /// <summary> /// These conditions are checked to determine whether this Buff should terminate /// </summary> protected virtual ConditionCollection<T> TerminateConditions { get { return new ConditionCollection<T> { new FalseCondition() }; } } #region Tagging /// <summary> /// Stores the static tags of this buff. /// </summary> public StaticTags Tags { get; protected set; } /// <summary> /// Checks whether this Buff is tagged with the given string or not. /// </summary> /// <param name="tag">Tag to check.</param> /// <returns>Whether the buff is tagged.</returns> public bool IsTagged(string tag) { return Tags.Has(tag); } #endregion /// <summary> /// Returns this Buffs identifier /// </summary> public string Identifier { get { return Name + "@" + Context.Identifier; } } } /// <summary> /// This enumeration dictates how a given Buff should respond in a stacking situation /// </summary> public enum StackBehavior { /// <summary> /// In the case of stacking, the Buff should reset its possession time. /// <see cref="Buff.ResetBeginning()"/> /// </summary> ResetBeginning = 1, /// <summary> /// In the case of stacking, the Buff should increase its stack count. /// </summary> IncreaseStacks = 2, /// <summary> /// In the case of stacking, the Buff shouldn't respond. /// </summary> Nothing = 4 } }
using System; using DevanshAssociate_API.DAL; using DevanshAssociate_API.Models; using System; using System.Collections.Generic; namespace DevanshAssociate_API.Services { public class CommonService: ICommonService { private CommonDal commonDataDAL; public CommonService() { commonDataDAL = new CommonDal(); } public List<LoanData> getAllLoanData() { return commonDataDAL.getAllLoanData(); } public List<BankData> getAllBankData() { return commonDataDAL.getAllBankData(); } } }
using System; using AutoMapper; using EQS.AccessControl.Application.Interfaces; using EQS.AccessControl.Application.ViewModels.Input; using EQS.AccessControl.Application.ViewModels.Output; using EQS.AccessControl.Application.ViewModels.Output.Base; using EQS.AccessControl.Domain.Entities; using EQS.AccessControl.Domain.Interfaces.Services; namespace EQS.AccessControl.Application.Services { public class LoginAppService : ILoginAppService { private readonly ILoginService _loginService; public LoginAppService(ILoginService loginService) { _loginService = loginService; } public void Dispose() { _loginService.Dispose(); GC.SuppressFinalize(this); } public ResponseModelBase<LoginOutput> Login(CredentialInput credential) { var credentialModel = Mapper.Map<Credential>(credential); var result = _loginService.Login(credentialModel); var personOutput = Mapper.Map<LoginOutput>(result); return new ResponseModelBase<LoginOutput>().OkResult(personOutput, result.Validations.ErrorMessages); } } }
namespace WebGallery.Data { public class HMessage { public const string ModeFolder = "Gallery from folder (F1)"; public static readonly string ModeLink = "Gallery from link (F2)\r\nSupport:"; public const string PathAccessFolder = "Browse for folder (F5)"; public const string PathAccessLink = "Access link (F5)"; public const string PathTextBox = "Focus here (F6)"; public const string OpenInternal = "Open gallery (F7)"; public const string OpenExternal = "Open gallery with default browser (F8)"; public const string Save = "Save (Ctrl + S)"; public const string ErrUrlInvalid = "Invalid URL format"; public const string ErrHostNotSupport = "Not support \"{0}\""; public const string ErrRemoved = "This gallery has been removed, and is unavailable."; } }
using Crossroads.Web.Common.MinistryPlatform; using FluentAssertions; using MinistryPlatform.Translation.Models.DTO; using MinistryPlatform.Translation.Repositories; using Moq; using NUnit.Framework; using System.Collections.Generic; namespace MinistryPlatform.Translation.Test.Repositories { public class EventRepositoryTest { private EventRepository _fixture; private Mock<IApiUserRepository> _apiUserRepository; private Mock<IMinistryPlatformRestRepository> _ministryPlatformRestRepository; private List<string> _eventGroupsColumns; [SetUp] public void SetUp() { _apiUserRepository = new Mock<IApiUserRepository>(MockBehavior.Strict); _ministryPlatformRestRepository = new Mock<IMinistryPlatformRestRepository>(MockBehavior.Strict); _eventGroupsColumns = new List<string> { "Event_Groups.[Event_Group_ID]", "Event_ID_Table.[Event_ID]", "Group_ID_Table.[Group_ID]", "Event_Room_ID_Table.[Event_Room_ID]", "Event_Room_ID_Table_Room_ID_Table.[Room_ID]", "Event_Room_ID_Table.[Capacity]", "Event_Room_ID_Table.[Label]", "Event_Room_ID_Table.[Allow_Checkin]", "Event_Room_ID_Table.[Volunteers]", "[dbo].crds_getEventParticipantStatusCount(Event_ID_Table.[Event_ID], Event_Room_ID_Table_Room_ID_Table.[Room_ID], 3) AS Signed_In", "[dbo].crds_getEventParticipantStatusCount(Event_ID_Table.[Event_ID], Event_Room_ID_Table_Room_ID_Table.[Room_ID], 4) AS Checked_In" }; _fixture = new EventRepository(_apiUserRepository.Object, _ministryPlatformRestRepository.Object); } [Test] public void TestGetEventGroupsForEvent() { const int eventId = 123; const string token = "tok 123"; var events = new List<MpEventGroupDto>(); _apiUserRepository.Setup(mocked => mocked.GetApiClientToken("CRDS.Service.SignCheckIn")).Returns(token); _ministryPlatformRestRepository.Setup(mocked => mocked.UsingAuthenticationToken(token)).Returns(_ministryPlatformRestRepository.Object); _ministryPlatformRestRepository.Setup(mocked => mocked.Search<MpEventGroupDto>($"Event_Groups.Event_ID IN ({eventId})", _eventGroupsColumns, null, false)).Returns(events); var result = _fixture.GetEventGroupsForEvent(eventId); _apiUserRepository.VerifyAll(); _ministryPlatformRestRepository.VerifyAll(); result.Should().BeSameAs(events); } [Test] public void TestImportEventSetup() { const string token = "tok123"; const int sourceEventId = 12345; const int destinationEventId = 67890; _apiUserRepository.Setup(m => m.GetApiClientToken("CRDS.Service.SignCheckIn")).Returns(token); _ministryPlatformRestRepository.Setup(mocked => mocked.UsingAuthenticationToken(token)).Returns(_ministryPlatformRestRepository.Object); _ministryPlatformRestRepository.Setup(mocked => mocked.PostStoredProc("api_crds_ImportEcheckEvent", It.IsAny<Dictionary<string, object>>())).Returns(1); _fixture.ImportEventSetup(destinationEventId, sourceEventId); _ministryPlatformRestRepository.VerifyAll(); _ministryPlatformRestRepository.Verify( mocked => mocked.PostStoredProc("api_crds_ImportEcheckEvent", It.Is<Dictionary<string, object>>(d => (int)d["@SourceEventId"] == sourceEventId && (int)d["@DestinationEventId"] == destinationEventId))); } [Test] public void TestResetEventSetup() { const string token = "tok123"; const int eventId = 12345; _apiUserRepository.Setup(m => m.GetApiClientToken("CRDS.Service.SignCheckIn")).Returns(token); _ministryPlatformRestRepository.Setup(mocked => mocked.UsingAuthenticationToken(token)).Returns(_ministryPlatformRestRepository.Object); _ministryPlatformRestRepository.Setup(mocked => mocked.PostStoredProc("api_crds_ResetEcheckEvent", It.IsAny<Dictionary<string, object>>())).Returns(1); _fixture.ResetEventSetup(eventId); _ministryPlatformRestRepository.VerifyAll(); _ministryPlatformRestRepository.Verify( mocked => mocked.PostStoredProc("api_crds_ResetEcheckEvent", It.Is<Dictionary<string, object>>(d => (int)d["@EventId"] == eventId))); } [Test] public void ItShouldGetEventAndSubevents() { // Arrange var token = "123abc"; var eventId = 1234567; List<MpEventDto> mpEventDtos = new List<MpEventDto>(); _apiUserRepository.Setup(m => m.GetApiClientToken("CRDS.Service.SignCheckIn")).Returns(token); _ministryPlatformRestRepository.Setup(mocked => mocked.UsingAuthenticationToken(token)).Returns(_ministryPlatformRestRepository.Object); _ministryPlatformRestRepository.Setup(mocked => mocked.Search<MpEventDto>(It.IsAny<string>(), It.IsAny<List<string>>(), null, false)).Returns(mpEventDtos); // Act _fixture.GetEventAndCheckinSubevents(eventId, false); // Assert _ministryPlatformRestRepository.VerifyAll(); } [Test] public void ShouldGetEventGroupsByGroupTypeId() { // Arrange var token = "123ABC"; var eventId = 1234567; var groupTypeId = 27; var mpEventGroups = new List<MpEventGroupDto> { new MpEventGroupDto { EventId = eventId, GroupId = 2233445 } }; _apiUserRepository.Setup(mocked => mocked.GetApiClientToken("CRDS.Service.SignCheckIn")).Returns(token); _ministryPlatformRestRepository.Setup(mocked => mocked.UsingAuthenticationToken(token)).Returns(_ministryPlatformRestRepository.Object); _ministryPlatformRestRepository.Setup(mocked => mocked.Search<MpEventGroupDto>( $"Event_Groups.Event_ID = {eventId} AND Group_ID_Table.[Group_Type_ID] = {groupTypeId}", _eventGroupsColumns, null, false)).Returns(mpEventGroups); // Act var result = _fixture.GetEventGroupsForEventByGroupTypeId(eventId, groupTypeId); // Assert Assert.AreEqual(1, result.Count); _ministryPlatformRestRepository.VerifyAll(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Pathfinding; public class StunZombie : MonoBehaviour { public AIDestinationSetter destinationSetter; public PlayerDetection playerDetection; public void Stunned(float stunTime) { StartCoroutine(StunnedZombieTimer(stunTime)); destinationSetter = gameObject.GetComponentInParent<AIDestinationSetter>(); destinationSetter.enabled = false; playerDetection = gameObject.GetComponentInParent<PlayerDetection>(); playerDetection.enabled = false; } IEnumerator StunnedZombieTimer(float time) { yield return new WaitForSeconds(time); destinationSetter.enabled = true; playerDetection.enabled = true; Destroy(gameObject.GetComponent<StunZombie>()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Pokemon_Internal_Blades_CSharp.Merchants { public class FenceMerchant : Merchant { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AxisEq; using AxisEq.CustomerDisplays; using AxisPosCore.EnvironmentObjects; using KartObjects; namespace AxisPosCore { /// <summary> /// Управление дисплеем покупателя /// </summary> public class CustomerDisplayEO:POSEnvironmentObject { AbstractCustomerDisplay customerDisplay; public CustomerDisplayEO(POSDevice device) { if (device != null) { //return null; //customerDisplay = AbstractCustomerDisplay.GetInstanсe("Software"); //customerDisplay.Open("COM1", "9600"); //} //else //{ customerDisplay = AbstractCustomerDisplay.GetInstanсe(device.Mnemonic); if (customerDisplay.Open(device.SerialPort, device.BaudRate.ToString()) != 0) customerDisplay=null; ///Инициализируем раскладку int cp = 0; if (int.TryParse(device.addParam, out cp)) customerDisplay.InitEncoding(cp); } ShowPosInactiveMessage(); } /// <summary> /// Показать добро пожаловать /// </summary> public void ShowWelcomeMessage() { if (customerDisplay != null) { customerDisplay.Clear(); customerDisplay.TextXy(1,1,Helper.CenterString("Добро пожаловать!",customerDisplay.Length)); } } /// <summary> /// Показать Спасибо за покупку /// </summary> public void ShowThxMessage() { if (customerDisplay != null) { customerDisplay.Clear(); customerDisplay.TextXy(1, 1, Helper.CenterString("Спасибо за покупку!", customerDisplay.Length)); } } /// <summary> /// Показать Cash Inactive /// </summary> public void ShowPosInactiveMessage() { if (customerDisplay != null) { customerDisplay.Clear(); customerDisplay.TextXy(1, 1, Helper.CenterString("Касса не работает.", customerDisplay.Length)); } } /// <summary> /// Показать текущую продажу /// </summary> /// <param name="receipt"></param> /// <param name="CurrPos"></param> public void ShowCurrentSale(Receipt receipt, int CurrPos) { if (customerDisplay != null) { ReceiptSpecRecord rgr = (from r in receipt.ReceiptSpecRecords where r.NumPos == CurrPos select r).SingleOrDefault(); if (rgr != null) { customerDisplay.Clear(); customerDisplay.TextXy(1, 1, Helper.GlueStrings(rgr.NameGood, rgr.PosSum, customerDisplay.Length)); customerDisplay.TextXy(1, 2, Helper.GlueStrings("ИТОГО", receipt.TotalSum, customerDisplay.Length)); } } } /// <summary> /// Показать текущую Сумму и сдачу /// </summary> /// <param name="receipt"></param> /// <param name="CurrPos"></param> public void ShowPayment(Receipt receipt) { if (customerDisplay != null) { customerDisplay.Clear(); customerDisplay.TextXy(1, 1, Helper.GlueStrings("ПОЛУЧЕНО", receipt.BuyerSum, customerDisplay.Length)); customerDisplay.TextXy(1, 2, Helper.GlueStrings("СДАЧА", receipt.Change, customerDisplay.Length)); } } public override void CloseEO() { if (customerDisplay!=null) customerDisplay.Close(); } } }
namespace P07PredicateForNames { using System; using System.Linq; public class PredicateForNames { public static void Main() { int length = int.Parse(Console.ReadLine()); Predicate<string> nameValidator = n => n.Length <= length; Console.ReadLine()? .Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries) .Where(n => nameValidator(n)) .ToList() .ForEach(Console.WriteLine); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using WpfTechTalk; namespace WpfTechTalkTest { [TestClass] public class StackAndPopTest { private StackAndPop model; [TestInitialize] public void setup() { model = new StackAndPop(); } [TestMethod] public void Push_CannotExecute_WhenBlockNameEmpty() { model.BlockName = null; Assert.IsFalse(model.PushA.CanExecute(null)); model.BlockName = ""; Assert.IsFalse(model.PushA.CanExecute(null)); model.BlockName = " "; Assert.IsFalse(model.PushA.CanExecute(null)); } [TestMethod] public void Push_AddsNametoStackA() { Push("aaa", "bbb", "ccc"); CollectionAssert.AreEquivalent(new[] {"aaa", "bbb", "ccc"}, model.StackA); } [TestMethod] public void Pop_CannotExecute_WhenStackA_Empty() { Assert.IsTrue(model.StackA.Count == 0); Assert.IsFalse(model.PopA.CanExecute(null)); } [TestMethod] public void Pop_PutsLastItem_OnStackB() { Push("aaa","bbb","ccc"); PopAndCheckStacks(new[] {"aaa", "bbb"}, new[] {"ccc"}); PopAndCheckStacks(new[] {"aaa"}, new[] {"ccc", "bbb"}); PopAndCheckStacks(new string[0], new[] {"ccc", "bbb", "aaa"}); } private void Push(params string[] blockNames) { foreach (var b in blockNames) { model.BlockName = b; model.PushA.Execute(null); } } private void PopAndCheckStacks(string[] expectStackA, string[] expectStackB) { model.PopA.Execute(null); CollectionAssert.AreEquivalent(expectStackA, model.StackA); CollectionAssert.AreEquivalent(expectStackB, model.StackB); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; namespace StrategyGame { public class Missile : IGameEffect { public Missile(Player enemy, Force enemyForce, double damage, bool isAccurate,Point from, Point to) { Enemy = enemy; EnemyForce = enemyForce; Damage = damage; IsAccurate = isAccurate; From = from; To = to; CurrentPosition = From; Direction = Math.Sign(To.X-From.X); } public double Damage { get; set; } public bool IsAccurate { get; set; } public Point From { get; set; } public Point To { get; set; } public Point CurrentPosition { get; set; } private int Direction { get; set; } public Force EnemyForce { get; set; } public Player Enemy { get; set; } public Texture2D MissileTexture2D { get; set; } public void Draw(SpriteBatch spriteBatch) { Texture2D rect = new Texture2D(TexturePack.graphicsDevice, 10, 10); Color[] data = new Color[10 * 10]; for (int i = 0; i < data.Length; ++i) data[i] = Color.Black; rect.SetData(data); Vector2 coor = new Vector2(CurrentPosition.X, CurrentPosition.Y); spriteBatch.Begin(); spriteBatch.Draw(rect,coor,Color.White); spriteBatch.End(); rect.Dispose(); } public bool Update(GameTime gameTime) { CurrentPosition = new Point((int)(CurrentPosition.X + Direction * 500 * gameTime.ElapsedGameTime.TotalSeconds),CurrentPosition.Y); if ((To.X - CurrentPosition.X)*Direction < 10) { EnemyForce.Defend(this); //if enemy force stays in base or is near - 100% splash on base if(EnemyForce.PosX<=100) { Enemy.PlayerBase.Defend(new MissileBase(Enemy, Damage, IsAccurate, From, To)); } return false; } return true; } } }
using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Caserraria.Projectiles { public class WarHornProj : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("War Horn"); //The English name of the projectile } public override void SetDefaults() { projectile.width = 500; projectile.height = 500; projectile.timeLeft = 1; projectile.penetrate = -1; projectile.friendly = true; projectile.hostile = false; projectile.tileCollide = false; projectile.ignoreWater = true; projectile.magic = true; projectile.aiStyle = -1; projectile.alpha = 255; } public override void AI() { for (int i = 0; i < 60; i++) { Dust d = Dust.NewDustPerfect(Main.player[projectile.owner].Center + Main.rand.NextVector2CircularEdge(250, 250), 143); Dust f = Dust.NewDustPerfect(Main.player[projectile.owner].Center + Main.rand.NextVector2CircularEdge(83, 83), 143); Dust g = Dust.NewDustPerfect(Main.player[projectile.owner].Center + Main.rand.NextVector2CircularEdge(166, 166), 143); d.noGravity = true; f.noGravity = true; g.noGravity = true; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MS0001.engine { class Inning { private readonly bool[] bases; public int Carreras { get; private set; } public int Outs { get; private set; } public bool IsActive { get { return Outs < 3; } } public bool HaveRunners { get { int c = bases.Count(b => b == true); return c > 0; } } public Inning() { bases = new bool[5]; Carreras = 0; Outs = 0; } public static Inning OneRun(bool isWinner) { var ini = new Inning(); if (isWinner) { ini = ini.Move(4); } for (int i = 0; i < 3; i++) { ini = ini.Out(); } return ini; } private Inning Copy() { var copy = new Inning { Carreras = Carreras, Outs = Outs }; bases.CopyTo(copy.bases, 0); return copy; } private Inning Move() { var copy = Copy(); for (int i = 4; i >= 1; i--) { copy.bases[i] = copy.bases[i - 1]; } copy.bases[0] = false; if (copy.bases[4]) { copy.Carreras++; copy.bases[4] = false; } return copy; } public Inning Move(int n) { var copy = Copy(); while(n > 0) { copy = copy.Move(); n--; } return copy; } private Inning Out() { var copy = Copy(); copy.bases[0] = false; copy.Outs++; return copy; } private Inning DoublePlay() { var copy = Out(); if (copy.bases[3]) copy.bases[3] = false; else if (copy.bases[2]) copy.bases[2] = false; else copy.bases[1] = false; return copy; } public Inning Out(int n) { if (n == 1) return Out(); if (n == 2) return DoublePlay(); return Copy(); } public Inning AddPlate() { var copy = Copy(); copy.bases[0] = true; return copy; } } }
using System; using System.Collections.Generic; using System.Text; namespace Cryptlex { public class ProductVersionFeatureFlag { public string Name; public bool Enabled; public string Data; public ProductVersionFeatureFlag(string name, bool enabled, string data) { this.Name = name; this.Enabled = enabled; this.Data = data; } } }
using System; namespace Lesson4._5 { class Program { static void Main(string[] args) { string str1 = " Предложение один Теперь предложение два Предложение три"; Console.WriteLine(Sentence(str1)); Console.ReadLine(); } static string Sentence(string sentence) { string str1 = string.Empty; for (int i = 0; i < sentence.Length; i++) { string tempSentence = string.Empty; if (sentence[i] != ' ' && sentence[i].ToString() == sentence[i].ToString().ToUpper()) { tempSentence += sentence[i]; i++; while (i < sentence.Length && (sentence[i] == ' ' || sentence[i].ToString() != sentence[i].ToString().ToUpper())) { tempSentence += sentence[i]; i++; } i--; str1 += tempSentence.TrimEnd() + ". "; } } return str1; } } }
// 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 Microsoft.Rest; using Newtonsoft.Json.Linq; namespace ApartmentApps.Client.Models { public partial class MaitenanceRequestModel { private string _comments; /// <summary> /// Optional. /// </summary> public string Comments { get { return this._comments; } set { this._comments = value; } } private bool? _emergency; /// <summary> /// Optional. /// </summary> public bool? Emergency { get { return this._emergency; } set { this._emergency = value; } } private IList<string> _images; /// <summary> /// Optional. /// </summary> public IList<string> Images { get { return this._images; } set { this._images = value; } } private int? _maitenanceRequestTypeId; /// <summary> /// Optional. /// </summary> public int? MaitenanceRequestTypeId { get { return this._maitenanceRequestTypeId; } set { this._maitenanceRequestTypeId = value; } } private bool? _permissionToEnter; /// <summary> /// Optional. /// </summary> public bool? PermissionToEnter { get { return this._permissionToEnter; } set { this._permissionToEnter = value; } } private int? _petStatus; /// <summary> /// Optional. /// </summary> public int? PetStatus { get { return this._petStatus; } set { this._petStatus = value; } } private int? _unitId; /// <summary> /// Optional. /// </summary> public int? UnitId { get { return this._unitId; } set { this._unitId = value; } } /// <summary> /// Initializes a new instance of the MaitenanceRequestModel class. /// </summary> public MaitenanceRequestModel() { this.Images = new LazyList<string>(); } /// <summary> /// Serialize the object /// </summary> /// <returns> /// Returns the json model for the type MaitenanceRequestModel /// </returns> public virtual JToken SerializeJson(JToken outputObject) { if (outputObject == null) { outputObject = new JObject(); } if (this.Comments != null) { outputObject["Comments"] = this.Comments; } if (this.Emergency != null) { outputObject["Emergency"] = this.Emergency.Value; } JArray imagesSequence = null; if (this.Images != null) { if (this.Images is ILazyCollection<string> == false || ((ILazyCollection<string>)this.Images).IsInitialized) { imagesSequence = new JArray(); outputObject["Images"] = imagesSequence; foreach (string imagesItem in this.Images) { if (imagesItem != null) { imagesSequence.Add(imagesItem); } } } } if (this.MaitenanceRequestTypeId != null) { outputObject["MaitenanceRequestTypeId"] = this.MaitenanceRequestTypeId.Value; } if (this.PermissionToEnter != null) { outputObject["PermissionToEnter"] = this.PermissionToEnter.Value; } if (this.PetStatus != null) { outputObject["PetStatus"] = this.PetStatus.Value; } if (this.UnitId != null) { outputObject["UnitId"] = this.UnitId.Value; } return outputObject; } } }
using System; using ApartmentApps.Data.Repository; using Newtonsoft.Json; namespace ApartmentApps.Api.NewFolder1 { public class EmailQueuer { private readonly IRepository<EmailQueueItem> _emailQueueItems; public EmailQueuer(IRepository<EmailQueueItem> emailQueueItems ) { _emailQueueItems = emailQueueItems; } public void QueueEmail<TData>(TData data, DateTime? scheduleDate = null) where TData : EmailData { if (data == null) throw new ArgumentNullException(nameof(data),"data can't be null"); _emailQueueItems.Add(new EmailQueueItem() { To = data.ToEmail, From = data.FromEmail, UserId = data.User.Id, Subject = data.Subject, ScheduleDate = scheduleDate, BodyData = JsonConvert.SerializeObject(data), BodyType = data.GetType().AssemblyQualifiedName }); _emailQueueItems.Save(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace tiny42sh { static class Execution { static private int execute_command ( string [] cmd ) { if (cmd.Length <= 0) { return 1; } else { int er = 0; Interpreter.Keyword kw = Interpreter.is_keyword(cmd[0]); switch (kw) { case Interpreter.Keyword.ls: er = execute_ls(cmd); break; case Interpreter.Keyword.cd: er = execute_cd(cmd); break; case Interpreter.Keyword.cat: er = execute_cat(cmd); break; case Interpreter.Keyword.touch: er = execute_touch(cmd); break; case Interpreter.Keyword.rm: er = execute_rm(cmd); break; case Interpreter.Keyword.rmdir: er = execute_rmdir(cmd); break; case Interpreter.Keyword.mkdir: er = execute_mkdir(cmd); break; case Interpreter.Keyword.pwd: er = execute_pwd(cmd); break; case Interpreter.Keyword.clear: er = execute_clear(cmd); break; case Interpreter.Keyword.whoami: er = execute_whoami(cmd); break; case Interpreter.Keyword.echo: er = execute_echo(cmd); break; case Interpreter.Keyword.tree: er = execute_tree(cmd); break; case Interpreter.Keyword.Empty: er = execute_empty(cmd); break; } return er; } } static public int execute_input ( string [][] input ) { int er = 0; for (int i = 0; i < input.GetLength(0); i++) { er = execute_command(input[i]); Console.WriteLine(""); } return er; } static private int show_content ( string entry ) { if (entry == " ") { string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory()); foreach (string str in filePaths) { string[] fullPath = Interpreter.splitstring(str, '\\'); Console.WriteLine(fullPath[fullPath.Length - 1]); } filePaths = Directory.GetDirectories(Directory.GetCurrentDirectory() + "\\" + entry); foreach (string str in filePaths) { string[] fullPath = Interpreter.splitstring(str, '\\'); Console.WriteLine(fullPath[fullPath.Length - 1]); } return 0; } if (Directory.Exists(Directory.GetCurrentDirectory() + "\\" + entry)) { string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\" + entry); foreach (string str in filePaths) { string[] fullPath = Interpreter.splitstring(str, '\\'); Console.WriteLine(fullPath[fullPath.Length - 1]); } filePaths = Directory.GetDirectories(Directory.GetCurrentDirectory() + "\\" + entry); foreach (string str in filePaths) { string[] fullPath = Interpreter.splitstring(str, '\\'); Console.WriteLine(fullPath[fullPath.Length - 1]); } return 0; } else if (File.Exists(Directory.GetCurrentDirectory() + "\\" + entry)) { Console.WriteLine(entry); return 0; } else { Console.WriteLine("ls: " + entry + ": No such file or directory"); return 1; } } static private int execute_ls ( string [] cmd ) { int er = 0; if(cmd.Length == 1) { show_content(" "); } for (int i = 1; i < cmd.Length; i++) { er = show_content(cmd[i]); } return er; } static private int execute_cd (string [] cmd) { if (cmd.Length != 2) { Console.WriteLine("cd: Invalid number of argument"); return 1; } else { if(cmd[1] == "..") { Directory.SetCurrentDirectory(".."); return 0; } else if (Directory.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[1])) { Directory.SetCurrentDirectory(cmd[1]); return 0; } else { Console.WriteLine("cd: " + cmd[1] + " : No such file or directory"); return 1; } } } static private int execute_clear(string [] cmd) { Console.Clear(); return 0; } static private int execute_cat(string[] cmd) { int er = 0; for(int i = 1; i < cmd.Length; i++) { if (File.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[i])) { try { FileStream read = File.OpenRead(Directory.GetCurrentDirectory() + "\\" + cmd[i]); read.Seek(0, SeekOrigin.Begin); int nextByte; while ((nextByte = read.ReadByte()) > 0) { Console.Write(Convert.ToChar(nextByte)); } read.Close(); Console.WriteLine(); Console.WriteLine("------------------------------"); er = 0; } catch { Console.WriteLine("echo: An error occured during the process"); er = 1; } } else if (Directory.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[i])) { Console.WriteLine("cat : " + cmd[i] + " : Is not a file"); er = 1; } else { Console.WriteLine("cat : " + cmd[i] + " : No such file or directory"); er = 1; } } return er; } static private int execute_touch(string[] cmd) { int er = 0; for (int i = 1; i < cmd.Length; i++) { if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[i])) { try { FileStream fs = File.Create(Directory.GetCurrentDirectory() + "\\" + cmd[i]); fs.Close(); Console.WriteLine(cmd[i] + " created"); er = 0; } catch { Console.WriteLine("touch: An error occured during the process"); } er = 1; } else { FileInfo fi = new FileInfo(Directory.GetCurrentDirectory() + "\\" + cmd[i]); fi.LastAccessTime = DateTime.Now; } } return er; } static private int execute_pwd(string[] cmd) { int er = 0; if (cmd.Length == 1) { if (Directory.GetCurrentDirectory().Length > 4) { string[] splited = Interpreter.splitstring(Directory.GetCurrentDirectory(), '\\'); string minus = ""; for (int i = 0; i < 2; i++) minus += splited[i] + "\\"; minus += " [...] \\" + splited[splited.Length - 2] + "\\"; minus += splited[splited.Length - 1]; Console.WriteLine(minus); er = 0; } else { Console.WriteLine(Directory.GetCurrentDirectory()); er = 1; } } else { Console.WriteLine("pwd : Invalid number of arguments"); er = 1; } return er; } static private int execute_echo(string[] cmd) { int er = 0; if (cmd.Length != 3) { Console.WriteLine("echo : Invalid number of arguments"); er = 1; } else { if (File.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[2])) { try { StreamWriter sw = new StreamWriter(Directory.GetCurrentDirectory() + "\\" + cmd[2]); sw.WriteLine(cmd[1]); sw.Close(); er = 0; } catch { Console.WriteLine("echo: An error occured during the process"); er = 1; } } else { Console.WriteLine("echo: No such file"); er = 1; } } return er; } static private int execute_rm(string[] cmd) { int er = 0; if(cmd.Length <= 1) { Console.WriteLine("rm : Invalid number of arguments"); er = 1; } else { for (int i = 1; i < cmd.Length; i++) { if(cmd[i] == "*") { string[] table = Directory.GetFiles(Directory.GetCurrentDirectory()); foreach(string t in table) { try { File.Delete(Directory.GetCurrentDirectory() + "\\" + cmd[i]); er = 0; } catch { Console.WriteLine("rm: invalid rights"); er = 1; } } } else if (File.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[i])) { try { File.Delete(Directory.GetCurrentDirectory() + "\\" + cmd[i]); er = 0; } catch { Console.WriteLine("rm: invalid rights"); er = 1; } } else if (Directory.Exists(cmd[i])) { Console.WriteLine("rm : " + cmd[i] +" is a directory"); er = 1; } else { Console.WriteLine("rm : " + cmd[i] + " : No such file or directory"); er = 1; } } } return er; } static private int execute_rmdir(string[] cmd) { int er = 0; if (cmd.Length <= 1) { Console.WriteLine("rmdir : Invalid number of arguments"); er = 1; } else { for (int i = 1; i < cmd.Length; i++) { if (Directory.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[i])) { string[] directory = Directory.GetDirectories(Directory.GetCurrentDirectory() + "\\" + cmd[i]); string[] files = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\" + cmd[i]); if (directory.Length == 0 && files.Length == 0) { try { Directory.Delete(Directory.GetCurrentDirectory() + "\\" + cmd[i]); er = 0; } catch { Console.WriteLine("rmdir: An error occured during the process"); er = 1; } } else { Console.WriteLine("rmdir : " + cmd[i] + " : is not an empty directory"); er = 1; } } else { Console.WriteLine("rm : " + cmd[i] + " : No such file or directory"); er = 1; } } } return er; } static private int execute_mkdir(string[] cmd) { int er = 0; if (cmd.Length <= 1) { Console.WriteLine("mkdir : Invalid number of arguments"); er = 1; } else { for(int i = 1; i < cmd.Length; i++) { if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[i])) { if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + cmd[i])) { try { Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\" + cmd[i]); er = 0; } catch { Console.WriteLine("mkdir: An error occured during the process"); er = 1; } } else { Console.WriteLine("mkdir : " + cmd[i] +" : File already exists"); er = 1; } } else { Console.WriteLine("mkdir : " + cmd[i] +" : Directory already exists"); er = 1; } } } return er; } static private int execute_whoami(string[] cmd) { Console.WriteLine("ADC 2017 -- MeltedPenguin && Eliams <3"); return 0; } static private int execute_tree(string[] cmd) { if(cmd.Length > 1) { Console.WriteLine("tree: invalid number of arguments"); return 1; } else { show_tree(Directory.GetCurrentDirectory(), ""); } return 0; } static private int show_tree(string path, string decalage) { string[] filePaths = Directory.GetFiles(path); foreach (string str in filePaths) { string[] fullPath = Interpreter.splitstring(str, '\\'); Console.WriteLine(decalage + "│__" + fullPath[fullPath.Length - 1]); } filePaths = Directory.GetDirectories(path); foreach (string str in filePaths) { string[] fullPath = Interpreter.splitstring(str, '\\'); Console.WriteLine(decalage + "│__" + fullPath[fullPath.Length - 1]); string dec = decalage + " "; show_tree(str, dec); } return 0; } static private int execute_empty(string[] cmd) { if(cmd.Length > 0) { Console.WriteLine(cmd[0] + ": Unknown command"); } return 0; } } }
using UnityEngine; using System.Collections; public class DropThroughOnDown : MonoBehaviour { private bool playerOnObject = true; // Platform should initially be 'solid' void Update () { if (playerOnObject) GetComponent<Collider2D>().isTrigger = Input.GetAxis("Vertical") < 0; } void OnTriggerEnter2D (Collider2D collider) { if (collider.tag == GameConstants.PlayerTag) playerOnObject = true; } void OnTriggerExit2D (Collider2D collider) { if (collider.tag == GameConstants.PlayerTag) playerOnObject = false; } }
using Library.Interfaces; using Library.Model; using Library.Serializers; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LibraryTest { [TestClass] public class OwnSerializerTests { private static readonly string FILENAME = "DataContextSerializedData.txt"; [TestMethod] public void SameDataAfterDeserializing() { IDataFiller filler = new DataFillerImpl(); DataRepository dataRepo = new DataRepository(filler); dataRepo.setDataContext(); var dataCtxOriginal = dataRepo.getDataContext(); OwnSerializer.Serialize(dataCtxOriginal, FILENAME); var dataCtxDeserialized = OwnSerializer.Deserialize(FILENAME); Assert.AreEqual(dataCtxOriginal.EventsCatalog[1].Person.LastName, dataCtxDeserialized.EventsCatalog[1].Person.LastName); } [TestMethod] public void SerializeReferenceTest() { IDataFiller filler = new DataFillerImpl(); DataRepository repo = new DataRepository(filler); repo.setDataContext(); OwnSerializer.Serialize(repo.getDataContext(), FILENAME); var originalDataCtx = repo.getDataContext(); Assert.IsTrue(originalDataCtx.StatesCatalog[0].Item == originalDataCtx.ItemsCatalog[originalDataCtx.StatesCatalog[0].Item.Id]); var deserializedDataCtx = OwnSerializer.Deserialize(FILENAME); Assert.IsTrue(deserializedDataCtx.StatesCatalog[0].Item == deserializedDataCtx.ItemsCatalog[originalDataCtx.StatesCatalog[0].Item.Id]); } } }
// <copyright file="ActiveDirectoryDeleteResponse.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> namespace SmartLibrary.Models { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// This class is used to Get Active Directory Delete response. /// </summary> /// <CreatedBy>Bhargav Aboti</CreatedBy> /// <CreatedDate>26-Dec-2018</CreatedDate> public class ActiveDirectoryDeleteResponse : ActiveDirectoryResponseBase { /// <summary> /// Gets or sets the Data list. /// </summary> public virtual ActiveDirectoryDeleteDataResponse Data { get; set; } } }
using Alabo.Domains.Services; using System.Collections.Generic; namespace Alabo.Framework.Core.Admins.Services { /// <summary> /// 数据库操作服务 /// </summary> public interface ICatalogService : IService { /// <summary> /// 数据库维护脚本 /// </summary> void UpdateDatabase(); /// <summary> /// 获取所有的Sql表实体 /// </summary> List<string> GetSqlTable(); } }
using PhobiaX.Assets; using PhobiaX.Graphics; using PhobiaX.Physics; using PhobiaX.SDL2; using System; using System.Collections.Generic; using System.Text; namespace PhobiaX.Game.GameObjects { public class PlayerGameObject : AnimatedGameObject { private static int playerGameObjectCount = 0; public int PlayerNumber { get; } = playerGameObjectCount; public int Score { get; set; } = 0; public int Life { get; set; } = 100; public PlayerGameObject(RenderablePeriodicAnimation renderablePeriodicAnimation, ICollidableObject collidableObject) : base(renderablePeriodicAnimation, collidableObject) { playerGameObjectCount = (playerGameObjectCount + 1) % 2; } public override void Hit() { if (Life > 0) { Life--; } if (Life == 0) { base.Hit(); } } } }
using System; using System.Collections.Generic; using System.Text; namespace BenefitDeduction.EmployeeBenefitDeduction { public abstract class BenefitDeductionDetailBase : IBenefitDeductionDetail { public decimal AnnualTotalCostGross { get; internal set; } public decimal AnnualTotalCostNet { get; internal set; } public decimal AnnualSalaryAjustment { get; internal set; } public decimal PerPayPeriodTotalCostGross { get; internal set; } public decimal PerPayPeriodTotalCostNet { get; internal set; } public decimal PerPayPeriodSalaryAjustment { get; internal set; } public decimal PerPayPeriodBenefitAjustment { get; internal set; } public List<IBenefitDeductionItem> BenefitDeductionItems { get; internal set; } = new List<IBenefitDeductionItem>(); public decimal EmployeeSalary { get; internal set; } public decimal EmployeeSalaryPerPayPeriod { get; internal set; } } }
namespace MvcApp.Web.Views.Home { using System.IO; using System.Text; using SimpleMVC.Interfaces.Generic; using ViewModels; public class Signed : IRenderable<SignedViewModel> { public SignedViewModel Model { get; set; } public string Render() { StringBuilder builder = new StringBuilder(); builder.Append(File.ReadAllText(Constants.ContentPath)); return builder.ToString(); } } }
using PagedList; using ShopTT.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ShopTT.Controllers { public class ProductsController : Controller { ShopTTEntities _dbContext = new ShopTTEntities(); // GET: SanPham public ActionResult Index(int? page) { //so sach tren trang int pageSize = 8; //so trang int pageNumber = (page ?? 1); var LstAllSanPham = _dbContext.Products.OrderByDescending(x => x.proPrice).ToList(); var LsAllSanPham = _dbContext.Products.OrderByDescending(x => x.proPrice).ToPagedList(pageNumber, pageSize); if (LsAllSanPham.Count > 0) { ViewBag.message = "Tổng sản phẩm: " + LsAllSanPham.Count.ToString(); } return View(LsAllSanPham); } public ActionResult DetailProducts(string idpro) { var detailsanpham = _dbContext.Products.SingleOrDefault(x => x.proID == idpro); if (detailsanpham == null) { ViewBag.message = "Sản phẩm chưa có thông tin chi tiết...."; return null; } return View(detailsanpham); } public ActionResult ProductbyType(int idproType) { //check topic exit? var lsanpham = _dbContext.ProductTypes.FirstOrDefault(x => x.typeID == idproType); if (lsanpham == null) { Response.StatusCode = 404; return null; } var lstloaiSP = _dbContext.Products.Where(x => x.typeID == idproType).OrderByDescending(x => x.proPrice).ToList(); if (lstloaiSP.Count > 0) { ViewBag.message = "Tổng sản phẩm: " + lstloaiSP.Count.ToString(); } if (lstloaiSP.Count == 0) { ViewBag.message = "Sản phẩm hiện chưa mở bán"; } return View(lstloaiSP); } public ActionResult Productbyproduce(int idpdc) { //check topic exit? var lsanpham = _dbContext.Producers.FirstOrDefault(x => x.pdcID == idpdc); if (lsanpham == null) { Response.StatusCode = 404; return null; } var lstnhasx = _dbContext.Products.Where(x => x.pdcID == idpdc).OrderByDescending(x => x.proPrice).ToList(); if (lstnhasx.Count > 0) { ViewBag.message = "Tổng sản phẩm: " + lstnhasx.Count.ToString(); } if (lstnhasx.Count == 0) { ViewBag.message = "Sản phẩm hiện chưa mở bán"; } return View(lstnhasx); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using System.Windows.Media; using System.Windows.Shapes; namespace ManyFoodZ { [Serializable] public class ArenaPosition { public double X { set; get; } public double Y { set; get; } public double Z { set; get; } public double V { set; get; } public double H { set; get; } public double L { set; get; } public double R { set; get; } public bool outOfRange = false; public bool tiltBack = false; public ArenaPosition(double x, double y, double z) { X = x; Y = y; Z = z; double a = MainWindow.MWInstance.allSets.basicParas.ArmLength; double l = MainWindow.MWInstance.allSets.basicParas.railLength * 100; V = Math.Asin(Z / a); H = Math.Asin(Y / a / Math.Cos(V)); L = 100.0 * (X - a * Math.Cos(H) * Math.Cos(V)); if (Z > a || L > l || Y < 0 || Z < 0) outOfRange = true; else if (L < 0) { H = Math.PI - H; L = 100.0 * (X - a * Math.Cos(H) * Math.Cos(V)); if (L < 0 || L > l) outOfRange = true; else tiltBack = true; } V = V / Math.PI * 180; H = H / Math.PI * 180; if (H > 90) R = 0; else if (H > 45) R = 45; else R = H; } public string Arena2RawCmd() { string cmdL = Convert.ToString(Math.Round(L, 3)); string cmdH = Convert.ToString(Math.Round(H, 3)); string cmdV = Convert.ToString(Math.Round(V, 3)); string cmdR = Convert.ToString(Math.Round(R, 3)); return cmdL + "l" + cmdH + "h" + cmdV + "v" + cmdR + "r" + "e"; } public bool Equals(ArenaPosition ap) { return X == ap.X && Y == ap.Y && Z == ap.Z; } } [Serializable] public class RawPosition { public double L; public double H; public double V; public bool outOfRange = false; public bool tiltback = false; public RawPosition(double l, double h, double v) { L = l; H = h; V = v; double length = MainWindow.MWInstance.allSets.basicParas.railLength * 100; if (L > length || L < 0 || H < 0 || H > 180 || V < 0 || V > 90) outOfRange = true; if (H > 90) tiltback = true; } public ArenaPosition Raw2Arena() { double h = H / 180.0 * Math.PI; double v = V / 180.0 * Math.PI; double a = (double)MainWindow.MWInstance.allSets.basicParas.ArmLength; double X = L / 100 + a * Math.Cos(h) * Math.Cos(v); double Y = a * Math.Sin(h) * Math.Cos(v); double Z = a * Math.Sin(v); return new ArenaPosition(X, Y, Z); } } class RandomPosition { int lowEdge; int highEdge; public ArenaPosition ap; public RandomPosition(LibPos lp, int accumulator) { lowEdge = accumulator; highEdge = lp.chance + accumulator; ap = new ArenaPosition(lp.X, lp.Y, lp.Z); } public bool LieWithin(double rand) { if (rand >= lowEdge && rand < highEdge) return true; else return false; } } class SeqPosition { public ArenaPosition ap; public int repeat; public SeqPosition(LibPos lp) { ap = new ArenaPosition(lp.X, lp.Y, lp.Z); repeat = lp.repeat; } } class Converter { public static Point ArenaUI2Arena(Point pt) { MainWindow win = MainWindow.MWInstance; double a = win.allSets.basicParas.ArmLength; double l = win.allSets.basicParas.railLength; double x = l + a - pt.Y / win.ArenaBoarderHeight * (l + 2 * a); double y = pt.X / win.ArenaBoarderWidth * a; return new Point(x, y); } public static Point Arena2ArenaUI(ArenaPosition ap) { MainWindow win = MainWindow.MWInstance; double a = win.allSets.basicParas.ArmLength; double l = win.allSets.basicParas.railLength; double top = (1 - (ap.X + a) / (l + 2 * a)) * win.ArenaBoarderHeight; double left = ap.Y / a * win.ArenaBoarderWidth; return new Point(top, left); } } // Open Folder or Open File Dialog class OpenF { public static string FolderBrowseDialog() { FolderBrowserDialog b = new FolderBrowserDialog(); DialogResult result = b.ShowDialog(); if (result == System.Windows.Forms.DialogResult.Cancel) { return ""; } return b.SelectedPath.Trim(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EasyDev.Taobao { public class FieldAttribute : Attribute { public string FieldName { get; set; } public FieldAttribute() { } public FieldAttribute(string _fieldName) { FieldName = _fieldName; } } }
using BP12.Collections; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DChild.Gameplay.Objects { public class PingPongSpike : MonoBehaviour { [SerializeField] private GameObject m_obstacles; [SerializeField] [Range(0, 7)] private float m_speed; [SerializeField] private float m_Distance; private Vector3 m_initialPos; public enum movementType { horizontal, vertical, } [SerializeField] private movementType m_movement; private void Update() { var m_obstaclePos = m_obstacles.transform.localPosition; if (m_movement == movementType.horizontal) { m_obstaclePos = new Vector3(Mathf.PingPong(Time.time * m_speed, m_Distance), m_obstaclePos.y, m_obstaclePos.z); } else if (m_movement == movementType.vertical) { m_obstaclePos = new Vector3(m_obstaclePos.x, Mathf.PingPong(Time.time * m_speed, m_Distance), m_obstaclePos.z); } m_obstacles.transform.localPosition = m_obstaclePos; } } }
// <copyright file="ActiveDirectoryController.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> namespace SmartLibrary.Admin.Controllers { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using System.Web.Mvc; using Infrastructure; using Infrastructure.Code; using Newtonsoft.Json; using Pages; using Resources; using RestSharp; using Services; using SmartLibrary.Models; /// <summary> /// Active Directory Controller /// </summary> public class ActiveDirectoryController : Controller { #region Class variables private CommonBL commonBL; private UserDataBL userDataBL; #endregion Class Variables /// <summary> /// Initializes a new instance of the <see cref="ActiveDirectoryController"/> class. /// AccountController. /// </summary> public ActiveDirectoryController() { this.commonBL = new CommonBL(); this.userDataBL = new UserDataBL(); } /// <summary> /// Active Directory Login. /// </summary> /// <returns>Login Page</returns> /// <param name="model">Return Url.</param> public ActionResult ActiveDirectoryLogin(Login model) { return this.View(model); } /// <summary> /// Staff Login. /// </summary> /// <param name="returnUrl">Return Url.</param> /// <returns>Staff Login Page</returns> [ActionName(Actions.StaffLogin)] public ActionResult StaffLogin(string returnUrl) { Login loginModel = new Login(); if (this.Request.Cookies["SmartLibraryAD"] != null) { System.Web.HttpCookie cookie = this.Request.Cookies["SmartLibraryAD"]; loginModel.RememberMe = ConvertTo.ToBoolean(cookie.Values.Get("LoginIsRemember")); if (loginModel.RememberMe) { if (cookie.Values.Get("LoginEmail") != null) { loginModel.Email = cookie.Values.Get("LoginEmail"); } if (cookie.Values.Get("LoginPassword") != null) { loginModel.Password = EncryptionDecryption.DecryptByTripleDES(cookie.Values.Get("LoginPassword")); } } } loginModel.ReturnUrl = returnUrl; return this.View(Views.StaffLogin, loginModel); } /// <summary> /// Use to index. /// </summary> /// <param name="model">model value.</param> /// <returns>return action result.</returns> [HttpPost] [ValidateAntiForgeryToken] [ActionName(Actions.StaffLogin)] public ActionResult StaffLogin(Login model) { if (this.ModelState.IsValid) { if (ProjectConfiguration.IsActiveDirectory) { var adResponse = this.commonBL.ActiveDirectoryResponse(model); if (adResponse == null || adResponse.Status?.ToLower() == "failure" || !string.IsNullOrEmpty(adResponse.Error_description) || !string.IsNullOrEmpty(adResponse.Error)) { this.AddToastMessage(Resources.General.Error, Account.InvalidCredenitals, Infrastructure.SystemEnumList.MessageBoxType.Error); model.Password = EncryptionDecryption.DecryptByTripleDES(model.Password); return this.View(Views.StaffLogin, model); } if (string.IsNullOrEmpty(adResponse.UserName) && string.IsNullOrEmpty(adResponse.Email)) { this.AddToastMessage(Resources.General.Error, Messages.EmailNotExistInAD, Infrastructure.SystemEnumList.MessageBoxType.Error); model.Password = EncryptionDecryption.DecryptByTripleDES(model.Password); return this.View(Views.StaffLogin, model); } Login userLogin = this.commonBL.GetUserLoginwithEmail(adResponse.Email); if (userLogin != null && userLogin.Userdata != null) { if (userLogin.Userdata.Active.ToBoolean() == false) { this.AddToastMessage(Resources.General.Error, Account.InactiveUserMessage, Infrastructure.SystemEnumList.MessageBoxType.Error); return this.View(Views.StaffLogin, model); } if (model.RememberMe) { System.Web.HttpCookie cookie = new System.Web.HttpCookie("SmartLibraryAD"); cookie.Values.Add("LoginEmail", model.Email); cookie.Values.Add("LoginPassword", EncryptionDecryption.EncryptByTripleDES(model.Password)); cookie.Values.Add("LoginIsRemember", Convert.ToString(model.RememberMe)); cookie.Expires = DateTime.Now.AddMonths(1); cookie.HttpOnly = true; this.Response.Cookies.Add(cookie); } else { this.Response.Cookies["SmartLibraryAD"].Expires = DateTime.Now.AddMonths(-1); } ProjectSession.AdminPortalLanguageId = userLogin.Userdata.Language ?? SystemEnumList.Language.English.GetHashCode(); ProjectSession.UserId = userLogin.Userdata.Id; ProjectSession.UserRole = userLogin.Userdata.RoleId; ProjectSession.UserRoleRights = this.commonBL.GetPageAccessBasedOnUserRole(userLogin.Userdata.RoleId); ProjectSession.SuperAdmin = userLogin.Userdata.SuperAdmin ?? false; ProjectSession.LoginType = SystemEnumList.LoginType.Staff.GetHashCode(); if (!string.IsNullOrEmpty(model.ReturnUrl)) { if (this.Url.IsLocalUrl(model.ReturnUrl)) { return this.Redirect(model.ReturnUrl); } } return this.RedirectToAction(Actions.BookGrid, Controllers.Book); } else { this.AddToastMessage(Resources.General.Error, Account.InvalidCredenitals, Infrastructure.SystemEnumList.MessageBoxType.Error); model.Password = EncryptionDecryption.DecryptByTripleDES(model.Password); return this.View(Views.StaffLogin, model); } } else { model.Password = EncryptionDecryption.EncryptByTripleDES(model.Password); Login response = this.commonBL.GetUserLogin(model); if (response != null && response.Userdata != null) { if (response.Userdata.Active.ToBoolean() == false) { this.AddToastMessage(Resources.General.Error, Account.InactiveUserMessage, Infrastructure.SystemEnumList.MessageBoxType.Error); return this.View(Views.StaffLogin, model); } if (model.RememberMe) { System.Web.HttpCookie cookie = new System.Web.HttpCookie("SmartLibraryAD"); cookie.Values.Add("LoginEmail", model.Email); cookie.Values.Add("LoginPassword", EncryptionDecryption.EncryptByTripleDES(model.Password)); cookie.Values.Add("LoginIsRemember", Convert.ToString(model.RememberMe)); cookie.Expires = DateTime.Now.AddMonths(1); cookie.HttpOnly = true; this.Response.Cookies.Add(cookie); } else { this.Response.Cookies["SmartLibraryAD"].Expires = DateTime.Now.AddMonths(-1); } ProjectSession.AdminPortalLanguageId = response.Userdata.Language ?? SystemEnumList.Language.English.GetHashCode(); ProjectSession.UserId = response.Userdata.Id; ProjectSession.UserRole = response.Userdata.RoleId; ProjectSession.UserRoleRights = this.commonBL.GetPageAccessBasedOnUserRole(response.Userdata.RoleId); ProjectSession.SuperAdmin = response.Userdata.SuperAdmin ?? false; if (!string.IsNullOrEmpty(model.ReturnUrl)) { if (this.Url.IsLocalUrl(model.ReturnUrl)) { return this.Redirect(model.ReturnUrl); } } return this.RedirectToAction(Actions.BookGrid, Controllers.Book); } else { this.AddToastMessage(Resources.General.Error, Account.InvalidCredenitals, Infrastructure.SystemEnumList.MessageBoxType.Error); model.Password = EncryptionDecryption.DecryptByTripleDES(model.Password); return this.View(Views.StaffLogin, model); } } } else if (string.IsNullOrEmpty(model.Email)) { this.ViewBag.ErrorMessage = SmartLibrary.Resources.Messages.RequiredFieldMessage.SetArguments(SmartLibrary.Resources.Account.InvalidEmailAddress); } else if (string.IsNullOrEmpty(model.Password)) { this.ViewBag.ErrorMessage = Messages.RequiredFieldMessage.SetArguments(SmartLibrary.Resources.Account.Password); } return this.View(Views.StaffLogin, model); } /// <summary> /// Staff Direct Login. /// </summary> /// <param name="returnUrl">Return Url.</param> /// <param name="userName">userName.</param> /// <returns>return action result.</returns> [HttpPost] [ValidateAntiForgeryToken] [ActionName(Actions.StaffDirectLogin)] public ActionResult StaffDirectLogin(string returnUrl, string userName) { var adResponse = this.commonBL.ActiveDirectoryDirectLogin(userName.ToString()); if (adResponse == null || adResponse.Status?.ToLower() == "failure" || !string.IsNullOrEmpty(adResponse.Error_description) || !string.IsNullOrEmpty(adResponse.Error)) { this.AddToastMessage(Resources.General.Error, string.IsNullOrEmpty(adResponse.Message) ? Account.InvalidCredenitals : adResponse.Message, Infrastructure.SystemEnumList.MessageBoxType.Error); return this.RedirectToAction(Actions.StaffLogin); } if (string.IsNullOrEmpty(adResponse.UserName) && string.IsNullOrEmpty(adResponse.Email)) { this.AddToastMessage(Resources.General.Error, Messages.EmailNotExistInAD, Infrastructure.SystemEnumList.MessageBoxType.Error); return this.RedirectToAction(Actions.StaffLogin); } Login userLogin = this.commonBL.GetUserLoginwithEmail(adResponse.Email); if (userLogin != null && userLogin.Userdata != null) { if (userLogin.Userdata.Active.ToBoolean() == false) { this.AddToastMessage(Resources.General.Error, Account.InactiveUserMessage, Infrastructure.SystemEnumList.MessageBoxType.Error); return this.RedirectToAction(Actions.StaffLogin); } ProjectSession.AdminPortalLanguageId = userLogin.Userdata.Language ?? SystemEnumList.Language.English.GetHashCode(); ProjectSession.UserId = userLogin.Userdata.Id; ProjectSession.UserRole = userLogin.Userdata.RoleId; ProjectSession.UserRoleRights = this.commonBL.GetPageAccessBasedOnUserRole(userLogin.Userdata.RoleId); ProjectSession.SuperAdmin = userLogin.Userdata.SuperAdmin ?? false; ProjectSession.LoginType = SystemEnumList.LoginType.Staff.GetHashCode(); if (!string.IsNullOrEmpty(returnUrl)) { if (this.Url.IsLocalUrl(returnUrl)) { return this.Redirect(returnUrl); } } return this.RedirectToAction(Actions.BookGrid, Controllers.Book); } else { this.AddToastMessage(Resources.General.Error, Account.InvalidCredenitals, Infrastructure.SystemEnumList.MessageBoxType.Error); return this.View(Views.StaffLogin); } return this.RedirectToAction(Actions.ActiveDirectoryLogin); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using AutoMapper; using DashBoard.Business.DTOs.Domains; using DashBoard.Business.Services; using DashBoard.Data.Data; using DashBoard.Data.Entities; using DashBoard.Data.Enums; using DashBoard.Web.Helpers; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.EntityFrameworkCore; using Microsoft.VisualBasic; using Xunit; namespace Services.Tests { //I recommend checking helper class at the bottom and get familiar with the seed data we use to populate databases in tests. When you know what data we have, these tests are self explanatory. public class TestDomainService { [Fact] public void TestGetById() { //Arrange var options = new DbContextOptionsBuilder<DataContext>() //instead of mocking we use inMemoryDatabase. .UseInMemoryDatabase(databaseName: "TestGetById") .Options; var config = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfile>()); var mapper = config.CreateMapper(); // according to some people this is better than mocking automapper. //Act using (var context = new DataContext(options)) { context.Domains.AddRange(SeedFakeData.SeedEntitiesDomainModels()); context.Users.AddRange(SeedFakeData.SeedEntitiesUsersModels()); context.SaveChanges(); } using (var context = new DataContext(options)) { var service = new DomainService(context, mapper); var okResult = service.GetById(1, "1"); var badResult = service.GetById(10000, "1"); //Assert Assert.Null(badResult); Assert.IsType<DomainModelDto>(okResult); Assert.Equal(1, okResult.Id); } } [Fact] public void TestGetAllNotDeleted() { //Arrange var options = new DbContextOptionsBuilder<DataContext>() //instead of mocking we use inMemoryDatabase. .UseInMemoryDatabase(databaseName: "TestGetAllNotDeleted") .Options; var config = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfile>()); var mapper = config.CreateMapper(); // according to some people this is better than mocking automapper. //Act using (var context = new DataContext(options)) { context.Domains.AddRange(SeedFakeData.SeedEntitiesDomainModels()); context.Users.AddRange(SeedFakeData.SeedEntitiesUsersModels()); context.SaveChanges(); } using (var context = new DataContext(options)) { var service = new DomainService(context, mapper); var result = service.GetAllNotDeleted("1"); //user that has id 1. This comes from controller in production. //Assert Assert.Equal(2, result.Count()); Assert.IsType<List<DomainModelDto>>(result); foreach (var domainModel in result) { Assert.False(domainModel.Deleted); } } } [Fact] public async void TestCreate() { //Arrange var options = new DbContextOptionsBuilder<DataContext>() //instead of mocking we use inMemoryDatabase. .UseInMemoryDatabase(databaseName: "TestCreate") .Options; var config = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfile>()); var mapper = config.CreateMapper(); // according to some people this is better than mocking automapper. var testModel = new DomainForCreationDto() { Service_Name = "service1", Url = "www.google.com", Notification_Email = "admin1@admin.com" }; //Act using (var context = new DataContext(options)) { context.Domains.AddRange(SeedFakeData.SeedEntitiesDomainModels()); context.Users.AddRange(SeedFakeData.SeedEntitiesUsersModels()); context.SaveChanges(); } using (var context = new DataContext(options)) { var service = new DomainService(context, mapper); var result = await service.Create(testModel, "1"); Assert.Equal(default, result.Parameters); //check for some un-set property if it becomes default after Create service Assert.False(result.Deleted); Assert.IsType<DomainModelDto>(result); Assert.Equal(5, context.Domains.Count()); } } [Fact] public void TestUpdate() { //Arrange var options = new DbContextOptionsBuilder<DataContext>() //instead of mocking we use inMemoryDatabase. .UseInMemoryDatabase(databaseName: "TestUpdate") .Options; var config = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfile>()); var mapper = config.CreateMapper(); // according to some people this is better than mocking automapper. using (var context = new DataContext(options)) { context.Domains.AddRange(SeedFakeData.SeedEntitiesDomainModels()); context.Users.AddRange(SeedFakeData.SeedEntitiesUsersModels()); context.SaveChanges(); } var testModel = new DomainForUpdateDto() { Service_Name = "newServiceName", Url = "http://www.festo.com", Service_Type = ServiceType.ServiceRest, Method = RequestMethod.Get, Basic_Auth = true, Auth_Password = null, Auth_User = null, Notification_Email = "aadas1@aaa.com", Interval_Ms = 30000, Parameters = null, Active = true }; //Act using (var context = new DataContext(options)) { var service = new DomainService(context, mapper); var result = service.Update(1, testModel, "1"); //Assert Assert.Equal(4,context.Domains.Count()); Assert.NotNull(result); Assert.Equal("newServiceName", context.Domains.Find(1).Service_Name); //check if property was updated } } [Fact] public void TestPseudoDelete() { //Arrange var options = new DbContextOptionsBuilder<DataContext>() //instead of mocking we use inMemoryDatabase. .UseInMemoryDatabase(databaseName: "TestPseudoDelete") .Options; var config = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfile>()); var mapper = config.CreateMapper(); // according to some people this is better than mocking automapper. using (var context = new DataContext(options)) { context.Domains.AddRange(SeedFakeData.SeedEntitiesDomainModels()); context.Users.AddRange(SeedFakeData.SeedEntitiesUsersModels()); context.SaveChanges(); } //Act using (var context = new DataContext(options)) { var service = new DomainService(context, mapper); var resultDeleted = service.PseudoDelete(2, "1"); //same teamKey var resultWrongTeam = service.PseudoDelete(4, "1"); //different teamKey //Assert Assert.Equal(4, context.Domains.Count()); //same number as before. It's pseudo delete for a reason. Assert.True(context.Domains.Find(2).Deleted); Assert.False(context.Domains.Find(4).Deleted); } } internal static class SeedFakeData { private static readonly Guid FirstTeamKey = Guid.NewGuid(); private static readonly Guid SecondTeamKey = Guid.NewGuid(); //creates fake users for database internal static IEnumerable<User> SeedEntitiesUsersModels() { var list = new List<User> { new User() { Id = 1, Team_Key = FirstTeamKey }, new User() { Id = 2, Team_Key = FirstTeamKey }, new User() { Id = 3, Team_Key = SecondTeamKey } }; return list; } //creates fake domains for database internal static IEnumerable<DomainModel> SeedEntitiesDomainModels() { var list = new List<DomainModel> { new DomainModel { Id = 1, Service_Name = "service1", Url = "http://www.festo.com", Service_Type = ServiceType.ServiceRest, Method = RequestMethod.Get, Basic_Auth = false, Auth_Password = null, Auth_User = null, Notification_Email = "aadas1@aaa.com", Interval_Ms = 30000, Parameters = null, Active = true, Deleted = false, Created_By = 0, Modified_By = 0, Date_Created = DateTime.Now, Date_Modified = DateTime.Now, Last_Fail = DateTime.Now, Team_Key = FirstTeamKey }, new DomainModel { Id = 2, Service_Name = "service2", Url = "http://www.google.com", Service_Type = ServiceType.ServiceSoap, Method = RequestMethod.Get, Basic_Auth = false, Auth_Password = null, Auth_User = null, Notification_Email = "aadas2@aaa.com", Interval_Ms = 60000, Parameters = "random parameters", Active = true, Deleted = false, Created_By = 0, Modified_By = 0, Date_Created = DateTime.Now, Date_Modified = DateTime.Now, Last_Fail = DateTime.Now, Team_Key = FirstTeamKey }, new DomainModel { Id = 3, Service_Name = "service3", Url = "http://www.kitm.lt", Service_Type = ServiceType.ServiceRest, Method = RequestMethod.Get, Basic_Auth = true, Auth_Password = "password123", Auth_User = "username", Notification_Email = "aadas3@aaa.com", Interval_Ms = 70000, Parameters = "random parameters", Active = false, Deleted = true, Created_By = 0, Modified_By = 0, Date_Created = DateTime.Now, Date_Modified = DateTime.Now, Last_Fail = DateTime.Now, Team_Key = SecondTeamKey }, new DomainModel { Id = 4, Service_Name = "service4", Url = "http://www.facebook.com", Service_Type = ServiceType.ServiceRest, Method = RequestMethod.Post, Basic_Auth = false, Auth_Password = null, Auth_User = null, Notification_Email = "aada4@aaa.com", Interval_Ms = 55000, Parameters = "random parameters", Active = true, Deleted = false, Created_By = 0, Modified_By = 0, Date_Created = DateTime.Now, Date_Modified = DateTime.Now, Last_Fail = DateTime.Now, Team_Key = SecondTeamKey } }; return list; } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2017 { public class Problem13 : AdventOfCodeBase { private Dictionary<int, Layer> _layers; private List<Offset> _offsets; public override string ProblemName { get { return "Advent of Code 2017: 13"; } } public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { GetLayers(input); return Simulate(); } private int Answer2(List<string> input) { GetLayers(input); SetOffsets(); return FindLowest(); } private int FindLowest() { int delay = 1; bool isGood; do { isGood = true; foreach (var offset in _offsets) { if ((delay - offset.Start) % offset.Cycle == 0) { isGood = false; break; } } if (isGood) return delay; delay++; } while (true); } private void SetOffsets() { _offsets = _layers.Values.Select(x => new Offset() { Cycle = (x.Length == 2 ? 2 : (x.Length - 2) * 2 + 2), Position = x.Number }).ToList(); _offsets.ForEach(x => x.Start = x.Cycle - x.Position); _offsets.Where(x => x.Position == 0).First().Start = 0; } private int Simulate() { int severity = 0; var max = _layers.Keys.Max(); for (int index = 0; index <= max; index++) { if (_layers.ContainsKey(index)) { var layer = _layers[index]; if (layer.Position == 1) { severity += layer.Number * layer.Length; } } SimulateNext(index, max); } return severity; } private void SimulateNext(int startIndex, int max) { for (int next = startIndex; next <= max; next++) { if (_layers.ContainsKey(next)) { var layer = _layers[next]; if (layer.Position == 1) { layer.Direction = 1; } else if (layer.Position == layer.Length) { layer.Direction = -1; } layer.Position += layer.Direction; } } } private void GetLayers(List<string> input) { _layers = input.Select(line => { var split = line.Split(':'); var layer = new Layer(); layer.Number = Convert.ToInt32(split[0]); layer.Length = Convert.ToInt32(split[1].Trim()); layer.Direction = 1; layer.Position = 1; return layer; }).ToDictionary(x => x.Number, x => x); } private class Offset { public int Start { get; set; } public int Cycle { get; set; } public int Position { get; set; } } private class Layer { public int Number { get; set; } public int Position { get; set; } public int Length { get; set; } public int Direction { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IslandProblem { public class Unit { public Unit() { } public Unit(byte contents, Island island, int x, int y, double f, int g, List<Unit> neighbours) { Contents = contents; Island = island; X = x; Y = y; F = f; G = g; Neighbours = neighbours; } public byte Contents { get; set; } public Island Island { get; set; } public int X { get; set; } public int Y { get; set; } public double F { get; set; } public int G { get; set; } public List<Unit> Neighbours { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TP.Entities { [Table("Payments")] public class Payment { [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int PaymentId { get; set; } public User pay_user { get; set; } [DisplayName("Miktar")] public decimal payment { get; set; } [DisplayName("Ödeme Tarihi")] public DateTime payDate { get; set; } public int JobAdvId { get; set; } [ForeignKey("JobAdvId")] public virtual Job_Adv Job_Adv { get; set; } } }
using Assets.Scripts.Ui; using UnityEngine; namespace Assets.Scripts.UI.Dialogs { public class OptionsDialog : View { public GameObject NewGameButton; public GameObject SaveButton; public GameObject CloseObject; public GameObject MoveCarButton; public GameObject MoveCarConfirm; public GameObject MoveCarConfrimOk; public GameObject MoveCarConfrimCancel; public GameObject PlayerRespwanButton; public GameObject PlayerRespawnConfrimDialog; public GameObject PlayerRespawnConfrimYes; public GameObject PlayerRespawnConfrimNo; public UILabel TimeLabel; public GameObject NewGameConfirm; public GameObject NewGameYesButton; public GameObject NewGameNoButton; public LanguageSelector LanguageDialog; public FbDialog FbDialog; public UISlider ControlSensitivitySlider; public UISlider GraphicQuality; public UISlider WaterQuality; public UILabel GraphicLevelLabel; public UILabel WaterLevelLabel; public GameObject ExitGameButton; public GameObject ExitGameConfirmDialog; public GameObject ExitGameConfirm; public GameObject ExitGameCancel; public GameObject AchievementsButton; public GameObject LeaderboardsButton; public GameObject ResetAchievementsButton; public GameObject CloudSaveButton; public GameObject LoadFromCloud; private long _score = 0; private long _achi = 0; public override void Init(GameManager gameManager) { base.Init(gameManager); LanguageDialog.Init(gameManager); FbDialog.Init(gameManager); UIEventListener.Get(NewGameButton).onClick += OnNewGameButtonClick; UIEventListener.Get(SaveButton).onClick += OnSaveClick; UIEventListener.Get(CloseObject).onClick += OnCloseClick; UIEventListener.Get(NewGameYesButton).onClick += OnNewGameYesButtonClick; UIEventListener.Get(NewGameNoButton).onClick += OnNewGameNoButtonClick; UIEventListener.Get(MoveCarButton).onClick += OnMoveCarClick; UIEventListener.Get(MoveCarConfrimOk).onClick += OnMoveCarConfrimClick; UIEventListener.Get(MoveCarConfrimCancel).onClick += OnMoveCarCancelClick; UIEventListener.Get(PlayerRespwanButton).onClick += OnPlayerRespawnClick; UIEventListener.Get(PlayerRespawnConfrimYes).onClick += OnPlayerRespawnConfrimClick; UIEventListener.Get(PlayerRespawnConfrimNo).onClick += OnPlayerRespawnNoClick; UIEventListener.Get(ExitGameButton).onClick += OnExitButtonClick; UIEventListener.Get(ExitGameConfirm).onClick += OnExitGameConfirm; UIEventListener.Get(ExitGameCancel).onClick += OnExitGameCancel; UIEventListener.Get(AchievementsButton).onClick += OnAchievementsClick; UIEventListener.Get(LeaderboardsButton).onClick += OnLeaderboarsClick; UIEventListener.Get(ResetAchievementsButton).onClick += OnResetAchievmentsClick; UIEventListener.Get(CloudSaveButton).onClick += OnSaveCloudClick; UIEventListener.Get(LoadFromCloud).onClick += OnLoadFromCloudClick; var defalutSensitivity = 0.12f; ExitGameButton.SetActive(false); #if UNITY_ANDROID defalutSensitivity = 0.12f; ExitGameButton.SetActive(true); #endif var sensitivity = PlayerPrefs.GetFloat("LookPadSensitivity", defalutSensitivity); SetSensitivity(sensitivity, true); GraphicQuality.value = (float)QualityManager.CurrentQuality / 3.0f; SetGraphicLevelText((int) QualityManager.CurrentQuality, GraphicLevelLabel); WaterQuality.value = (float) QualityManager.CurrentWaterQuality / 2.0f; SetGraphicLevelText((int)QualityManager.CurrentWaterQuality, WaterLevelLabel); ControlSensitivitySlider.onDragFinished += OnSensitivity; GraphicQuality.onDragFinished += OnChangeGraphicQuality; WaterQuality.onDragFinished += OnChangeWaterQuality; #if UNITY_ANDROID CloudSaveButton.SetActive(true); LoadFromCloud.SetActive(true); #else CloudSaveButton.SetActive(false); LoadFromCloud.SetActive(false); #endif } public override void Show() { base.Show(); GameManager.Player.MainHud.SetActiveButtons(false); GameManager.Player.MainHud.SetActiveControls(false); var time = TOD_Sky.Instance.Cycle.DateTime.ToShortTimeString(); TimeLabel.text = time.ToString(); FbDialog.Show(); } private void OnPlayerRespawnNoClick(GameObject go) { PlayerRespawnConfrimDialog.SetActive(false); } private void OnPlayerRespawnConfrimClick(GameObject go) { PlayerRespawnConfrimDialog.SetActive(false); GameManager.Player.transform.position = GameManager.Player.RespawnPoint.position; Hide(); } private void OnPlayerRespawnClick(GameObject go) { PlayerRespawnConfrimDialog.SetActive(true); } private void OnMoveCarCancelClick(GameObject go) { MoveCarConfirm.SetActive(false); } private void OnMoveCarConfrimClick(GameObject go) { MoveCarConfirm.SetActive(false); GameManager.CarInteractive.MoveToDefaultPosition(); Hide(); } private void OnMoveCarClick(GameObject go) { MoveCarConfirm.SetActive(true); } private void OnChangeGraphicQuality() { var value = GraphicQuality.value * 3.0f; QualityManager.SetQuality(GameManager, (int)value); SetGraphicLevelText((int)value, GraphicLevelLabel); } private void OnChangeWaterQuality() { var value = WaterQuality.value * 2.0f; QualityManager.SetWaterQuality(GameManager, (int)value); SetGraphicLevelText((int)value, WaterLevelLabel); } private void SetGraphicLevelText(int value, UILabel label) { switch (value) { case 0: label.text = Localization.Get("low"); break; case 1: label.text = Localization.Get("medium"); break; case 2: label.text = Localization.Get("high"); break; case 3: label.text = Localization.Get("ultra"); break; } } private void OnSensitivity() { SetSensitivity(ControlSensitivitySlider.value); } private void SetSensitivity(float sens, bool changeSliderValue = false) { if (sens <= 0) sens = 0.1f; if (changeSliderValue) ControlSensitivitySlider.value = sens; GameManager.Player.MainHud.LookPad.RotationSensitivity = new Vector2(sens * 2.0f, sens * 1.4f); #if UNITY_ANDROID GameManager.Player.MainHud.LookPad.RotationSensitivity = new Vector2(sens * 3.0f, sens * 2.0f); #endif PlayerPrefs.SetFloat("LookPadSensitivity", sens); } private void OnNewGameButtonClick(GameObject go) { NewGameConfirm.SetActive(true); SoundManager.PlaySFX(WorldConsts.AudioConsts.ButtonClick); } private void OnNewGameYesButtonClick(GameObject go) { GameManager.StartNewGame(); SoundManager.PlaySFX(WorldConsts.AudioConsts.ButtonClick); } private void OnNewGameNoButtonClick(GameObject go) { NewGameConfirm.SetActive(false); SoundManager.PlaySFX(WorldConsts.AudioConsts.ButtonClick); } private void OnSaveClick(GameObject go) { ProgressManager.SaveProgress(GameManager); GameManager.Player.MainHud.ShowHudText("Game Saved", HudTextColor.Green); Hide(); } private void OnExitGameCancel(GameObject go) { ExitGameConfirmDialog.SetActive(false); } private void OnExitGameConfirm(GameObject go) { ProgressManager.SaveProgress(GameManager); Application.Quit(); } private void OnExitButtonClick(GameObject go) { ExitGameConfirmDialog.SetActive(true); } private void OnCloseClick(GameObject go) { Hide(); } private void OnAchievementsClick(GameObject go) { #if UNITY_IOS GameCenterManager.ShowAchievements(); #endif #if UNITY_ANDROID GooglePlayServicesController.ShowAchievmentsUI(); #endif } private void OnLeaderboarsClick(GameObject go) { #if UNITY_IOS GameCenterManager.ShowLeaderboards(); #endif #if UNITY_ANDROID GooglePlayServicesController.ShowLeaderBoardUI(); #endif } private void OnResetAchievmentsClick(GameObject go) { #if UNITY_IOS GameCenterManager.ResetAchievments(); PlayerPrefs.DeleteAll(); #endif } private void OnSaveCloudClick(GameObject go) { ProgressManager.SaveProgress(GameManager, true); } private void OnLoadFromCloudClick(GameObject go) { GooglePlayServicesController.LoadGame(OnCloudGameLoaded); } private void OnCloudGameLoaded(bool success) { if (!success) return; ProgressManager.LoadProgressFromCloud(GameManager); } public override void Hide() { GameManager.Player.MainHud.SetActiveButtons(true); GameManager.Player.MainHud.SetActiveControls(true); base.Hide(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using GDS.Entity; using SqlSugar; namespace GDS.Dal { public class ImplUsers : ImplDaoBase<Users>, IUsersDao<Users> { public List<Users> GetUsersByDepartId(int departId) { try { using (var db = SugarDao.GetInstance()) { db.IsNoLock = true; if (departId == 0) { var li = db.Queryable<Users>().Where(x => !x.Disable).ToList(); return li; } else { var li = db.SqlQuery<Users>(@" select a.* from Users a left join UserDetail b on a.ID = b.UserID where b.departId = @departId ", new { departId }); return li; } } } catch (Exception ex) { return null; } } public List<Users> GetDataByUserName(string userName) { try { using (var db = SugarDao.GetInstance()) { db.IsNoLock = true; var li = db.Queryable<Users>().Where(x => x.UserName == userName).ToList(); return li; } } catch (Exception ex) { return null; } } } }