text
stringlengths
13
6.01M
using UnityEngine; using UnityEngine.UI; public class Battle : MonoBehaviour { [SerializeField] private SceneNavigator _scneeNavigator; [SerializeField] private GameObject prefab; [SerializeField] private float timer = 120; [SerializeField] private Text TimerText; [SerializeField] private GameObject scoreDatePrefab; [SerializeField] private ScoreParameters[] _scoreParameters; [SerializeField] private AudioClip _countSound = null; [SerializeField] private AudioClip _countdownSound = null; private AudioSource _audioSource; public AudioSource AudioSource { get { if (_audioSource == null) { _audioSource = GetComponent<AudioSource>(); } return _audioSource; } } private bool OneAudio = false; private float count; void Start() { } // Update is called once per frame void Update() { timer -= Time.deltaTime; TimerText.text = timer.ToString("N2"); if (timer == 60) { AudioSource.PlayOneShot(_countSound); } count = timer % 10; if (count <= 5 && count >= 4.5) { Instantiate(prefab, new Vector3(Random.Range(-7.0f, 7.0f), 5, Random.Range(-5.0f, 3.0f)), Quaternion.identity); } if (timer <= 10) { Instantiate(prefab, new Vector3(Random.Range(-7.0f, 7.0f), 7, Random.Range(-5.0f, 3.0f)), Quaternion.identity); if (OneAudio == false) { OneAudio = true; AudioShot(); } } bool Enter = Input.GetKeyDown("return"); if (timer <= 0.01 || Enter) { _scoreParameters[0].GetScore(); var scoreDate =Instantiate(scoreDatePrefab).GetComponent<RankRemoval>(); scoreDate.gameObject.name = "ScoreDate"; scoreDate.Add("1Player", _scoreParameters[0].GetScore()); scoreDate.Add("2Player", _scoreParameters[1].GetScore()); scoreDate.Add("3Player", _scoreParameters[2].GetScore()); scoreDate.Add("4Player", _scoreParameters[3].GetScore()); scoreDate.Sort(); _scneeNavigator.Navigate(Scenes.Result); } } void AudioShot() { AudioSource.PlayOneShot(_countdownSound); } }
using System; namespace accumulatorsandcounters { class Program { static void Main(string[] args) { Console.WriteLine("please insert a number: "); int num = Convert.ToInt32(Console.ReadLine()); for(int i=1; i<=8; i++) // hace que se pueda repetir cada valor y se pueda crear el triangulo { for(int j=num; j>i; j--) // da el valor para poder hacer el triangulo { Console.Write(j + " "); } for(int a=num; a<i; a++) //bucle para los espacios para crear el triangulo { Console.WriteLine(); } Console.WriteLine(); } Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace PaperPlane.API.MemoryManager { internal class MemoryLine { private readonly Memory<byte> _value; private readonly IEnumerable<MemoryLine> _lines = null; private MemoryLine(IEnumerable<MemoryLine> lines) => _lines = lines; private MemoryLine(Memory<byte> data) => _value = data; private MemoryLine(byte[] data) => _value = data; private MemoryLine(long number) => _value = BitConverter.GetBytes(number); private MemoryLine(int number) => _value = BitConverter.GetBytes(number); private MemoryLine(byte number) => _value = new byte[] { number }; public int Length { get => !_value.IsEmpty ? _value.Length : _lines.Sum(l => l.Length); } public byte[] ToArray() { var line = new byte[Length]; using (var ms = new MemoryStream(line)) { WriteToStream(ms, this); return ms.ToArray(); } } private static void WriteToStream(Stream stream, MemoryLine line) { if (!line._value.IsEmpty) stream.Write(line._value.Span); else if (line._lines != null) foreach (var l in line._lines) { WriteToStream(stream, l); } } public async ValueTask WriteToStreamAsync(Stream stream) { if (!_value.IsEmpty) await stream.WriteAsync(_value); if (_lines != null) foreach (var l in _lines) { await stream.WriteAsync(l._value); } } public static implicit operator MemoryLine(Memory<byte> data) => new MemoryLine(data); public static implicit operator MemoryLine(byte[] data) => new MemoryLine(data); public static implicit operator MemoryLine(long number) => new MemoryLine(number); public static implicit operator MemoryLine(int number) => new MemoryLine(number); public static implicit operator MemoryLine(byte number) => new MemoryLine(number); public static MemoryLine Create(params MemoryLine[] lines) => new MemoryLine(lines); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Application.Controllers; using ApplicationBAL; using System.Web.Mvc; using System.Collections.Generic; using Application.ViewModels; namespace Application.Tests { [TestClass] public class ProductControllerTests { [TestMethod] public void GetProductList() { // Case when the productList is given then the productList should dispaly all the products(Count in this case) var mockBAL = new Moq.Mock<IProductService>(); mockBAL.Setup(x => x.GetAllProducts()).Returns(new ProductBusinessModel[] { new ProductBusinessModel() { Id = 1, Name = "Product1", Category = "Category1", StockCount = 3, Price = 1 }}); ProductController productController = new ProductController(mockBAL.Object); var result = productController.Index() as ViewResult; var actualProducts = result.Model as IList<ProductViewModel>; Assert.AreEqual(actualProducts.Count, 1); } [TestMethod] public void ReturnsProductDetailsView() { // Case When productdetails were given then the productDetails view should contain the given data. var mockBAL = new Moq.Mock<IProductService>(); mockBAL.Setup(x => x.GetAllProducts()).Returns(new ProductBusinessModel[] { new ProductBusinessModel() { Id = 1, Name = "Product1", Category = "Category1", StockCount = 3, Price = 1 }}); ProductController productController = new ProductController(mockBAL.Object); var result = productController.Index() as ViewResult; var products = result.Model as List<ProductViewModel>; Assert.IsTrue(products.Exists(x => x.Id == 1)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; namespace FakePlayer { [Service] public class PlayerService : Service { public static string EXTRA_PLAYLIST = "EXTRA_PLAYLIST"; public static string EXTRA_SHUFFLE = "EXTRA_SHUFFLE"; private bool isPlaying = false; public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { string playlist = intent.GetStringExtra(EXTRA_PLAYLIST); bool useShuffle = intent.GetBooleanExtra(EXTRA_SHUFFLE, false); Play(playlist, useShuffle); return StartCommandResult.NotSticky; } public override IBinder OnBind(Intent intent) { return (null); } public override void OnDestroy() { Stop(); base.OnDestroy(); } private void Play(string playlist, bool useShuffle) { if (!isPlaying) { Log.WriteLine(LogPriority.Info, Class.Name, "Got to Play()"); isPlaying = true; } } private void Stop() { if (isPlaying) { Log.WriteLine(LogPriority.Info, Class.Name, "Got to Stop()"); isPlaying = false; } } } }
using System; namespace Piovra.Graphs; public class PrimMST<V> where V : IEquatable<V> { readonly IWeightedGraph<V> _g; public PrimMST(IWeightedGraph<V> g) { _g = g; } public MST<V> Execute() { var mst = new MST<V>(); return mst; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems.AdventOfCode.Y2022 { public class Problem09 : AdventOfCodeBase { public override string ProblemName => "Advent of Code 2022: 9"; public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { var moves = GetMoves(input); var state = Process(moves); return Count(state); } private int Answer2(List<string> input) { var moves = GetMoves(input); var state = ProcessAll(moves); return Count(state); } private State Process(List<Move> moves) { var state = new State() { Hash = new Dictionary<int, HashSet<int>>(), Head = new Point(), Tail = new Point() }; foreach (var move in moves) { for (int count = 1; count <= move.Count; count++) { MoveHead(state, move); Follow(state.Head, state.Tail); AddToHash(state.Tail, state.Hash); } } return state; } private State ProcessAll(List<Move> moves) { var state = new State() { Hash = new Dictionary<int, HashSet<int>>(), Head = new Point(), All = Enumerable.Range(0, 9).Select(x => new Point()).ToArray() }; foreach (var move in moves) { for (int count = 1; count <= move.Count; count++) { MoveHead(state, move); Follow(state.Head, state.All[0]); for (int index = 1; index < state.All.Length; index++) { Follow(state.All[index - 1], state.All[index]); } AddToHash(state.All.Last(), state.Hash); } } return state; } private void MoveHead(State state, Move move) { switch (move.Direction) { case enumDirection.Up: state.Head.Y--; break; case enumDirection.Down: state.Head.Y++; break; case enumDirection.Left: state.Head.X--; break; case enumDirection.Right: state.Head.X++; break; } } private void AddToHash(Point point, Dictionary<int, HashSet<int>> hash) { if (!hash.ContainsKey(point.X)) { hash.Add(point.X, new HashSet<int>()); } hash[point.X].Add(point.Y); } private void Follow(Point head, Point tail) { if (head.X != tail.X && head.Y != tail.Y && (Math.Abs(head.X - tail.X) == 2 || Math.Abs(head.Y - tail.Y) == 2)) { if (head.X > tail.X) { tail.X++; } else { tail.X--; } if (head.Y > tail.Y) { tail.Y++; } else { tail.Y--; } } else if (head.X - tail.X == 2) { tail.X++; } else if (tail.X - head.X == 2) { tail.X--; } else if (head.Y - tail.Y == 2) { tail.Y++; } else if (tail.Y - head.Y == 2) { tail.Y--; } } private int Count(State state) { return state.Hash.SelectMany(x => x.Value).Count(); } private List<Move> GetMoves(List<string> input) { return input.Select(x => new Move() { Count = Convert.ToInt32(x.Substring(2)), Direction = Move.GetDirection(x[0]) }).ToList(); } private class Move { public enumDirection Direction { get; set; } public int Count { get; set; } public static enumDirection GetDirection(char digit) { switch (digit) { case 'D': return enumDirection.Down; case 'U': return enumDirection.Up; case 'L': return enumDirection.Left; case 'R': return enumDirection.Right; default: throw new Exception(); } } } private enum enumDirection { Down, Up, Left, Right } private class Point { public int X { get; set; } public int Y { get; set; } } private class State { public Point Head { get; set; } public Point Tail { get; set; } public Point[] All { get; set; } public Dictionary<int, HashSet<int>> Hash { get; set; } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Katas; namespace Katas.Tests; [TestClass] public class BinToDecTests { [TestMethod] public void binaryArrayToNumber_Should_Return_Int() { // Arrange int[] myBinaryNumber = new int[] { 0, 1, 0, 1}; var expected = 5; var binToDecConverter = new BinToDec(); // Act var result = binToDecConverter.binaryArrayToNumber(myBinaryNumber); // Assert Assert.AreEqual(expected, result); } }
using System; using LibBlowfish; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BlowfishTest { [TestClass] public class BlowfishTest { private string key = "alwo20493jd;a;85"; private string plainText = "badcoffeeweirdfo"; private string ciphertext = "854E2CDB188093EB93122D0942DC7579"; [TestMethod] public void TestStringEncrypt() { Blowfish b = new Blowfish(key); Assert.AreEqual(ciphertext, b.EncryptString(plainText)); } [TestMethod] public void TestStringDecrypt() { Blowfish b = new Blowfish(key); Assert.AreEqual(plainText, b.DecryptString(ciphertext)); } [TestMethod] public void TestBlockRoundTrip() { Blowfish b = new Blowfish(key); byte[] bytes = new byte[] { 0x10, 0x10, 0xFF, 0xFF, 0xDE, 0xAD, 0xBE, 0xEF }; byte[] encrypted = b.EncryptBlock(bytes); byte[] decrypted = b.DecryptBlock(encrypted); for (int i = 0; i < 8; i++) { Assert.AreEqual(bytes[i], decrypted[i]); } } } }
using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace ClinicManagement.Blazor.Services { public class HttpService { private readonly HttpClient _httpClient; private readonly string _apiUrl; public HttpService(HttpClient httpClient) { _httpClient = httpClient; _apiUrl = _httpClient.BaseAddress.ToString(); } public async Task<T> HttpGetAsync<T>(string uri) where T : class { var result = await _httpClient.GetAsync($"{_apiUrl}{uri}"); if (!result.IsSuccessStatusCode) { return null; } return await FromHttpResponseMessageAsync<T>(result); } public async Task<string> HttpGetAsync(string uri) { var result = await _httpClient.GetAsync($"{_apiUrl}{uri}"); if (!result.IsSuccessStatusCode) { return null; } return await result.Content.ReadAsStringAsync(); } public async Task<T> HttpDeleteAsync<T>(string uri, object id) where T : class { var result = await _httpClient.DeleteAsync($"{_apiUrl}{uri}/{id}"); if (!result.IsSuccessStatusCode) { return null; } return await FromHttpResponseMessageAsync<T>(result); } public async Task<T> HttpPostAsync<T>(string uri, object dataToSend) where T : class { var content = ToJson(dataToSend); var result = await _httpClient.PostAsync($"{_apiUrl}{uri}", content); if (!result.IsSuccessStatusCode) { return null; } return await FromHttpResponseMessageAsync<T>(result); } public async Task<T> HttpPutAsync<T>(string uri, object dataToSend) where T : class { var content = ToJson(dataToSend); var result = await _httpClient.PutAsync($"{_apiUrl}{uri}", content); if (!result.IsSuccessStatusCode) { return null; } return await FromHttpResponseMessageAsync<T>(result); } private StringContent ToJson(object obj) { return new StringContent(JsonSerializer.Serialize(obj), Encoding.UTF8, "application/json"); } private async Task<T> FromHttpResponseMessageAsync<T>(HttpResponseMessage result) { return JsonSerializer.Deserialize<T>(await result.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } } }
namespace SOLIDPrinciples.OCP.Example1.Good { public class Frete2 : IServicoDeEntrega { public double Para(string cidade) { if ("RIO DE JANEIRO".Equals(cidade.ToUpper())) { return 10; } return 15; } } }
using Hayaa.BaseModel; using System; using System.Collections.Generic; using System.Text; namespace Hayaa.Security.Service { public interface LoginService { /// <summary> /// 使用可登陆信息和密码进行登陆 /// </summary> /// <param name="loginKey">可登陆信息:用户名、邮箱、手机号</param> /// <param name="pwd">密码</param> /// <returns></returns> FunctionResult<JobToken> Login(String loginKey, String pwd); FunctionOpenResult<Boolean> WorkerIsLogin(String authtoken); /// <summary> /// 无需授权的用户登陆 /// </summary> /// <param name="loginKey"></param> /// <param name="pwd"></param> /// <returns></returns> FunctionResult<LoginToken> UserLogin(String loginKey, String pwd); FunctionOpenResult<Boolean> UserIsLogin(String authtoken); /// <summary> /// 使用手机号和验证码登陆 /// </summary> /// <param name="mobile"></param> /// <param name="code"></param> /// <returns></returns> FunctionResult<JobToken> MobileLogin(String mobile, String code); /// <summary> /// 注册用户信息 /// </summary> /// <param name="key">人员登陆凭证</param> /// <param name="pwd">密码</param> /// <returns></returns> FunctionOpenResult<Boolean> Reg(string key, string pwd,int userId); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; public class VideoBehavior : MonoBehaviour { // Use this for initialization private VideoPlayer videoPlayer; private Camera camera; void Start () { videoPlayer = GetComponent<VideoPlayer>(); camera = Camera.main; } // Update is called once per frame void Update () { if (Input.GetButtonDown("Fire1")) { Debug.DrawRay(camera.transform.position, camera.transform.forward * 5.0f, Color.yellow, 1.5f); RaycastHit hit; if(Physics.Raycast(camera.transform.position, camera.transform.TransformDirection(Vector3.forward), out hit, 5.0f)) { if(hit.collider.tag == "VideoScreen") { if (videoPlayer.isPlaying) { videoPlayer.Pause(); } else { videoPlayer.Play(); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Media; namespace Crystal.Plot2D { /// <summary> /// Base class for all data transforms. /// Defines methods to transform point from data coordinate system to viewport coordinates and vice versa. /// Derived class should be immutable; to perform any changes a new new instance with different parameters should be created. /// </summary> public abstract class DataTransform { /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns>Transformed point in viewport coordinates.</returns> public abstract Point DataToViewport(Point pt); /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns>Transformed point in data coordinates.</returns> public abstract Point ViewportToData(Point pt); /// <summary> /// Gets the data domain of this dataTransform. /// </summary> /// <value>The data domain of this dataTransform.</value> public virtual DataRect DataDomain => DefaultDomain; public static DataRect DefaultDomain { get; } = DataRect.Empty; } /// <summary> /// Represents identity data transform, which applies no transformation. /// is by default in CoordinateTransform. /// </summary> public sealed class IdentityTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="IdentityTransform"/> class. /// </summary> public IdentityTransform() { } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) => pt; /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) => pt; } /// <summary> /// Represents a logarithmic transform of y-values of points. /// </summary> public sealed class Log10YTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="Log10YTransform"/> class. /// </summary> public Log10YTransform() { } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) { double y = pt.Y; if (y < 0) { y = double.MinValue; } else { y = Math.Log10(y); } return new Point(pt.X, y); } /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) => new(pt.X, Math.Pow(10, pt.Y)); /// <summary> /// Gets the data domain of this dataTransform. /// </summary> /// <value>The data domain of this dataTransform.</value> public override DataRect DataDomain => DataDomains.YPositive; } /// <summary> /// Represents a logarithmic transform of x-values of points. /// </summary> public sealed class Log10XTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="Log10XTransform"/> class. /// </summary> public Log10XTransform() { } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) { double x = pt.X; if (x < 0) { x = double.MinValue; } else { x = Math.Log10(x); } return new Point(x, pt.Y); } /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) => new(Math.Pow(10, pt.X), pt.Y); /// <summary> /// Gets the data domain. /// </summary> /// <value>The data domain.</value> public override DataRect DataDomain => DataDomains.XPositive; } /// <summary> /// Represents a mercator transform, used in maps. /// Transforms y coordinates. /// </summary> public sealed class MercatorTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="MercatorTransform"/> class. /// </summary> public MercatorTransform() => CalcScale(MaxLatitude); /// <summary> /// Initializes a new instance of the <see cref="MercatorTransform"/> class. /// </summary> /// <param name="maxLatitude">The maximal latitude.</param> public MercatorTransform(double maxLatitude) { MaxLatitude = maxLatitude; CalcScale(maxLatitude); } private void CalcScale(double maxLatitude) { double maxLatDeg = maxLatitude; double maxLatRad = maxLatDeg * Math.PI / 180; Scale = maxLatDeg / Math.Log(Math.Tan(maxLatRad / 2 + Math.PI / 4)); } /// <summary> /// Gets the scale. /// </summary> /// <value>The scale.</value> public double Scale { get; private set; } /// <summary> /// Gets the maximal latitude. /// </summary> /// <value>The max latitude.</value> public double MaxLatitude { get; } = 85; /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public sealed override Point DataToViewport(Point pt) { double y = pt.Y; if (-MaxLatitude <= y && y <= MaxLatitude) { y = Scale * Math.Log(Math.Tan(Math.PI * (pt.Y + 90) / 360)); } return new Point(pt.X, y); } /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public sealed override Point ViewportToData(Point pt) { double y = pt.Y; if (-MaxLatitude <= y && y <= MaxLatitude) { double e = Math.Exp(y / Scale); y = 360 * Math.Atan(e) / Math.PI - 90; } return new Point(pt.X, y); } } /// <summary> /// Represents transform from polar coordinate system to rectangular coordinate system. /// </summary> public sealed class PolarToRectTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="PolarToRectTransform"/> class. /// </summary> public PolarToRectTransform() { } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) { double r = pt.X; double phi = pt.Y; double x = r * Math.Cos(phi); double y = r * Math.Sin(phi); return new Point(x, y); } /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) { double x = pt.X; double y = pt.Y; double r = Math.Sqrt(x * x + y * y); double phi = Math.Atan2(y, x); return new Point(r, phi); } } /// <summary> /// Represents a data transform which applies rotation around specified center at specified angle. /// </summary> public sealed class RotateDataTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="RotateDataTransform"/> class. /// </summary> /// <param name="angleInRadians">The angle in radians.</param> public RotateDataTransform(double angleInRadians) { Center = new Point(); Angle = angleInRadians; } /// <summary> /// Initializes a new instance of the <see cref="RotateDataTransform"/> class. /// </summary> /// <param name="angleInRadians">The angle in radians.</param> /// <param name="center">The center of rotation.</param> public RotateDataTransform(double angleInRadians, Point center) { Center = center; Angle = angleInRadians; } /// <summary> /// Gets the center of rotation. /// </summary> /// <value>The center.</value> public Point Center { get; } /// <summary> /// Gets the rotation angle. /// </summary> /// <value>The angle.</value> public double Angle { get; } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) => Transform(pt, Angle); /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) => Transform(pt, -Angle); private Point Transform(Point pt, double angle) { Vector vec = pt - Center; double currAngle = Math.Atan2(vec.Y, vec.X); currAngle += angle; Vector rotatedVec = new Vector(Math.Cos(currAngle), Math.Sin(currAngle)) * vec.Length; return Center + rotatedVec; } } /// <summary> /// Represents data transform performed by multiplication on given matrix. /// </summary> public sealed class MatrixDataTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="MatrixDataTransform"/> class. /// </summary> /// <param name="matrix">The transform matrix.</param> public MatrixDataTransform(Matrix matrix) { Matrix = matrix; InvertedMatrix = matrix; InvertedMatrix.Invert(); } public Matrix Matrix { get; } public Matrix InvertedMatrix { get; } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) => Matrix.Transform(pt); /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) => InvertedMatrix.Transform(pt); } /// <summary> /// Represents a chain of transforms which are being applied consequently. /// </summary> public sealed class CompositeDataTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="CompositeDataTransform"/> class. /// </summary> /// <param name="transforms">The transforms.</param> public CompositeDataTransform(params DataTransform[] transforms) { if (transforms == null) { throw new ArgumentNullException("transforms"); } foreach (var transform in transforms) { if (transform == null) { throw new ArgumentNullException("transforms", Strings.Exceptions.EachTransformShouldNotBeNull); } } Transforms = transforms; } /// <summary> /// Initializes a new instance of the <see cref="CompositeDataTransform"/> class. /// </summary> /// <param name="transforms">The transforms.</param> public CompositeDataTransform(IEnumerable<DataTransform> transforms) { Transforms = transforms ?? throw new ArgumentNullException("transforms"); } /// <summary> /// Gets the transforms. /// </summary> /// <value>The transforms.</value> public IEnumerable<DataTransform> Transforms { get; } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) { foreach (var transform in Transforms) { pt = transform.DataToViewport(pt); } return pt; } /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) { foreach (var transform in Transforms.Reverse()) { pt = transform.ViewportToData(pt); } return pt; } } /// <summary> /// Represents a data transform, performed by given lambda function. /// </summary> public sealed class LambdaDataTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="DelegateDataTransform"/> class. /// </summary> /// <param name="dataToViewport">The data to viewport transform delegate.</param> /// <param name="viewportToData">The viewport to data transform delegate.</param> public LambdaDataTransform(Func<Point, Point> dataToViewport, Func<Point, Point> viewportToData) { DataToViewportFunc = dataToViewport ?? throw new ArgumentNullException("dataToViewport"); ViewportToDataFunc = viewportToData ?? throw new ArgumentNullException("viewportToData"); } /// <summary> /// Gets the data to viewport transform delegate. /// </summary> /// <value>The data to viewport func.</value> public Func<Point, Point> DataToViewportFunc { get; } /// <summary> /// Gets the viewport to data transform delegate. /// </summary> /// <value>The viewport to data func.</value> public Func<Point, Point> ViewportToDataFunc { get; } /// <summary> /// Transforms the point in data coordinates to viewport coordinates. /// </summary> /// <param name="pt">The point in data coordinates.</param> /// <returns></returns> public override Point DataToViewport(Point pt) => DataToViewportFunc(pt); /// <summary> /// Transforms the point in viewport coordinates to data coordinates. /// </summary> /// <param name="pt">The point in viewport coordinates.</param> /// <returns></returns> public override Point ViewportToData(Point pt) => ViewportToDataFunc(pt); } /// <summary> /// Contains default data transforms. /// </summary> public static class DataTransforms { /// <summary> /// Gets the default identity data transform. /// </summary> /// <value>The identity data transform.</value> public static IdentityTransform Identity { get; } = new IdentityTransform(); } }
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Industry.Cms.Articles.Domain.Entities; using MongoDB.Bson; namespace Alabo.Industry.Cms.Articles.Domain.Repositories { public class SinglePageRepository : RepositoryMongo<SinglePage, ObjectId>, ISinglePageRepository { public SinglePageRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class Score : MonoBehaviour { public static int ordersDelivered = 0; public static int ordersFailed = 0; public static int totalScore = 0; // inspector public GameObject _scorePanel; public static GameObject scorePanelReference; private void Awake() { scorePanelReference = _scorePanel; ordersDelivered = 0; ordersFailed = 0; totalScore = 0; } void Update() { scorePanelReference.transform.Find("Score").GetComponent<TextMeshProUGUI>().text = totalScore.ToString(); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class MoneyDisplay : MonoBehaviour { public Text moneyText; PlayerStats playerStats; bool registerdForEvents; DistortForEffect distortForEffect; void Awake() { distortForEffect = GetComponent<DistortForEffect> (); } // Use this for initialization void Start () { playerStats = PlayerStats.instance; playerStats.MoneyChanged += new PlayerStats.MoneyChangedEventHandler (DynamicUpdateTreatsText); registerdForEvents = true; SetTreatsText (); } void OnDestroy() { if (registerdForEvents) { playerStats.MoneyChanged -= new PlayerStats.MoneyChangedEventHandler (DynamicUpdateTreatsText); } } bool SetTreatsText() { string text = "" + playerStats.money; if (text != moneyText.text) { moneyText.text = text; return true; } else { return false; } } void DynamicUpdateTreatsText () { if (SetTreatsText()) { distortForEffect.DistortWithDelay (TweakableParams.flyingAnimationTime); } } }
using UnityEngine; using System.Collections.Generic; public class MovementTransformContainer : MonoBehaviour { // references [Header("references")] public List<Transform> movementTransforms; }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Genesys.WebServicesClient { static class GTrace { static readonly TraceSource Log = new TraceSource(typeof(GTrace).Namespace); public enum TraceType { Request, Event, Bayeux, BayeuxError, } public static void Trace(TraceType type, string format, params object[] args) { var traceEventType = type == TraceType.BayeuxError ? TraceEventType.Error : TraceEventType.Verbose; Log.TraceEvent(traceEventType, (int)type, format, args); } public static string PrettifyJson(string json) { object obj = JsonConvert.DeserializeObject(json); return JsonConvert.SerializeObject(obj, Formatting.Indented); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class VibrationManager : MonoBehaviour { public PlayerInput playerInput; private void Awake() { playerInput = GetComponentInParent<PlayerInput>(); } public void Vibrate() { StartCoroutine(Vibration(1, 0.1f)); } IEnumerator Vibration(float strength, float duration) { print("VIBRATE"); Gamepad gamepad = playerInput.GetDevice<Gamepad>(); if (gamepad == null) { print("No gamepad"); yield break; } gamepad.SetMotorSpeeds(strength, strength); print("before"); yield return new WaitForSeconds(duration); print("after"); gamepad.SetMotorSpeeds(0, 0); } }
using IWorkFlow.DataBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("Para_CP_ProjectTrade", "")] public class Para_CP_ProjectTrade : QueryInfo { [DataField("TradeCode", "Para_CP_ProjectTrade")] public string TradeCode { get { return this._TradeCode; } set { this._TradeCode = value; } } string _TradeCode; [DataField("TradeName", "Para_CP_ProjectTrade")] public string TradeName { get { return this._TradeName; } set { this._TradeName = value; } } string _TradeName; [DataField("ParentCode", "Para_CP_ProjectTrade")] public string ParentCode { get { return this._ParentCode; } set { this._ParentCode = value; } } string _ParentCode; [DataField("Old", "Para_CP_ProjectTrade")] public int Old { get { return this._Old; } set { this._Old = value; } } int _Old; } }
using System; using System.Collections.Generic; using System.Text; namespace MazeGenerator { public class Generator { private int x_size; private int y_size; private Field start; private Field end; private Field[,] board; private int length; public Generator(int x, int y) { this.x_size = x; this.y_size = y; } public void Start() { this.board = new Field[x_size, y_size]; //Ustawianie mapy na 0 InitMaze(); SetEntryAndExitPoint(); board[start.point.X, start.point.Y].text = start.text; board[end.point.X, end.point.Y].text = end.text; // DrawCorrectPath(); DrawMaze(); } private void DrawCorrectPath() { List<Field> correctPathFromBegin = new List<Field>(); List<Field> correctPathFromEnd = new List<Field>(); correctPathFromBegin.Add(start); correctPathFromEnd.Add(end); int i = 0; while (true) { bla(correctPathFromBegin[i], '+'); bla(correctPathFromEnd[i], '-'); i++; break; } correctPathFromBegin.AddRange(correctPathFromEnd); List<Field> fullCorrectPath = new List<Field>(correctPathFromBegin); } private void bla(Field field, char operation) { Random random = new Random(); var seed = random.Next(1, 4); switch (seed) { case 1: // lewo if (!field.leftWall) { if (!board[field.point.X - 1, field.point.Y].Visited) { } else { bla(field, operation); } } else { bla(field, operation); } break; case 2: // gora if (!field.topWall) { if (!board[field.point.X, field.point.Y + 1].Visited) { } else { bla(field, operation); } } else { bla(field, operation); } break; case 3: //prawo if (!field.rightWall) { if (!board[field.point.X + 1, field.point.Y].Visited) { } else { bla(field, operation); } } else { bla(field, operation); } break; case 4: //dol if (!field.bottomWall) { if (!board[field.point.X, field.point.Y - 1].Visited) { } else { bla(field, operation); } } else { bla(field, operation); } break; default: break; } } private void InitMaze() { for (int y_axis = 0; y_axis < y_size; y_axis++) { for (int x_axis = 0; x_axis < x_size; x_axis++) { board[y_axis, x_axis] = new Field(new Point(y_axis, x_axis), "0"); if (y_axis == 0) { board[y_axis, x_axis].leftWall = true; } if (y_axis == y_size - 1) { board[y_axis, x_axis].rightWall = true; } if (x_axis == 0) { board[y_axis, x_axis].topWall = true; } if (x_axis == x_size - 1) { board[y_axis, x_axis].bottomWall = true; } } } } private void SetEntryAndExitPoint() { // 1 - lewo 2 - gora 3 - prawo 4 - dol Random random = new Random(); int startSeed = random.Next(1, 4); int exitSeed = random.Next(1, 4); switch (startSeed) { case 1: // x = 0 start = new Field(new Point(0, random.Next(1, y_size - 2)), "1"); start.topWall = true; break; case 2: // y = 0 start = new Field(new Point(random.Next(1, x_size - 2), 0), "1"); start.leftWall = true; break; case 3: // x = max start = new Field(new Point(x_size - 1, random.Next(1, y_size - 2)), "1"); start.bottomWall = true; break; case 4: // y = max start = new Field(new Point(random.Next(1, x_size - 2), y_size - 1), "1"); start.rightWall = true; break; default: break; } if (startSeed == exitSeed) { List<int> AvaliableX = new List<int>(); List<int> AvaliableY = new List<int>(); for (int i = 1; i < x_size - 1; i++) { if (i != start.point.X) if (i != start.point.X - 1) if (i != start.point.X + 1) AvaliableX.Add(i); } for (int i = 1; i < y_size - 1; i++) { if (i != start.point.Y) if (i != start.point.Y - 1) if (i != start.point.Y + 1) AvaliableY.Add(i); } switch (exitSeed) { case 1: // x = 0 end = new Field(new Point(0, AvaliableY[random.Next(0, AvaliableY.Count - 1)]), String.Empty); end.topWall = true; break; case 2: // y = 0 end = new Field(new Point(AvaliableX[random.Next(0, AvaliableX.Count - 1)], 0), String.Empty); end.leftWall = true; break; case 3: // x = max end = new Field(new Point(x_size - 1, AvaliableY[random.Next(0, AvaliableY.Count - 1)]), String.Empty); end.bottomWall = true; break; case 4: // y = max end = new Field(new Point(AvaliableX[random.Next(0, AvaliableX.Count - 1)], y_size - 1), String.Empty); end.rightWall = true; break; default: break; } } else { switch (exitSeed) { case 1: // x = 0 end = new Field(new Point(0, random.Next(1, y_size - 2)), ""); end.topWall = true; break; case 2: // y = 0 end = new Field(new Point(random.Next(1, x_size - 2), 0), ""); end.leftWall = true; break; case 3: // x = max end = new Field(new Point(x_size - 1, random.Next(1, y_size - 2)), ""); end.bottomWall = true; break; case 4: // y = max end = new Field(new Point(random.Next(1, x_size - 2), y_size - 1), ""); end.rightWall = true; break; default: break; } } SetCorrectPathLength(random); end.text = length.ToString(); } private void SetCorrectPathLength(Random random) { length = (int)Math.Round((x_size * y_size) * (0.01 * random.Next(25, 35))); } private void DrawMaze() { for (int i = 0; i < y_size; i++) { for (int j = 0; j < x_size; j++) { Console.Write(board[i, j].text + "\t"); } Console.WriteLine(); Console.WriteLine(); } Console.ReadLine(); } } }
namespace E_ticaret.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class sipari { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public sipari() { faturas = new HashSet<fatura>(); } [Key] public int siparis_id { get; set; } [Column(TypeName = "date")] public DateTime? siparis_talep_tarih { get; set; } public int? urun_id { get; set; } public int? kargo_id { get; set; } [Column(TypeName = "date")] public DateTime? cikis_tarih { get; set; } [Column(TypeName = "date")] public DateTime? teslim_tarih { get; set; } public int? kargo_ucret { get; set; } public int? odeme_id { get; set; } public int? adres_id { get; set; } public virtual Adre Adre { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<fatura> faturas { get; set; } public virtual kargo kargo { get; set; } public virtual odeme odeme { get; set; } public virtual urunler urunler { get; set; } } }
using System; using System.Diagnostics.CodeAnalysis; using UnityEngine; namespace Quark.Utilities { /// <summary> /// This enumeration is used by the 2 dimensional geometry functions /// to determine the correct plane to work on in Quark utilities. /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public enum Planes { /// <summary> /// The X-Y plane. /// </summary> XY, /// <summary> /// The X-Z plane. /// </summary> XZ, /// <summary> /// The Y-Z plane. /// </summary> YZ } public class Utils { /// <summary> /// This function checks whether a value is included in a given enumeration. /// </summary> /// <param name="value">The value to check</param> /// <param name="checkfor">The value to check for</param> /// <returns></returns> public static bool Checkflag(Enum value, Enum checkfor) { ulong longVal = Convert.ToUInt64(value); ulong longOpt = Convert.ToUInt64(checkfor); return (longVal & longOpt) == longOpt; } /// <summary> /// Aligns a vector in the given direction /// </summary> /// <param name="vector">Vector to align</param> /// <param name="align">Direction</param> /// <returns>Aligned vector</returns> public static Vector3 AlignVector(Vector3 vector, Vector3 align) { float angle = Mathf.Atan(align.z / align.x); int isNegative = (align.z < 0 && align.x > 0) || (align.x > 0 && align.z > 0) ? 1 : -1; float sin = Mathf.Sin(angle); float cos = Mathf.Cos(angle); Vector3 temp = new Vector3 { x = vector.x * cos - vector.z * sin, z = vector.x * sin + vector.z * cos }; temp = temp * isNegative; temp.y = vector.y; return temp; } /// <summary> /// Sets the unnecessary component of a 3d vector to zero. /// </summary> /// <param name="vector">The vector</param> /// <param name="plane">The plane</param> /// <returns>A new vector on the given plane.</returns> public static Vector3 VectorOnPlane(Vector3 vector, Planes plane) { switch (plane) { case Planes.XY: vector.z = 0; break; case Planes.XZ: vector.y = 0; break; case Planes.YZ: vector.x = 0; break; } return vector; } /// <summary> /// Calculates the distance between two points /// </summary> /// <param name="v1">First point</param> /// <param name="v2">Second point</param> /// <param name="plane">The plane this function should work on (default XZ)</param> /// <returns>Calculated distance</returns> public static float Distance2(Vector3 v1, Vector3 v2, Planes plane = Planes.XZ) { v1 = VectorOnPlane(v1, plane); v2 = VectorOnPlane(v2, plane); return Vector3.Distance(v1, v2); } /// <summary> /// Returns the angle between 2 points in the range of [0,360] degrees. /// </summary> /// <param name="v1">First Point</param> /// <param name="v2">Second Point</param> /// <param name="plane">The plane this function should work on (default XZ)</param> /// <returns>Angle between them in degrees</returns> public static float Angle2(Vector3 v1, Vector3 v2, Planes plane = Planes.XZ) { v1 = VectorOnPlane(v1, plane); v2 = VectorOnPlane(v2, plane); v1.Normalize(); v2.Normalize(); Vector3 normal = Vector3.up; switch (plane) { case Planes.XY: normal = Vector3.forward; break; case Planes.XZ: normal = Vector3.up; break; case Planes.YZ: normal = Vector3.right; break; } float angle = Vector3.Angle(v1, v2); float sign = Mathf.Sign(Vector3.Dot(v1, Vector3.Cross(normal, v2))); return sign * angle + (sign > 0 ? 0 : 360); } /// <summary> /// Returns the slope in degrees from a vector to another /// </summary> /// <param name="v1">First point</param> /// <param name="v2">Second point</param> /// <param name="plane">The plane this function should work on (default XZ)</param> /// <returns>Slope from the first point to the other in degrees</returns> public static float Slope2(Vector3 v1, Vector3 v2, Planes plane = Planes.XZ) { v1 = VectorOnPlane(v1, plane); v2 = VectorOnPlane(v2, plane); float nominator = 0; float denominator = 0; switch (plane) { case Planes.XY: nominator = v2.y - v1.y; denominator = v2.x - v1.x; break; case Planes.XZ: nominator = v2.z - v1.z; denominator = v2.x - v1.x; break; case Planes.YZ: nominator = v2.z - v1.z; denominator = v2.y - v1.y; break; } float angle = denominator == 0 ? 90 : Mathf.Atan(nominator / denominator) * Mathf.Rad2Deg; if (v2.y > v1.y) { if (angle > 0) return angle; return angle + 180; } if (angle < 0) return angle + 360; return angle + 180; } } }
namespace Krafteq.ElsterModel { using System; using Krafteq.ElsterModel.ValidationCore; using LanguageExt; /// <summary> /// Represents valid money value rounded to 0.01 /// Value must be maximum 11 digits before decimal point /// Cannot be negative /// </summary> public class UnsignedMoney : NewType<UnsignedMoney, decimal> { static readonly Validator<NumericError, decimal> Validator = Validators.All( NumberValidators.LessThan(100000000000m), NumberValidators.NonNegative() ); UnsignedMoney(decimal value) : base(value) { } public static UnsignedMoney Create(uint uintValue) => new UnsignedMoney(uintValue); /// <summary> /// Usually used for Expenses in the UstVa report /// </summary> /// <param name="decimalValue"></param> /// <returns></returns> public static Validation<NumericError, UnsignedMoney> RoundUp(decimal decimalValue) => Validator(decimalValue).Bind(Money.RoundUp).Map(x => new UnsignedMoney(x.Value)); /// <summary> /// Usually used for Income in the UstVa report /// </summary> /// <param name="decimalValue"></param> /// <returns></returns> public static Validation<NumericError, UnsignedMoney> RoundDown(decimal decimalValue) => Validator(decimalValue).Bind(Money.RoundDown).Map(x => new UnsignedMoney(x.Value)); public static implicit operator decimal(UnsignedMoney money) => money.Value; } }
namespace Ejercicio { public class Persona { Quirk quirk; public Persona(Quirk quirk) { this.quirk = quirk; } public int poder(){ return quirk.TiempoDeUso * quirk.Nombre; } public bool esPeligroso(){ return poder() > 1000 && quirk.TiempoDeUso > 60; } } }
namespace FluentQuery.QueryParts { public class InnerJoin : IQueryPart { private string _table1 { get; set; } private string _table2 { get; set; } private string _column1 { get; set; } private string _column2 { get; set; } public InnerJoin(string table1, string column1, string table2, string column2) { _column1 = column1; _column2 = column2; _table1 = table1; _table2 = table2; } public string ToQuery() { return $"INNER JOIN {_table1} on {_table1}.{_column1} = {_table2}.{_column2}"; } } }
using Microsoft.Extensions.Logging; using MikeGrayCodes.BuildingBlocks.Application; using MikeGrayCodes.BuildingBlocks.Application.Behaviors; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace MikeGrayCodes.BuildingBlocks.Infrastructure { public class CommandsScheduler : ICommandsScheduler { private readonly IInternalCommandRepository internalCommandsRepository; private readonly ILogger<CommandsScheduler> logger; public CommandsScheduler(IInternalCommandRepository internalCommandsRepository, ILogger<CommandsScheduler> logger) { this.internalCommandsRepository = internalCommandsRepository ?? throw new ArgumentNullException(nameof(internalCommandsRepository)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task EnqueueAsync(ICommand command) { await internalCommandsRepository.Add(new InternalCommand { Id = command.Id, EnqueueDate = DateTime.UtcNow, Type = command.GetType().FullName, Data = JsonConvert.SerializeObject(command, new JsonSerializerSettings { ContractResolver = new AllPropertiesContractResolver() }) }); } private class AllPropertiesContractResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Select(p => base.CreateProperty(p, memberSerialization)) .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Select(f => base.CreateProperty(f, memberSerialization))) .ToList(); props.ForEach(p => { p.Writable = true; p.Readable = true; }); return props; } } } }
using System; using System.Threading; using System.Threading.Tasks; using CronScheduler.Extensions.StartupInitializer; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection; public static class StartupJobsServiceCollectionExtensions { /// <summary> /// Adds task to run as async job before the rest of the application launches. /// </summary> /// <param name="services"></param> /// <param name="job"></param> /// <returns></returns> public static IServiceCollection AddStartupJobInitializer(this IServiceCollection services, Func<Task> job) { return services.AddStartupJobInitializer() .AddSingleton<IStartupJob>(new DelegateStartupJobInitializer(job)); } /// <summary> /// Adds <see cref="StartupJobInitializer"/> to DI registration. /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddStartupJobInitializer(this IServiceCollection services) { services.TryAddTransient<StartupJobInitializer>(); return services; } /// <summary> /// Adds <see cref="IStartupJob"/> job to the DI registration. /// </summary> /// <typeparam name="TStartupJob"></typeparam> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddStartupJob<TStartupJob>(this IServiceCollection services) where TStartupJob : class, IStartupJob { return services .AddStartupJobInitializer() .AddTransient<IStartupJob, TStartupJob>(); } private class DelegateStartupJobInitializer : IStartupJob { private readonly Func<Task> _startupJob; public DelegateStartupJobInitializer(Func<Task> startupJob) { _startupJob = startupJob; } public Task ExecuteAsync(CancellationToken cancellationToken = default) { return _startupJob(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Animal.GameStrategy { /// <summary> /// 怪物 /// </summary> public class Monster { /// <summary> /// 怪物的生命值 /// </summary> public Int32 HP { get; set; } public Monster(String name, Int32 hp) { this.Name = name; this.HP = hp; } /// <summary> /// 怪物的名字 /// </summary> public String Name { get; set; } /// <summary> /// 怪物被攻击时,被调用的方法,用来处理被攻击后的状态更改 /// </summary> /// <param name="loss">此次攻击损失的HP</param> public void Notify(Int32 loss) { if (this.HP <= 0) { Console.WriteLine("此怪物已死"); return; } this.HP -= loss; if (this.HP <= 0) { Console.WriteLine("怪物" + this.Name + "被打死"); } else { Console.WriteLine("怪物" + this.Name + "损失" + loss + "HP"); } } } }
using System.Collections.Generic; namespace E2 { public class Empresa { List<Monstruos> amistosos = new List<Monstruos>(); List<Monstruos> peligrosos = new List<Monstruos>(); List<Monstruos> respetables = new List<Monstruos>(); public Empresa() { amistosos.Add(new Amistosos(10)); amistosos.Add(new Amistosos(80)); peligrosos.Add(new Amistosos(16)); peligrosos.Add(new Amistosos(75)); } public void NocheDeSustos(){ foreach (var i in peligrosos) i.asustar(); foreach (var i in amistosos) i.asustar(); } public void NocheDeRisas(){ foreach (var i in peligrosos) i.reir(); foreach (var i in amistosos) i.reir(); } public void Respetables(){ foreach(var i in amistosos){ if (i.Respeto > 70) respetables.Add(i); } foreach(var i in peligrosos){ if (i.Respeto > 70) respetables.Add(i); } } public int energia (){ int suma = 0; foreach (var i in amistosos){ suma += i.Respeto; } foreach (var i in peligrosos){ suma += i.Respeto; } return suma; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace signalcompiler { class MainClass { public static void Main(string[] args) { var LexAn = new LexAnalyzer(@"C:\Users\m3sc4\test.sg"); Console.WriteLine("Lexecial Analyzer: "); LexAn.StartAnalyzing(); LexAn.PrintResults(); var SyntaxAn = new SyntaxAnalyzer(LexAn.GetLexemList(), LexAn.GetTokensTable(), LexAn.GetErrorList()); Console.WriteLine("Syntax Analyzer: "); var ParsingTree = SyntaxAn.Parser(); if (ParsingTree != null) { string TextTree = "Parsing tree: " + ParsingTree.Root.ToString() + "\n"; System.IO.File.WriteAllText(@"C:\Users\m3sc4\Tree.txt", TextTree); Console.WriteLine(TextTree); } if(SyntaxAn.GetErrors() != null) { var Errors = SyntaxAn.GetErrors(); foreach(var Error in Errors) { Console.WriteLine(Error.ToString()); } } Console.WriteLine("Code generator: "); var CodeGenerator = new CodeGenerator(ParsingTree, "GeneratedCode.asm", SyntaxAn.GetConstants()); CodeGenerator.GenerateCode(); } } }
using System; using System.Collections; using System.Collections.Generic; using AlgorithmProblems.Graphs.GraphHelper; namespace AlgorithmProblems.Graphs { /// <summary> /// An island is represented by a matrix having 1s and 0s, where 1 -> land and 0 ->water. /// You can change a 0 -> 1 to get the greatest island and need to return the total number of elements forming land /// </summary> public class MakeLargestIsland { #region Naive approach /// <summary> /// This is the main method. /// Algo: 1. Iterate all the cells with 0 and make it 1 /// 2. Do BFS starting at the cell which was switched and calculate the island size /// 3. update whether we found the largest island /// 4. Backtrack by switching back the cell to 0 /// /// The time complexity is O(n^4) /// The space complexity is O(n^2) /// </summary> /// <param name="grid"></param> /// <returns></returns> public int LargestIsland(int[][] grid) { bool isAnyCellWater = false; int largestIsland = 0; if (grid != null) { for (int i = 0; i < grid.Length; i++) { for (int j = 0; j < grid[i].Length; j++) { if (grid[i][j] == 0) { isAnyCellWater = true; // Make this cell as land and check the max land grid[i][j] = 1; int largeIsland = GetMaxIsland(new Cell(i, j), grid, InitializeVisitedArray(grid)); if(largeIsland > largestIsland) { largestIsland = largeIsland; } grid[i][j] = 0; // backtrack } } } } return (isAnyCellWater) ? largestIsland: GetTotalCells(grid); } #endregion #region Performant approach /// <summary> /// /// The running time for this approach is O(n^2) /// The space requirement is O(n^2) /// </summary> /// <param name="grid"></param> /// <returns></returns> public int LargestIslandAlgo2(int[][] grid) { int[][] visitedArr = InitializeVisitedArray(grid); Dictionary<int, int> groupSize = new Dictionary<int, int>(); int groupId = 1; int largestIslandSize = 0; // First pass is to traverse all closely connected components and mark them with one groupId // Also have the groupsize saved in the dictionary for(int i = 0; i < visitedArr.Length; i++) { for(int j = 0; j < visitedArr[i].Length; j++) { if(visitedArr[i][j] == 0 && grid[i][j] == 1) { int islandSize = GetMaxIsland(new Cell(i, j), grid, visitedArr, groupId); groupSize[groupId++] = islandSize; } } } // Second pass will mock convert 0->1 and check whether we can form the biggest island for (int i = 0; i < visitedArr.Length; i++) { for (int j = 0; j < visitedArr[i].Length; j++) { if (grid[i][j] == 0) { int islandSize = 1; HashSet<int> positions = new HashSet<int>(); foreach(Cell direction in GetAllDirections()) { int newRow = i + direction.XCoordinate; int newCol = j + direction.YCoordinate; if (newRow >= 0 && newCol >= 0 && newRow < grid.Length && newCol < grid[newRow].Length && !positions.Contains(visitedArr[newRow][newCol]) && grid[newRow][newCol] == 1 ) { positions.Add(visitedArr[newRow][newCol]); islandSize += groupSize[visitedArr[newRow][newCol]]; } } if(islandSize > largestIslandSize) { largestIslandSize = islandSize; } } } } return largestIslandSize == 0 ? GetTotalCells(grid) : largestIslandSize; } #endregion #region common methods private int[][] InitializeVisitedArray(int[][] grid) { int[][] ret = new int[grid.Length][]; for (int i = 0; i < grid.Length; i++) { ret[i] = new int[grid[i].Length]; } return ret; } private int GetTotalCells(int[][] grid) { int totalCells = 0; for (int i = 0; i < grid.Length; i++) { totalCells += grid[i].Length; } return totalCells; } private List<Cell> GetCellNeighbours(Cell c, int[][] grid, int[][] visited, int groupId = 1) { List<Cell> cells = new List<Cell>(); if (c.XCoordinate + 1 < grid.Length && visited[c.XCoordinate + 1][c.YCoordinate] != groupId && grid[c.XCoordinate + 1][c.YCoordinate] == 1) { cells.Add(new Cell(c.XCoordinate + 1, c.YCoordinate)); } if (c.XCoordinate - 1 >= 0 && visited[c.XCoordinate - 1][c.YCoordinate] != groupId && grid[c.XCoordinate - 1][c.YCoordinate] == 1) { cells.Add(new Cell(c.XCoordinate - 1, c.YCoordinate)); } if (c.YCoordinate + 1 < grid[c.XCoordinate].Length && visited[c.XCoordinate][c.YCoordinate + 1] != groupId && grid[c.XCoordinate][c.YCoordinate + 1] == 1) { cells.Add(new Cell(c.XCoordinate, c.YCoordinate + 1)); } if (c.YCoordinate - 1 >= 0 && visited[c.XCoordinate][c.YCoordinate - 1] != groupId && grid[c.XCoordinate][c.YCoordinate - 1] == 1) { cells.Add(new Cell(c.XCoordinate, c.YCoordinate - 1)); } return cells; } /// <summary> /// We do BFS from the input cell and keep track of the number of cells which are 1 /// </summary> /// <param name="c"></param> /// <returns></returns> private int GetMaxIsland(Cell c, int[][] grid, int[][] visited, int groupId = 1) { Queue<Cell> q = new Queue<Cell>(); q.Enqueue(c); int maxIsland = 0; visited[c.XCoordinate][c.YCoordinate] = groupId; while (q.Count > 0) { Cell currentCell = q.Dequeue(); maxIsland++; foreach (Cell neighbour in GetCellNeighbours(currentCell, grid, visited, groupId)) { visited[neighbour.XCoordinate][neighbour.YCoordinate] = groupId; q.Enqueue(neighbour); } } return maxIsland; } private static List<Cell> GetAllDirections() { return new List<Cell> { new Cell(-1,0), new Cell(0,-1), new Cell(1,0), new Cell(0,1) }; } #endregion public static void TestMakeLargestIsland() { int[][] island = new int[2][]; island[0] = new int[2] { 1, 1 }; island[1] = new int[2] { 1, 0 }; MakeLargestIsland largeIsland = new MakeLargestIsland(); Console. WriteLine("The size of largest island is {0}, Expected: 4",largeIsland.LargestIsland(island)); Console.WriteLine("Algo2: The size of largest island is {0}, Expected: 4", largeIsland.LargestIslandAlgo2(island)); island = new int[2][]; island[0] = new int[2] { 1, 1 }; island[1] = new int[2] { 1, 1 }; Console.WriteLine("The size of largest island is {0}, Expected: 4", largeIsland.LargestIsland(island)); Console.WriteLine("Algo2: The size of largest island is {0}, Expected: 4", largeIsland.LargestIslandAlgo2(island)); island = new int[5][]; island[0] = new int[5] { 1, 1, 1,0,0 }; island[1] = new int[5] { 1, 1, 1,0,0 }; island[2] = new int[5] { 0, 0, 0, 0, 0 }; island[3] = new int[5] { 0, 0, 1, 1, 1 }; island[4] = new int[5] { 0, 0, 1, 1, 1 }; Console.WriteLine("The size of largest island is {0}, Expected: 13", largeIsland.LargestIsland(island)); Console.WriteLine("Algo2: The size of largest island is {0}, Expected: 13", largeIsland.LargestIslandAlgo2(island)); } } }
using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace EddiSpeechService { /// <summary>Translations for Elite items for text-to-speech</summary> public partial class Translations { public static string GetTranslation(string val, bool useICAO = false, string type = null) { // Translations from fixed dictionaries string translation = val; type = !string.IsNullOrEmpty(type) ? type.ToLowerInvariant() : null; switch (type) { case "power": translation = getPhoneticPower(val); break; case "planettype": translation = getPhoneticPlanetClass(val); break; case "shipmodel": translation = getPhoneticShipModel(val); break; case "shipmanufacturer": translation = getPhoneticShipManufacturer(val); break; case "station": translation = getPhoneticStation(val); break; case "starsystem": translation = getPhoneticStarSystem(val, useICAO); break; case "body": translation = getPhoneticBody(val, useICAO); break; case "faction": translation = getPhoneticFaction(val, useICAO); break; default: if (translation == val) { translation = getPhoneticPower(val); } if (translation == val) { translation = getPhoneticPlanetClass(val); } if (translation == val) { translation = getPhoneticShipModel(val); } if (translation == val) { translation = getPhoneticShipManufacturer(val); } if (translation == val) { translation = getPhoneticStation(val); } if (translation == val) { translation = getPhoneticBody(val, useICAO); } if (translation == val) { translation = getPhoneticStarSystem(val, useICAO); } if (translation == val) { // Faction names can include system names, so we need to recognize system names first translation = getPhoneticFaction(val, useICAO); } break; } return translation; } // Various handy regexes so we don't keep recreating them private static readonly Regex ALPHA_DOT = new Regex(@"[A-Z]\."); private static readonly Regex ALPHA_THEN_NUMERIC = new Regex(@"[A-Za-z]+[0-9]+"); private static readonly Regex UPPERCASE = new Regex(@"([A-Z]{2,})|(?:([A-Z])(?:\s|$))"); private static readonly Regex TEXT = new Regex(@"([A-Za-z]{1,3}(?:\s|$))"); private static readonly Regex DIGIT = new Regex(@"\d+(?:\s|$)"); private static readonly Regex THREE_OR_MORE_DIGITS = new Regex(@"\d{3,}"); private static readonly Regex DECIMAL_DIGITS = new Regex(@"( point )(\d{2,})"); private static readonly Regex SECTOR = new Regex("(.*) ([A-Za-z][A-Za-z]-[A-Za-z] .*)"); private static readonly Regex MOON = new Regex(@"^[a-z]$"); private static readonly Regex SUBSTARS = new Regex(@"^\bA[BCDE]?[CDE]?[DE]?[E]?\b|\bB[CDE]?[DE]?[E]?\b|\bC[DE]?[E]?\b|\bD[E]?\b$"); private static readonly Regex SYSTEMBODY = new Regex(@"^(.*?) ([A-E]+ ){0,2}(Belt(?:\s|$)|Cluster(?:\s|$)|Ring|\d{1,2}(?:\s|$)|[A-Za-z](?:\s|$)){1,12}$"); private static readonly Regex SHORTBODY = new Regex(@"(?=\S)(?<STARS>(?<=^|\s)A?B?C?D?E?)? ?(?<PLANET>(?<=^|\s)\d{1,2})? ?(?<MOON>(?<=^|\s)[a-z])? ?(?<SUBMOON>(?<=^|\s)[a-z])? ?(?>(?<=^|\s)(?<RINGORBELTGROUP>[A-Z]) (?<RINGORBELTTYPE>Belt|Ring))? ?(?>(?<=^|\s)(?<CLUSTER>Cluster) (?<CLUSTERNUMBER>\d*))?$"); private static readonly Regex PROC_GEN_SYSTEM = new Regex(@"^(?<SECTOR>[\w\s'.()-]+) (?<COORDINATES>(?<l1>[A-Za-z])(?<l2>[A-Za-z])-(?<l3>[A-Za-z]) (?<mcode>[A-Za-z])(?:(?<n1>\d+)-)?(?<n2>\d+))$"); private static readonly Regex PROC_GEN_SYSTEM_BODY = new Regex(@"^(?<SYSTEM>(?<SECTOR>[\w\s'.()-]+) (?<COORDINATES>(?<l1>[A-Za-z])(?<l2>[A-Za-z])-(?<l3>[A-Za-z]) (?<mcode>[A-Za-z])(?:(?<n1>\d+)-)?(?<n2>\d+))) ?(?<BODY>.*)$"); private static string replaceWithPronunciation(string sourcePhrase, string[] pronunciation) { StringBuilder sb = new StringBuilder(); int i = 0; foreach (string source in sourcePhrase.Split(' ')) { if (i > 0) { sb.Append(" "); } sb.Append("<phoneme alphabet=\"ipa\" ph=\""); sb.Append(pronunciation[i++]); sb.Append("\">"); sb.Append(source); sb.Append("</phoneme>"); } return sb.ToString(); } public static string ICAO(string callsign, bool passDash = false) { if (callsign == null) { return null; } var elements = new List<string>(); foreach (char c in callsign.ToUpperInvariant()) { switch (c) { case 'A': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈælfə\">alpha</phoneme>"); break; case 'B': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈbrɑːˈvo\">bravo</phoneme>"); break; case 'C': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈtʃɑɹli\">charlie</phoneme>"); break; case 'D': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈdɛltə\">delta</phoneme>"); break; case 'E': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈeko\">echo</phoneme>"); break; case 'F': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈfɒkstrɒt\">foxtrot</phoneme>"); break; case 'G': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ɡɒlf\">golf</phoneme>"); break; case 'H': elements.Add("<phoneme alphabet=\"ipa\" ph=\"hoːˈtel\">hotel</phoneme>"); break; case 'I': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈindiˑɑ\">india</phoneme>"); break; case 'J': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈdʒuːliˑˈet\">juliet</phoneme>"); break; case 'K': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈkiːlo\">kilo</phoneme>"); break; case 'L': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈliːmɑ\">lima</phoneme>"); break; case 'M': elements.Add("<phoneme alphabet=\"ipa\" ph=\"maɪk\">mike</phoneme>"); break; case 'N': elements.Add("<phoneme alphabet=\"ipa\" ph=\"noˈvembə\">november</phoneme>"); break; case 'O': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈɒskə\">oscar</phoneme>"); break; case 'P': elements.Add("<phoneme alphabet=\"ipa\" ph=\"pəˈpɑ\">papa</phoneme>"); break; case 'Q': elements.Add("<phoneme alphabet=\"ipa\" ph=\"keˈbek\">quebec</phoneme>"); break; case 'R': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈroːmiˑo\">romeo</phoneme>"); break; case 'S': elements.Add("<phoneme alphabet=\"ipa\" ph=\"siˈerə\">sierra</phoneme>"); break; case 'T': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈtænɡo\">tango</phoneme>"); break; case 'U': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈjuːnifɔːm\">uniform</phoneme>"); break; case 'V': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈvɪktə\">victor</phoneme>"); break; case 'W': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈwiski\">whiskey</phoneme>"); break; case 'X': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈeksˈrei\">x-ray</phoneme>"); break; case 'Y': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈjænki\">yankee</phoneme>"); break; case 'Z': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈzuːluː\">zulu</phoneme>"); break; case '0': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈzɪərəʊ\">zero</phoneme>"); break; case '1': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈwʌn\">one</phoneme>"); break; case '2': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈtuː\">two</phoneme>"); break; case '3': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈtriː\">tree</phoneme>"); break; case '4': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈfoʊ.ər\">fawer</phoneme>"); break; case '5': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈfaɪf\">fife</phoneme>"); break; case '6': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈsɪks\">six</phoneme>"); break; case '7': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈsɛvɛn\">seven</phoneme>"); break; case '8': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈeɪt\">eight</phoneme>"); break; case '9': elements.Add("<phoneme alphabet=\"ipa\" ph=\"ˈnaɪnər\">niner</phoneme>"); break; case '-': if (passDash) { elements.Add(" " + Properties.Phrases.dash + " "); } break; } } return string.Join(" ", elements).Trim(); } public static string sayAsLettersOrNumbers(string part, bool useLongNumbers = false, bool useICAO = false) { var matchConditions = new Regex(@"([A-Z])|(\d+)|([a-z])|(\S)"); var elements = new List<string>(); foreach (var match in matchConditions.Matches(part)) { var matchAsString = match.ToString(); if (long.TryParse(matchAsString, out long number)) { // Handle numbers if (useICAO) { elements.Add(ICAO(matchAsString)); } else if (!useLongNumbers) { foreach (var c in matchAsString) { elements.Add($"{c}"); } } else { // Handle leading zeros if (number > 0) { elements.AddRange(matchAsString.TakeWhile(s => s == '0').Select(s => s.ToString())); } // Handle the number elements.Add($"{number}"); } } else if (!(new Regex(@"\w").IsMatch(matchAsString))) { // Handle non-word and non-number characters foreach (var c in matchAsString) { if (matchAsString == "-") { elements.Add(Properties.Phrases.dash); } else if (matchAsString == ".") { elements.Add(Properties.Phrases.point); } else if (matchAsString == "+") { elements.Add(Properties.Phrases.plus); } else { elements.Add(matchAsString); } } } else { // Handle strings if (useICAO) { elements.Add(ICAO(matchAsString)); } else { foreach (var c in matchAsString) { elements.Add(@"<say-as interpret-as=""characters"">" + c + @"</say-as>"); } } } } return string.Join(" ", elements).Trim(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using HASRental.Models; using Microsoft.AspNetCore.Authorization; namespace HASRental.Controllers { public class VoziloController : Controller { private readonly NasContext _context; public VoziloController(NasContext context) { _context = context; } // GET: Vozilo public async Task<IActionResult> Index() { var nasContext = _context.Vozilo.Include(v => v.Proizvodjac).Include(v => v.TrenutnaLokacija).Include(v => v.VoziloKategorija); return View(await nasContext.ToListAsync()); } // GET: Vozilo/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var vozilo = await _context.Vozilo .Include(v => v.Proizvodjac) .Include(v => v.TrenutnaLokacija) .Include(v => v.VoziloKategorija) .FirstOrDefaultAsync(m => m.Id == id); if (vozilo == null) { return NotFound(); } return View(vozilo); } // GET: Vozilo/Create public IActionResult Create() { ViewData["ProizvodjacId"] = new SelectList(_context.Proizvodjac, "Id", "Naziv"); ViewData["TrenutnaLokacijaId"] = new SelectList(_context.Lokacija, "Id", "Grad"); ViewData["VoziloKategorijaId"] = new SelectList(_context.VoziloKategorija, "Id", "Ime"); return View(); } // POST: Vozilo/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles="Admin")] public async Task<IActionResult> Create([Bind("Id,VoziloKategorijaId,ProizvodjacId,TrenutnaLokacijaId,Model,GodinaProizvodnje,Kilometraza,Boja")] Vozilo vozilo) { if (ModelState.IsValid) { _context.Add(vozilo); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["ProizvodjacId"] = new SelectList(_context.Proizvodjac, "Id", "Naziv", vozilo.ProizvodjacId); ViewData["TrenutnaLokacijaId"] = new SelectList(_context.Lokacija, "Id", "Grad", vozilo.TrenutnaLokacijaId); ViewData["VoziloKategorijaId"] = new SelectList(_context.VoziloKategorija, "Id", "Ime", vozilo.VoziloKategorijaId); return View(vozilo); } // GET: Vozilo/Edit/5 [Authorize(Roles = "Admin")] public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var vozilo = await _context.Vozilo.FindAsync(id); if (vozilo == null) { return NotFound(); } ViewData["ProizvodjacId"] = new SelectList(_context.Proizvodjac, "Id", "Id", vozilo.ProizvodjacId); ViewData["TrenutnaLokacijaId"] = new SelectList(_context.Lokacija, "Id", "Id", vozilo.TrenutnaLokacijaId); ViewData["VoziloKategorijaId"] = new SelectList(_context.VoziloKategorija, "Id", "Id", vozilo.VoziloKategorijaId); return View(vozilo); } // POST: Vozilo/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize(Roles = "Admin")] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,VoziloKategorijaId,ProizvodjacId,TrenutnaLokacijaId,Model,GodinaProizvodnje,Kilometraza,Boja")] Vozilo vozilo) { if (id != vozilo.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(vozilo); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!VoziloExists(vozilo.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["ProizvodjacId"] = new SelectList(_context.Proizvodjac, "Id", "Id", vozilo.ProizvodjacId); ViewData["TrenutnaLokacijaId"] = new SelectList(_context.Lokacija, "Id", "Id", vozilo.TrenutnaLokacijaId); ViewData["VoziloKategorijaId"] = new SelectList(_context.VoziloKategorija, "Id", "Id", vozilo.VoziloKategorijaId); return View(vozilo); } // GET: Vozilo/Delete/5 [Authorize(Roles = "Admin")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var vozilo = await _context.Vozilo .Include(v => v.Proizvodjac) .Include(v => v.TrenutnaLokacija) .Include(v => v.VoziloKategorija) .FirstOrDefaultAsync(m => m.Id == id); if (vozilo == null) { return NotFound(); } return View(vozilo); } // POST: Vozilo/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [Authorize(Roles = "Admin")] public async Task<IActionResult> DeleteConfirmed(int id) { var vozilo = await _context.Vozilo.FindAsync(id); _context.Vozilo.Remove(vozilo); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } [Authorize(Roles = "Admin")] private bool VoziloExists(int id) { return _context.Vozilo.Any(e => e.Id == id); } } }
using System; using System.Collections.Generic; using System.Text; namespace Ex03.GarageLogic { public class Owner_Details { public enum eVehicleStatus { INPROCESS, FIXED, PAIDUP }; // Status types private string m_ownerName; private string m_ownerPhoneNumber; private Vehicle m_ownerVehicle; private eVehicleStatus m_currentVehicleStatus; public Owner_Details() { m_currentVehicleStatus = eVehicleStatus.INPROCESS; } public eVehicleStatus currentVehicleStatus { get { return m_currentVehicleStatus; } set { m_currentVehicleStatus = value; } } public Vehicle ownerVehicle { get { return m_ownerVehicle; } set { m_ownerVehicle = value; } } public string ownerName { get { return m_ownerName; } set { m_ownerName = value; } } public string ownerPhoneNumber { get { return m_ownerPhoneNumber; } set { m_ownerPhoneNumber = value; } } public List<string> QuestionsForOwner() // this function hold the list of quastion that related to the Owner Details { List<string> questionsForOwner = new List<string>(); questionsForOwner.Add("Please enter the owner's name and press 'Enter' "); questionsForOwner.Add("Please enter the phone number of the owner and press 'Enter' "); return questionsForOwner; } public void CheckOwnerDetailsInput(string i_input, int i_numberOfQuestion) // this function check the input from user according to the question number { switch (i_numberOfQuestion) { case 1: // question number 1 { CheckOwnersName(i_input); // call to function that check the owner's name input and update the data members break; } case 2: // question number 2 { CheckOwnersPhone(i_input); // call to function that check the phone number input and update the data members break; } } } public bool updateOwnerDetailsInput(string i_input, int i_numberOfQuestion) // this function updeate the Owner Details members { bool correctInput = true; // a boolean variable that checks whether the input from the user is correct switch (i_numberOfQuestion) { case 1: // question number 1 { m_ownerName = i_input; // updeate the data member break; } case 2: // question number 2 { m_ownerPhoneNumber = i_input; // updeate the data member break; } } return correctInput; } public void CheckOwnersName(string i_input) // this function check the Owners Name input and update the data members { if (i_input.CompareTo("") == 0) // if its an empty input { throw new ArgumentException("You have to write owner name "); } foreach (char letter in i_input) { if(!((letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z') || (letter == ' '))) // If input is not composed of letters and spaces { throw new ArgumentException("The name have to be only latters"); } } } public void CheckOwnersPhone(string i_input) // this function check the Owners Phone input and update the data members { if (i_input.CompareTo("") == 0) // if its an empty input { throw new ArgumentException("You have to write phone number"); } foreach (char letter in i_input) { if (!(letter <= '9' && letter >= '0')) // If the input is not composed of numbers only { throw new ArgumentException("The number have to be only numbers"); } } } public void UpdeateVehicleStatus(string i_statusInput) // this function updeate the vehicle status according to user input { try { m_currentVehicleStatus = (eVehicleStatus)Enum.Parse(typeof(eVehicleStatus), i_statusInput); // try to parss the input to enum } catch (ArgumentException Ex) { throw new ArgumentException("You have to choose one of the follwoing status: INPROCESS, FIXED, PAIDUP"); } } public void GetDetailesOwner(List<string> io_listOfDetailes) // this function add the Owner detailes to the list { io_listOfDetailes.Add(string.Format("Name:{0}", m_ownerName)); io_listOfDetailes.Add(string.Format("phone:{0}", m_ownerPhoneNumber)); io_listOfDetailes.Add(string.Format("Current Vehicle Status:{0}", m_currentVehicleStatus.ToString())); m_ownerVehicle.GetDetailesOwnerVehicle(io_listOfDetailes); } } }
using System; using System.Windows; using BSky.Lifetime; using BSky.Lifetime.Interfaces; using Microsoft.Win32; using BSky.Statistics.Common; using BlueSky.CommandBase; namespace BlueSky.Commands.Tools.Package { //initially it was copied from InstallPackageCommand.cs //04May2015 class UpdateBlueSkyPacakgesCommand : BSkyCommandBase { ILoggerService logService = LifetimeService.Instance.Container.Resolve<ILoggerService>(); protected override void OnPreExecute(object param) { } public const String FileNameFilter = "Package (BlueSky*.zip)|BlueSky*.zip"; protected override void OnExecute(object param) { //Window1 appwindow = LifetimeService.Instance.Container.Resolve<Window1>(); try { bool autoLoad = true, overwrite = true; OpenFileDialog openFileDialog = new OpenFileDialog(); //// Get initial Dir //// //string initDir = confService.GetConfigValueForKey("InitialDirectory"); //openFileDialog.InitialDirectory = initDir; openFileDialog.Filter = FileNameFilter; openFileDialog.Multiselect = true; bool? output = openFileDialog.ShowDialog(Application.Current.MainWindow); if (output.HasValue && output.Value) { string[] pkgfilenames = openFileDialog.FileNames; PackageHelperMethods phm = new PackageHelperMethods(); UAReturn r = phm.PackageFileInstall(pkgfilenames, autoLoad, overwrite);// PackageFileInstall(pkgfilenames);//openFileDialog.FileName); if (r != null && r.Success) { SendToOutputWindow(BSky.GlobalResources.Properties.Resources.InstallPkg, r.SimpleTypeData.ToString()); MessageBox.Show(BSky.GlobalResources.Properties.Resources.RestartToApplyChanges2, BSky.GlobalResources.Properties.Resources.RestartBSkyApp, MessageBoxButton.OK, MessageBoxImage.Warning); } else { if (r != null) { string msg = r.SimpleTypeData as string; SendToOutputWindow(BSky.GlobalResources.Properties.Resources.ErrInstallingRPkg, msg); } } ///Set initial Dir./// //initDir = Path.GetDirectoryName(openFileDialog.FileName); //confService.ModifyConfig("InitialDirectory", initDir); //confService.RefreshConfig(); } } catch (Exception ex) { MessageBox.Show(BSky.GlobalResources.Properties.Resources.ErrInstallingRPkg2, BSky.GlobalResources.Properties.Resources.ErrorOccurred); logService.WriteToLogLevel("Error:", LogLevelEnum.Error, ex); } } protected override void OnPostExecute(object param) { } } }
using System.Windows.Controls; namespace CODE.Framework.Wpf.Theme.Metro.StandardViews { /// <summary> /// Interaction logic for PeekImageAndText04.xaml /// </summary> public partial class PeekImageAndText04 : Grid { /// <summary> /// Initializes a new instance of the <see cref="PeekImageAndText04"/> class. /// </summary> public PeekImageAndText04() { InitializeComponent(); } } }
namespace Heists { using System; using System.Linq; public class StartUp { public static void Main() { var prices = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(long.Parse) .ToArray(); var totalExpenses = 0L; var totalEarnings = 0L; var totalProfit = 0L; while (true) { var lootAndExpenses = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); if (lootAndExpenses[0] == "Jail" && lootAndExpenses [1] == "Time") { break; } var jewels = '%'; var gold = '$'; var loot = lootAndExpenses[0].ToArray(); var expenses = Convert.ToInt64(lootAndExpenses[1]); for (int i = 0; i < loot.Length; i++) { if (loot[i] == jewels) { totalEarnings += prices[0]; } if (loot[i] == gold) { totalEarnings += prices[1]; } } totalExpenses += expenses; } totalProfit = totalEarnings - totalExpenses; if (totalProfit >= 0) { Console.WriteLine($"Heists will continue. Total earnings: {totalProfit}."); } else { Console.WriteLine($"Have to find another job. Lost: {Math.Abs(totalProfit)}."); } } } }
using System; namespace Plugin.XamJam.BugHound { /// <summary> /// Interface for XamJam.BugHound /// </summary> public interface IBugHound { BugHound.Tracker CreateTracker(double probability = 0.1); /// <summary> /// <see cref="Level.Trace"/> /// </summary> /// <param name="message">the log message</param> void Trace(string message); /// <summary> /// <see cref="Level.Debug"/> /// </summary> /// <param name="message">the log message</param> void Debug(string message); /// <summary> /// <see cref="Level.Info"/> /// </summary> /// <param name="message">the log message</param> void Info(string message); /// <summary> /// <see cref="Level.Warn"/> /// </summary> /// <param name="message">the log message</param> /// <param name="ex">the optional applicable exception</param> void Warn(string message, Exception ex = null); /// <summary> /// <see cref="Level.Error"/> /// </summary> /// <param name="message">the log message</param> /// <param name="ex">the optional applicable exception</param> void Error(string message, Exception ex = null); /// <summary> /// Logs a message and, optionally, an exception, at the specified level. /// </summary> /// <param name="level">the log level for this log message</param> /// <param name="message">the log message</param> /// <param name="ex">the optional applicable exception</param> void Log(Level level, string message, Exception ex = null); /// <summary> /// The Hound records the exception at <see cref="Level.Error"/> level and rethrows it. /// </summary> /// <param name="exceptionMessage">a custom message helping diagnose the exception</param> /// <param name="ex">the inner (aka caused-by) exception, if any</param> /// <param name="level">a custom level other than the default <see cref="Level.Error"/></param> void Throw(string exceptionMessage = null, Exception ex = null, Level level = null); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cracking { class NodeFactory { public static Node createList() { Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); n1.Next = n2; n2.Next = n3; n3.Next = n4; n4.Next = n5; return n1; } public static Node createList(int [] a) { Node head = null; Node tail = null; for (int i = 0; i<a.Length; i++) { Node n = new Node(a[i]); if (head == null) { head = n; tail = n; } else { tail.Next = n; tail = n; } } return head; } public static Node createUnsortedList() { Node n1 = new Node(3); Node n2 = new Node(4); Node n3 = new Node(5); Node n4 = new Node(1); Node n5 = new Node(0); n1.Next = n2; n2.Next = n3; n3.Next = n4; n4.Next = n5; return n1; } public static Node createListDups() { Node n1 = new Node(1); Node n2 = new Node(1); Node n3 = new Node(1); Node n4 = new Node(4); Node n5 = new Node(5); n1.Next = n2; n2.Next = n3; n3.Next = n4; n4.Next = n5; return n1; } public static void traverseList(Node head) { Node n = head; while (n != null) { Console.Write(n); n = n.Next; } Console.WriteLine(); } public static void print(Node head) { Node n = head; while (n != null) { Console.Write(n); n = n.Next; } Console.WriteLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectEuler17 { class Program { static void Main(string[] args) { //If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? List<int> units = new List<int>(); int one, two, three, four, five, six, seven, eight, nine; units.Add(one = "one".Length); units.Add(two = "two".Length); units.Add(three = "three".Length); units.Add(four = "four".Length); units.Add(five = "five".Length); units.Add(six = "six".Length); units.Add(seven = "seven".Length); units.Add(eight = "eight".Length); units.Add(nine = "nine".Length); List<int> teens = new List<int>(); int ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen; teens.Add(ten = "ten".Length); teens.Add(eleven = "eleven".Length); teens.Add(twelve = "twelve".Length); teens.Add(thirteen = "thirteen".Length); teens.Add(fourteen = "fourteen".Length); teens.Add(fifteen = "fifteen".Length); teens.Add(sixteen = "sixteen".Length); teens.Add(seventeen = "seventeen".Length); teens.Add(eighteen = "eighteen".Length); teens.Add(nineteen = "nineteen".Length); List<int> tens = new List<int>(); int twenty, thirty, fourty, fifty, sixty, seventy, eighty, ninety; tens.Add(twenty = "twenty".Length); tens.Add(thirty = "thirty".Length); tens.Add(fourty = "forty".Length); tens.Add(fifty = "fifty".Length); tens.Add(sixty = "sixty".Length); tens.Add(seventy = "seventy".Length); tens.Add(eighty = "eighty".Length); tens.Add(ninety = "ninety".Length); int hundred = "hundred".Length; int and = "and".Length; Int64 answer = 0; int oneToOneHundred = 0; foreach (int a in units) oneToOneHundred += a; foreach (int b in teens) oneToOneHundred += b; foreach (int c in tens) { oneToOneHundred += c; foreach (int d in units) oneToOneHundred += c + d; } answer += oneToOneHundred; foreach (int e in units) { answer += e + hundred; answer += 99 * (e + hundred + and); answer += oneToOneHundred; } answer += "onethousand".Length; Console.WriteLine(answer); Console.ReadLine(); } } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq.Expressions; using UnityEngine; using UnityEngine.VR; public class Graph : MonoBehaviour { private static Graph m_instance = null; // Graph 정보 public List<Node> node_List = new List<Node>(); private int nodeIndex = 0; // 생성되는 노드에 매겨줄 번호 값 변수 // 기타 변수 private int searchIndex = 0; // 탐색 실행 중 번호 지정을 위한 값 변수 public bool is_Freemode = false; public bool is_Movemode = true; public static Graph GetInstance() { if(m_instance == null) { return null; } return m_instance; } void Awake() { if (m_instance == null) { m_instance = this; } if(node_List == null) { Debug.LogError(name + " : Warning! Node List doesn't exist!"); } } public KeyValuePair<Stack<Node>, float> AStar(Node startNode, Node goalNode) { // 예외 처리 if (startNode == null || goalNode == null) { return new KeyValuePair<Stack<Node>, float>(null, -1); } KeyValuePair<float, Edge>[] distances = new KeyValuePair<float, Edge>[node_List.Count]; for (int i = 0; i < node_List.Count; i++) { distances[i] = new KeyValuePair<float, Edge>(float.MaxValue, null); } distances[startNode.id] = new KeyValuePair<float, Edge>(0, null); Priority_Queue.SimplePriorityQueue<Node> pq = new Priority_Queue.SimplePriorityQueue<Node>(); pq.Enqueue(startNode, 0); int visitCount = 0; // 노드 방문횟수 측정을 위한 변수 // A* (Dijkstra) 알고리즘 while (pq.Count > 0) { Node current = pq.First; float dist = pq.GetPriority(current); current.GetComponent<MeshRenderer>().material.color = new Color(0, 0, 1); pq.Dequeue(); visitCount++; if (current == goalNode) // 목표까지 탐색이 완료되면 탈출 { break; } if (dist < distances[current.id].Key) { continue; } for (int i = 0; i < current.edges.Count; i++) { Node next = null; if (current == current.edges[i].left_Node) { next = current.edges[i].right_Node; } else if (current == current.edges[i].right_Node) { next = current.edges[i].left_Node; } else { Debug.LogError("Dijkstra critical error occured!"); return new KeyValuePair<Stack<Node>, float>(null, -1); } // 이어지는 노드가 장애물로 되어있을 경우 처리하지 않음(값을 무한대로 유지) if(next.is_Obstacle) { continue; } float nextDist = dist + current.edges[i].weight + Vector3.Distance(next.transform.position, goalNode.transform.position); if (nextDist < distances[next.id].Key) { distances[next.id] = new KeyValuePair<float, Edge>(nextDist, current.edges[i]); pq.Enqueue(next, nextDist); } } } // 최단 경로 산출(distance 배열 edge 역행) Stack<Node> pathStack = new Stack<Node>(); Node reversingNode = goalNode; int reversingIndex = goalNode.id; while (reversingNode != startNode) { // 경로 표시 pathStack.Push(reversingNode); VisitNode(reversingNode); distances[reversingIndex].Value.GetComponent<MeshRenderer>().material.color = new Color(1, 0, 0); if (reversingNode == distances[reversingIndex].Value.left_Node) { reversingNode = distances[reversingIndex].Value.right_Node; } else if (reversingNode == distances[reversingIndex].Value.right_Node) { reversingNode = distances[reversingIndex].Value.left_Node; } else { Debug.LogError("Dijkstra : Critical error occured!"); break; } reversingIndex = reversingNode.id; } pathStack.Push(reversingNode); VisitNode(reversingNode); Debug.Log("A* visits node " + visitCount + " time(s)!"); return new KeyValuePair<Stack<Node>, float>(pathStack, distances[goalNode.id].Key); } public int GetNodeID() { nodeIndex++; return nodeIndex - 1; } public Node GetNodeFromID(int id) { for(int i = 0; i < node_List.Count; i++) { if(node_List[i].id == id) { return node_List[i]; } } return null; } private void VisitNode(Node node) { node.is_Visited = true; node.gameObject.GetComponent<MeshRenderer>().material.color = new Color(1, 0, 0); node.gameObject.GetComponentInChildren<TextMesh>().text = string.Format("{0}", searchIndex + 1); searchIndex++; } public void SearchClear() { foreach(Node node in node_List) { node.is_Visited = false; node.gameObject.GetComponent<MeshRenderer>().material.color = new Color(1, 1, 1); node.gameObject.GetComponentInChildren<TextMesh>().text = string.Empty; for(int i = 0; i < node.edges.Count; i++) { node.edges[i].GetComponent<MeshRenderer>().material.color = new Color(0, 0, 0); } } searchIndex = 0; } public void AllClear() { foreach(Node node in node_List) { node.is_Obstacle = false; } SearchClear(); } public void SetFreemode(bool value) { is_Freemode = value; } }
using RRExpress.Common.Extends; using System; using System.Configuration; using System.Linq; namespace RRExpress.Moq.Auth { /// <summary> /// /// </summary> [Obsolete("只用于模拟, 请不要使用")] public class UsersConfig : ConfigurationSection { [ConfigurationProperty("", IsDefaultCollection = true)] public Users Users { get { return (Users)this[""]; } } } [Obsolete("只用于模拟, 请不要使用")] public class Users : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new User(); } protected override object GetElementKey(ConfigurationElement element) { return ((User)element).ID; } public User Get(int id) { var item = (User)this.BaseGet(id); return item; } public User Get(string userName) { return this.Cast<User>().FirstOrDefault(u => u.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase)); } } [Obsolete("只用于模拟, 请不要使用")] public class User : ConfigurationElement { protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) { return true; } protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader) { return true; } /// <summary> /// Key /// </summary> [ConfigurationProperty("id", IsRequired = true)] public int ID { get { return this["id"].ToString().ToInt(); } set { this["id"] = value; } } /// <summary> /// /// </summary> [ConfigurationProperty("userName", IsRequired = true)] public string UserName { get { return this["userName"].ToString(); } set { this["userName"] = value; } } [ConfigurationProperty("password", IsRequired = true)] public string Password { get { return this["password"].ToString(); } set { this["password"] = value; } } } }
using BuisinessLogic.Interfaces; using System; using System.Collections.Generic; using System.Text; using CryptoHelper; namespace BuisinessLogic.Implementations { public class CryptoHelperBsLogic : ICryptoHelper { public string HashPassword(string password) { return Crypto.HashPassword(password); } public bool VerifyPassword(string hash, string password) { return Crypto.VerifyHashedPassword(hash, password); } } }
using System; using Anywhere2Go.DataAccess.Object; using Anywhere2Go.DataAccess; using Anywhere2Go.Library; using Anywhere2Go.Business.Master; namespace Claimdi.WCF.Public { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TSoftService" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select TSoftService.svc or TSoftService.svc.cs at the Solution Explorer and start debugging. public class TSoftService : ITSoftService { public BaseResult<string> GetDamageChoice() { throw new NotImplementedException(); } //public BaseResult<bool> UpdateTaskProcess(string tradvertiseid, int tsoft_status_id) //{ // BaseResult<bool> res = new BaseResult<bool>(); // try // { // APIUpdateTaskProcessTSoft obj = new APIUpdateTaskProcessTSoft(); // obj.TRAdvertiseId = tradvertiseid; // obj.TSoftStatusId = tsoft_status_id; // if (obj.TSoftStatusId == 0) // { // obj.TSoftStatusId = null; // } // var validationResult = DataAnnotation.ValidateEntity<APIUpdateTaskProcessTSoft>(obj); // if (validationResult.HasError) // { // res.StatusCode = Constant.ErrorCode.RequiredData; // res.Message = validationResult.HasErrorMessage; // } // else // { // TaskLogic task = new TaskLogic(); // var result = task.UpdateTaskProcessByTSoftStatusID(obj.TRAdvertiseId, obj.TSoftStatusId.Value); // if (result.Result) // { // res.Result = result.Result; // } // else // { // res.StatusCode = result.StatusCode; // res.Message = result.Message; // res.SystemErrorMessage = result.SystemErrorMessage; // } // } // } // catch (Exception ex) // { // res.StatusCode = Constant.ErrorCode.SystemError; // res.Message = Constant.ErrorMessage.SystemError; // res.SystemErrorMessage = ex.Message; // } // return res; //} } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class SpeedMeter : MonoBehaviour { public Rigidbody objectToMeasure; public float maxVelocity = 10.0f; public bool disallowBackwards = false; private Image image; void Start () { image = GetComponent<Image> (); } void Update () { image.fillAmount = objectToMeasure.velocity.magnitude / maxVelocity; } }
namespace Timer { using System; class Program { static void Main() { Timer timer = new Timer(1); timer.SomeMethods += FirstTestMethod; timer.SomeMethods += SecondTestMethod; timer.ExecuteMethods(); } public static void FirstTestMethod() { Console.Write("Tick-"); } public static void SecondTestMethod() { Console.WriteLine("Tock"); } } }
namespace chat.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class User_Picture { public User_Picture() { Loves = new HashSet<User_Picture_Like>(); } public long Id { get; set; } [StringLength(500)] public string Name { get; set; } [Required] public string Path { get; set; } [Required] public string ThumbnailPath { get; set; } [DataType(DataType.DateTime)] public DateTime Date { get; set; } public long? Profile_Id { get; set; } public virtual User_Profile Profile { get; set; } public virtual ICollection<User_Picture_Like> Loves { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using oleDB = System.Data.OleDb; namespace lab_074 { class Program { static void Main(string[] args) { var connection = new oleDB.OleDbConnection("Data Source=\"e:\\vic.mdb\";User ID=Admin;Provider=\"Microsoft.Jet.OLEDB.4.0\";"); connection.Open(); var command = new oleDB.OleDbCommand("Delete * From [Phones] Where fio Like 'Св%'", connection); int i = command.ExecuteNonQuery(); if (i > 0) MessageBox.Show("Записи, содержащие в поле ФИО фрагмент 'Св*', удалены"); if (i == 0) MessageBox.Show("Запись, содержащая в поле ФИО фрагмент 'Св*', не найдена"); connection.Close(); } } }
using Microsoft.AspNetCore.SignalR; namespace Amf.Ultima.Api.HubConfig { public class UltimaHub : Hub { } }
using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using LittleFlowerBot.Repositories; namespace LittleFlowerBot.Models.Renderer { public class LineNotifySender : ITextRenderer { public string SenderId { get; set; } private readonly IHttpClientFactory _httpClientFactory; private readonly ISubscriptionRepository _subscriptionRepository; private readonly string _notifyApi = "https://notify-api.line.me/api/notify"; public LineNotifySender(IHttpClientFactory httpClientFactory, ISubscriptionRepository subscriptionRepository) { _httpClientFactory = httpClientFactory; _subscriptionRepository = subscriptionRepository; } public void Render(string text) { var receiver = _subscriptionRepository.Get(SenderId).Receiver; var requestMessage = new HttpRequestMessage(HttpMethod.Post, _notifyApi) { Content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("message", $"\n{text}") }) }; requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", receiver); _httpClientFactory.CreateClient().SendAsync(requestMessage); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TopInfos : BasePanel { int oldValue; int changeValue; public void Init(int changeValue) { oldValue = GameRoot.instance.playerModel.Coin- changeValue; this.changeValue = changeValue; GetControl<Text>("Text_ChangeValue").text = changeValue.ToString(); GetControl<Text>("Text_Coin").text = oldValue.ToString(); if (changeValue == 0) { GetControl<Text>("Text_ChangeValue").enabled = false; } Invoke("HideThisCounter", 6f); } public void HideThisCounter() { try { UIManager.GetInstance().HidePanel("TopInfos"); } catch { Debug.Log("BUG"); } Destroy(this.gameObject); } public void SetNewCoinValue() { GetControl<Text>("Text_Coin").text = (oldValue + changeValue).ToString(); } public void HideThis() { UIManager.GetInstance().HidePanel("TopInfos"); } }
/************************************** * * A Generic Button that have 2 states, * Events are called to the listeners depending * on what state the button is in. Interacting with * the button toggles the button between two states * **************************************/ using System.Collections; using System.Collections.Generic; using Sirenix.OdinInspector; using UnityEngine; using UnityEngine.Events; namespace DChild.Gameplay.Environment { [RequireComponent(typeof(Collider2D))] public class SwitchButton : MonoBehaviour, IInteractable { [SerializeField] [Tooltip("Delay Between Interactions")] [MinValue(0f)] private float m_interactionDelay = 0.1f; [SerializeField] private UnityEvent m_onEvents; [SerializeField] private UnityEvent m_offEvents; [SerializeField] [HideInInspector] private Collider2D m_collider; private bool m_isOn; public Vector3 position => transform.position; public IInteractable Interact(Player.Player player) { if (m_isOn) { m_offEvents.Invoke(); m_isOn = false; } else { m_onEvents.Invoke(); m_isOn = true; } StartCoroutine(InteractionDelay()); return this; } private IEnumerator InteractionDelay() { m_collider.enabled = false; yield return new WaitForSeconds(m_interactionDelay); m_collider.enabled = true; } private void OnDrawGizmosSelected() { Gizmos.color = Color.green; for (int i = 0; i < m_onEvents.GetPersistentEventCount(); i++) { if (m_onEvents.GetPersistentTarget(i) != null) { Gizmos.DrawLine(transform.position, ((Component)m_onEvents.GetPersistentTarget(i)).transform.position); } } Gizmos.color = Color.red; for (int i = 0; i < m_offEvents.GetPersistentEventCount(); i++) { if (m_offEvents.GetPersistentTarget(i) != null) { Gizmos.DrawLine(transform.position, ((Component)m_offEvents.GetPersistentTarget(i)).transform.position); } } } private void OnValidate() { m_collider = GetComponent<Collider2D>(); } } }
using System; using UnityEngine; using HoloToolkit.Unity.InputModule; public class TransformGizmo : MonoBehaviour { [Tooltip("The Transform to be controlled by the Gizmo")] public Transform RootTransform; [Tooltip("The Transform containing the mdoel geometry")] public Transform TargetTransform; [Tooltip("The GameObject to be attached to the Scale handle")] public GameObject ScalePrefab; [Tooltip("The GameObject to be attached to the Rotate handle")] public GameObject RotatePrefab; [Tooltip("The GameObject to be attached to the Remove handle")] public GameObject RemovePrefab; [Tooltip("The Material assigned to the Box")] public Material Material; /// <summary> /// Keeps track of which face we are addressing. /// </summary> private enum BoxFace { Top, Bottom, Side } /// <summary> /// A matrix of vectors for translating one point to four corners. /// </summary> private static readonly Vector3[] CornerScales = new Vector3[] { new Vector3( 1, 1, 1 ), new Vector3( -1, 1, 1 ), new Vector3( -1, 1,-1 ), new Vector3( 1, 1,-1 ) }; /// <summary> /// The calculated corners of the bounding box. /// </summary> private Vector3[,] corners; private Bounds bounds; /// <summary> /// The bounds of the targeted object. /// </summary> public Bounds Bounds { get { return this.bounds; } } #region MonoBehaviour Members /// <summary> /// MonoBehaviour Members /// </summary> private void Start() { this.bounds = new Bounds(); ExpandBounds(this.TargetTransform); this.corners = LocateCorners(this.bounds); CreateTransformBox(); this.RootTransform.localScale /= (this.bounds.size.magnitude / 5); this.RootTransform.position += new Vector3(0, 0, 20); this.gameObject.SetActive(false); } #endregion /// <summary> /// Recursively walk the scene root expanding the bounds of the gizmo. /// </summary> /// <param name="parent"></param> private void ExpandBounds(Transform parent) { foreach (Transform child in parent) { var filter = child.GetComponent<MeshFilter>(); if (filter != null) { var mesh = filter.mesh; if (mesh == null) continue; this.bounds.Encapsulate(mesh.bounds); } ExpandBounds(child); } } /// <summary> /// Method to remove scaling from an object. /// </summary> /// <param name="targetObject"></param> private void NormalizeObject(GameObject targetObject) { var targetSize = targetObject.GetComponent<MeshFilter>().mesh.bounds.size; var maxSize = 1 / Mathf.Max(targetSize.x, Mathf.Max(targetSize.y, targetSize.z)); targetObject.transform.localScale = new Vector3(maxSize, maxSize, maxSize); } /// <summary> /// Method to create subcomponents of TransformBox. /// </summary> private void CreateTransformBox() { CreateFrame("Edge"); CreateTranslateGizmo("TranslateGizmo"); CreateScaleGizmos("ScaleGizmo", BoxFace.Top); CreateScaleGizmos("ScaleGizmo", BoxFace.Bottom); CreateRotateGizmos("RotateGizmo", BoxFace.Side); } /// <summary> /// Method to add components to the TransformGizmo to enable Translation. /// </summary> /// <param name="name"></param> private void CreateTranslateGizmo(string name) { this.gameObject.AddComponent<BoxCollider>().size = this.bounds.size; this.gameObject.AddComponent<CursorTransform>().CursorType = CursorTransformEnum.Translate; this.gameObject.AddComponent<HandTranslate>().HostTransform = this.RootTransform; } /// <summary> /// Method to generate rotate gizmos for the four sides of the TransformBox /// </summary> /// <param name="name"></param> /// <param name="face"></param> void CreateRotateGizmos(string name, BoxFace face) { var gizmo = this.RotatePrefab; for (int i = 0; i < 4; ++i) { var position = (this.corners[0, i] + this.corners[1, i]) / 2; var instance = Instantiate(gizmo, position, Quaternion.identity); ConfigureGizmo(instance); instance.AddComponent<HandRotate>().HostTransform = this.RootTransform; instance.name = name; } } /// <summary> /// Method to generate scale gizmos for the four sides of the TransformBox /// </summary> /// <param name="name"></param> /// <param name="face"></param>g void CreateScaleGizmos(string name, BoxFace face) { var gizmo = this.ScalePrefab; for (int i = 0; i < 4; ++i) { var position = this.corners[(int)face, i]; var instance = Instantiate(gizmo, position, Quaternion.Euler(0, 180 - i * 90, (int)face * 90 - 90)); ConfigureGizmo(instance); instance.AddComponent<HandScale>().HostTransform = this.RootTransform; instance.name = name; } } /// <summary> /// Generate the Remove handle for the TransformBox /// </summary> /// <param name="name"></param> /// <param name="face"></param> void CreateRemoveGizmo(string name, BoxFace face) { var gizmo = this.RemovePrefab; var position = (this.corners[0, 0] + this.corners[0, 1]) / 2; var instance = Instantiate(gizmo, position, Quaternion.identity); ConfigureGizmo(instance); instance.name = name; } /// <summary> /// Method to set the Transforms and Components of each gizmo /// </summary> /// <param name="gizmo"></param> /// <param name="action"></param> private void ConfigureGizmo(GameObject gizmo) { var scaleVector = Vector3.one * (this.bounds.size.magnitude / 40); gizmo.transform.localScale = scaleVector; gizmo.transform.parent = this.transform; } /// <summary> /// Method to build the outline of the bouding box /// </summary> /// <returns></returns> private void CreateFrame(string name) { CreateLoop(this.gameObject, this.corners, name, BoxFace.Top); CreateLoop(this.gameObject, this.corners, name, BoxFace.Bottom); CreateRing(this.gameObject, this.corners, name, BoxFace.Side); } /// <summary> /// Method to generate the lines connecting faces /// </summary> /// <param name="parent"></param> /// <param name="corners"></param> /// <param name="name"></param> /// <param name="face"></param> private void CreateRing(GameObject parent, Vector3[,] corners, string name, BoxFace face) { for (int j = 0; j < 4; ++j) { var vectors = new Vector3[] { corners[0, j], corners[1, j] }; var line = new GameObject(name); AddLineRenderer(line).SetPositions(vectors); line.transform.parent = parent.transform; } } /// <summary> /// Method to generate the closed polygons for faces /// </summary> /// <param name="parent"></param> /// <param name="corners"></param> /// <param name="name"></param> /// <param name="face"></param> private void CreateLoop(GameObject parent, Vector3[,] corners, string name, BoxFace face) { for (int j = 0; j < 4; ++j) { int k = ((j + 1) % 4 == 0) ? 0 : (j + 1); var vectors = new Vector3[] { corners[(int)face, j], corners[(int)face, k] }; var line = new GameObject(name); AddLineRenderer(line).SetPositions(vectors); line.transform.parent = parent.transform; } } /// <summary> /// Method to create a LineRenderer component /// </summary> /// <param name="line"></param> /// <returns></returns> private LineRenderer AddLineRenderer(GameObject line) { var renderer = line.AddComponent<LineRenderer>(); renderer.widthMultiplier = 0.02f; renderer.useWorldSpace = false; renderer.numPositions = 2; renderer.material = this.Material; return renderer; } /// <summary> /// Method to derive the corner points of the bounding box based /// on the target object's bounds /// </summary> /// <param name="bounds"></param> /// <returns></returns> private static Vector3[,] LocateCorners(Bounds bounds) { var sign = 1; var corners = new Vector3[2, 4]; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 4; ++j) { int k = j + i * 2; k = (k > 3) ? k - 4 : k; var vector = Vector3.Scale(CornerScales[j], bounds.extents) * sign; corners[i, k] = CreatePoint(bounds.center, vector); } sign *= -1; } return corners; } /// <summary> /// Method to generate a vector from two other vectors. /// </summary> /// <param name="center"></param> /// <param name="vector"></param> /// <returns></returns> private static Vector3 CreatePoint(Vector3 center, Vector3 vector) { return center + vector; } }
using System; using System.Collections.Generic; using System.Linq; namespace KnightBilGraph { class Algo { public bool BFS(ref Node src, ref Node dest) { var queue = new List<Node>(); src.IsChecked = true; queue.Add(src); // standard BFS algorithm while (queue.Count != 0) { //queue = queue.OrderBy(p => p.Distance).ToList(); var current = queue.First(); queue.RemoveAt(0); current.IsChecked = true; foreach (var neighbour in current.Neighbours) { if (!neighbour.IsChecked) { //neighbour.IsChecked = true; queue.Add(neighbour); if (neighbour.Distance > current.Distance + 1) { neighbour.previous = current; neighbour.Distance = current.Distance + 1; } } } } if (dest.previous == null) return false; else return true; } public List<Node> ShortestDistance(ref Node src, ref Node dest) { if (BFS(ref src, ref dest) == false) { Console.WriteLine("Given source and destination are not connected"); return null; } // vector path stores the shortest path List<Node> path = new List<Node>(); Node current = dest; path.Add(current); while (current.previous != null) { path.Add(current.previous); current = current.previous; } return path; } } }
namespace Infrostructure.Enums { public enum ValidateForPaymentMethodEnum { Bought, NullProducts, Success } }
using System; using System.Linq; using System.Web.Mvc; using ApartmentApps.Api; using ApartmentApps.Api.Modules; using ApartmentApps.Api.ViewModels; using ApartmentApps.API.Service.Controllers; using ApartmentApps.Data; using ApartmentApps.Data.Repository; using ApartmentApps.Portal; using ApartmentApps.Portal.Controllers; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ninject; using MaitenanceRequestModel = ApartmentApps.Portal.Controllers.MaitenanceRequestModel; namespace ApartmentApps.Tests { [TestClass] public class MaitenanceRequestsControllerTests : PropertyControllerTest<MaitenanceRequestsController> { [TestInitialize] public override void Init() { base.Init(); Context.Kernel.Bind<ApartmentApps.API.Service.Controllers.MaitenanceController>().ToSelf(); ApiController = Context.Kernel.Get<API.Service.Controllers.MaitenanceController>(); } public MaitenanceController ApiController { get; set; } [TestMethod] public void TestApi() { SubmitMaintenanceRequest(); var result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); var apiResult = ApiController.Get(Convert.ToInt32(result.Id)); } [TestMethod] public void TestProcess() { SubmitMaintenanceRequest(); var result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); Assert.IsNotNull(result, "Maintenance Request Create Not Working"); Controller.StartRequest(new MaintenanceStatusRequestModel() { Id = Convert.ToInt32(result.Id), Comments = "Test Pause" }); result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); Assert.IsTrue(result != null && result.StatusId == "Started"); Controller.PauseRequest(new MaintenanceStatusRequestModel() { Id = Convert.ToInt32(result.Id), Comments = "Test Pause" }); result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); Assert.IsTrue(result != null && result.StatusId == "Paused"); Controller.StartRequest(new MaintenanceStatusRequestModel() { Id = Convert.ToInt32(result.Id), Comments = "Restarting" }); result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); Assert.IsTrue(result != null && result.StatusId == "Started"); Controller.CompleteRequest(new MaintenanceStatusRequestModel() { Id = Convert.ToInt32(result.Id), Comments = "Complete" }); result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); Assert.IsTrue(result != null && result.StatusId == "Complete"); } [TestMethod] public void TestAssign() { SubmitMaintenanceRequest(); var result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); Assert.IsNotNull(result, "Maintenance Request Create Not Working"); Controller.AssignRequestSubmit( new AssignMaintenanceEditModel() { Id = result.Id, AssignedToId = Context.UserContext.UserId }); result = Context.Kernel.Get<MaintenanceService>().GetAll<MaintenanceRequestViewModel>().FirstOrDefault(); Assert.IsNotNull(result); Assert.AreEqual(Context.UserContext.UserId, result.AssignedToId); // Submit another request to test the list SubmitMaintenanceRequest(); var config = Context.Kernel.Get<ConfigProvider<MaintenanceConfig>>().Config; config.SupervisorMode = true; var controllerRequestList = ApiController.ListRequests(); Assert.AreEqual(2,controllerRequestList.Count()); config.SupervisorMode = false; controllerRequestList = ApiController.ListRequests(); // Assert.AreEqual(2,controllerRequestList.Count()); } private void SubmitMaintenanceRequest() { var editModel = Context.Kernel.Get<MaitenanceRequestModel>();// new MaitenanceRequestModel() { editModel.Comments = "Here is my new maintenance request"; }; editModel.MaitenanceRequestTypeId = Convert.ToInt32(editModel.MaitenanceRequestTypeId_Items.First().Id); editModel.UnitId = Convert.ToInt32(editModel.UnitId_Items.First().Id); editModel.PermissionToEnter = true; editModel.PetStatus = PetStatus.YesContained; Controller.SubmitRequest(editModel); } [TestCleanup] public override void DeInit() { RemoveAll<MaintenanceRequestCheckin>(); RemoveAll<MaitenanceRequest>(); base.DeInit(); } } [TestClass] public class UserManagementTests : PropertyControllerTest<UserManagementController> { [TestInitialize] public override void Init() { base.Init(); //Context.Kernel.Bind<UserManagementController>().ToSelf(); } [TestMethod] public void TestCreateUser() { var data = new UserFormModel(Context.Kernel.Get<UnitService>()) { Email = $"{Guid.NewGuid()}@aol-aol.com", FirstName = "Bla", LastName = "Bla", Password = "bla", PhoneNumber = "555-555-5555", }; data.SelectedRoles = new[] {"Resident"}.ToList(); var unit = data.UnitItems.FirstOrDefault(); if (unit != null) data.UnitId = Convert.ToInt32(unit.Id); Controller.UserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(DbContext)); var result = Controller.SaveUser(data).Result; var userRepo = Context.Kernel.Get<IRepository<ApplicationUser>>(); var user = userRepo.GetAll().FirstOrDefault(p => p.Email == data.Email); Assert.IsNotNull(user,"User is null"); } [TestCleanup] public override void DeInit() { base.DeInit(); } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace MergeSort { public class PassingCarsService { public void ConsoleRun() { //Array //var array = string.Empty; //while (array.ToLower() != "exit") //{ // Console.WriteLine("Enter an array: "); // array = Console.ReadLine(); // if (array == "exit") // break; // Console.WriteLine("Enter number of times to shift: "); // var line2 = Console.ReadLine(); // if (line2 == "exit") // break; // else // { // int[] arr = Array.ConvertAll(array.Split(" "), int.Parse); // var outputArray = MyMethod(arr, Convert.ToInt32(line2)); // string output = outputArray[0].ToString(); // for (int i = 1; i < arr.Length; i++) // { // output = output + ", " + outputArray[i].ToString(); // } // Console.WriteLine($"Output: {output}"); // } //} } public class Car { public int Direction { get; set; } public int Location { get; set; } } public int GetPairs(int[] arr) { var pairCount = 0; var oneCount = 0; for (int i = 0; i < arr.Length; i++) { if (arr[i] == 1) oneCount++; } for (int i = 0; i < arr.Length; i++) { if (arr[i] == 0) pairCount += oneCount; else oneCount--; if (pairCount > 1000000000) return -1; } return pairCount; } public int GetPairsFast(int[] arr) { var pairCount = 0; var zeroCount = 0; for (int i = 0; i < arr.Length; i++) { if (arr[i] == 0) zeroCount++; else if (zeroCount > 0) pairCount += zeroCount; if (pairCount > 1000000000) return -1; } return pairCount; } public int GetPairsSlow2(int[] arr) { var hash = new HashSet<Car>(); var pairCount = 0; for (int i = 0; i < arr.Length; i++) { hash.Add(new Car() { Direction = arr[i], Location = i }); } for (int i = 0; i < arr.Length; i++) { if (arr[i] == 0) pairCount += hash.Count(x => x.Location > i && x.Direction == 1); } return pairCount > 1000000000 ? -1 : pairCount; } public int GetPairsSlow(int[] arr) { var pairCount = 0; for (int i = 0; i < arr.Length; i++) { for (int j = i + 1; j < arr.Length; j++) { if (arr[i] == 0 && arr[j] == 1) { pairCount++; } } } return pairCount > 1000000000 ? -1 : pairCount; } } [TestFixture] public class PassingCarsServiceTests { public PassingCarsService service = new PassingCarsService(); [Test] public void GetPairsTest1() { var givenArray = new int[] { 0, 1, 0, 1, 1 }; var expectedArray = 5; Assert.AreEqual(expectedArray, service.GetPairs(givenArray)); } [Test] public void GetPairsTest2() { var givenArray = new int[] { 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0 }; ; var expectedArray = 13; Assert.AreEqual(expectedArray, service.GetPairs(givenArray)); } } }
using System; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Atc.CodeAnalysis.CSharp.SyntaxFactories { public static class SyntaxArgumentFactory { public static ArgumentSyntax Create(string argumentName) { if (argumentName == null) { throw new ArgumentNullException(nameof(argumentName)); } return SyntaxFactory.Argument( SyntaxFactory.IdentifierName(argumentName)); } } }
using System.Text; namespace Witsml.Extensions { public static class ObjectExtensions { public static string PrintProperties(this object obj) { var props = obj.GetType().GetProperties(); var sb = new StringBuilder(); foreach (var p in props) { sb.AppendLine(p.Name + ": " + p.GetValue(obj, null)); } return sb.ToString(); } } }
using System.ComponentModel; using System.Reflection; namespace IRAP.UFMPS.Library { public enum TThreadStartMark { [Description("文件导入完成")] FileDealCompleted = 0, [Description("导入表空白")] TableIsEmpty = 1, } }
// <copyright file="Social.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2020 Firoozeh Technology LTD. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> /** * @author Alireza Ghodrati */ using System.Collections.Generic; using System.Threading.Tasks; using FiroozehGameService.Core.ApiWebRequest; using FiroozehGameService.Models; using FiroozehGameService.Models.BasicApi.Social; using FiroozehGameService.Models.BasicApi.Social.Providers; using FiroozehGameService.Models.Enums; using FiroozehGameService.Utils; namespace FiroozehGameService.Core.Social { internal class Social : SocialProvider { private readonly Friend _friend; private readonly Party _party; internal Social() { _party = new Party(); _friend = new Friend(); } public override FriendProvider Friends() { return _friend; } public override PartyProvider Parties() { return _party; } public override async Task<List<Event>> GetAllEvents() { if (!GameService.IsAuthenticated()) throw new GameServiceException("GameService Not Available").LogException(typeof(Social), DebugLocation.Social, "GetAllEvents"); return await ApiRequest.GetAllEvents(); } } }
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using System.Collections.Generic; using System.Web.Mvc; namespace Pe.Stracon.Politicas.Presentacion.Core.ViewModel.General.SeccionParametro { /// <summary> /// Modelo de Sección Parámetro /// </summary> /// <remarks> /// Creación: GMD 22122014 <br /> /// Modificación: <br /> /// </remarks> public class SeccionParametroModel { /// <summary> /// Constructor de la Clase /// </summary> public SeccionParametroModel() { Parametro = new ParametroResponse(); SeccionParametro = new ParametroSeccionResponse(); ListaTipoDato = new List<SelectListItem>(); ListaParametroRelacionado = new List<SelectListItem>(); ListaSeccionRelacionada = new List<SelectListItem>(); ListaSeccionRelacionadaVisible = new List<SelectListItem>(); } #region Propiedades /// <summary> /// Lista de Tipo de Dato /// </summary> public List<SelectListItem> ListaTipoDato { get; set; } /// <summary> /// Lista de Parámetro Relacionado /// </summary> public List<SelectListItem> ListaParametroRelacionado { get; set; } /// <summary> /// Lista de Sección Relacionada /// </summary> public List<SelectListItem> ListaSeccionRelacionada { get; set; } /// <summary> /// Lista de Sección Relacionada Visible /// </summary> public List<SelectListItem> ListaSeccionRelacionadaVisible { get; set; } /// <summary> /// Parámetro /// </summary> public ParametroResponse Parametro { get; set; } /// <summary> /// Parámetro Sección /// </summary> public ParametroSeccionResponse SeccionParametro { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Models.Models { public class ViewUser { public Guid? UserId { get; set; } public string UserName { get; set; } public string Pword { get; set; } public string Email { get; set; } public DateTime? Dob { get; set; } public int? Bucks { get; set; } public bool Active { get; set; } public DateTime LastLogin { get; set; } public int? LoginStreak { get; set; } public string? ProfilePic { get; set; } public bool RewardCollected { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoftwareAuthKeyLoader.Kmm { public class NegativeAcknowledgement : KmmBody { public MessageId AcknowledgedMessageId { get; private set; } public Status Status { get; private set; } public override MessageId MessageId { get { return MessageId.NegativeAcknowledgement; } } public override ResponseKind ResponseKind { get { return ResponseKind.None; } } public NegativeAcknowledgement(byte[] contents) { Parse(contents); } public override byte[] ToBytes() { throw new NotImplementedException(); } protected override void Parse(byte[] contents) { if (contents.Length != 2) { throw new ArgumentOutOfRangeException("contents", string.Format("length mismatch - expected 2, got {0} - {1}", contents.Length.ToString(), BitConverter.ToString(contents))); } /* acknowledged message id */ AcknowledgedMessageId = (MessageId)contents[0]; /* status */ Status = (Status)contents[1]; } public override string ToString() { return string.Format("[AcknowledgedMessageId: {0} (0x{1:X2}), Status: {2} (0x{3:X2})]", AcknowledgedMessageId.ToString(), (byte)AcknowledgedMessageId, Status.ToString(), (byte)Status); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugTracker.Models.classes { public class CreateTicketListModel { public int ProjectId { get; set; } public string Title { get; set; } public string Description { get; set; } public SelectList TicketType { get; set; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Threading.Tasks; using Confluent.Kafka; using Microsoft.Azure.WebJobs.Host; using Microsoft.Azure.WebJobs.Host.Bindings; using Microsoft.Azure.WebJobs.Host.Listeners; using Microsoft.Azure.WebJobs.Host.Triggers; using Microsoft.Azure.WebJobs.Logging; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.Azure.WebJobs.Extensions.Kafka { internal class KafkaTriggerAttributeBindingProvider : ITriggerBindingProvider { private readonly IConfiguration config; private readonly IConverterManager converterManager; private readonly INameResolver nameResolver; private readonly IOptions<KafkaOptions> options; private readonly ILogger logger; public KafkaTriggerAttributeBindingProvider( IConfiguration config, IOptions<KafkaOptions> options, IConverterManager converterManager, INameResolver nameResolver, ILoggerFactory loggerFactory) { this.config = config; this.converterManager = converterManager; this.nameResolver = nameResolver; this.options = options; this.logger = loggerFactory.CreateLogger(LogCategories.CreateTriggerCategory("Kafka")); } public Task<ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context) { var parameter = context.Parameter; var attribute = parameter.GetCustomAttribute<KafkaTriggerAttribute>(inherit: false); if (attribute == null) { return Task.FromResult<ITriggerBinding>(null); } var consumerConfig = CreateConsumerConfiguration(attribute); // TODO: reuse connections if they match with others in same function app Task<IListener> listenerCreator(ListenerFactoryContext factoryContext, bool singleDispatch) { var listener = KafkaListenerFactory.CreateFor(attribute, parameter.ParameterType, factoryContext.Executor, singleDispatch, this.options.Value, consumerConfig, logger); return Task.FromResult(listener); } #pragma warning disable CS0618 // Type or member is obsolete var binding = BindingFactory.GetTriggerBinding(new KafkaTriggerBindingStrategy(), context.Parameter, this.converterManager, listenerCreator); #pragma warning restore CS0618 // Type or member is obsolete return Task.FromResult<ITriggerBinding>(binding); } private KafkaListenerConfiguration CreateConsumerConfiguration(KafkaTriggerAttribute attribute) { var consumerConfig = new KafkaListenerConfiguration() { BrokerList = this.config.ResolveSecureSetting(nameResolver, attribute.BrokerList), ConsumerGroup = this.nameResolver.ResolveWholeString(attribute.ConsumerGroup), Topic = this.nameResolver.ResolveWholeString(attribute.Topic), EventHubConnectionString = this.config.ResolveSecureSetting(nameResolver, attribute.EventHubConnectionString), }; if (attribute.AuthenticationMode != BrokerAuthenticationMode.NotSet || attribute.Protocol != BrokerProtocol.NotSet) { consumerConfig.SaslPassword = this.config.ResolveSecureSetting(nameResolver, attribute.Password); consumerConfig.SaslUsername = this.config.ResolveSecureSetting(nameResolver, attribute.Username); consumerConfig.SslKeyLocation = attribute.SslKeyLocation; if (attribute.AuthenticationMode != BrokerAuthenticationMode.NotSet) { consumerConfig.SaslMechanism = (SaslMechanism)attribute.AuthenticationMode; } if (attribute.Protocol != BrokerProtocol.NotSet) { consumerConfig.SecurityProtocol = (SecurityProtocol)attribute.Protocol; } } return consumerConfig; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Grillisoft.FastCgi { public interface ILoggerFactory { ILogger Create(Type type); ILogger Create(string name); } }
using Grpc.Core; using Grpc.Net.Client; using GrpcServer; using GrpcServer.Protos; using System; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; namespace Grpc_Client { class Program { private const string Address = "localhost:5001"; private static string _token; static async Task Main(string[] args) { //var clientCert = File.ReadAllText(@"ssl/client.crt"); //var clientKey = File.ReadAllText(@"ssl/client.key"); //var caCrt = File.ReadAllText(@"ssl/ca.crt"); var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions { MaxReceiveMessageSize = 550 * 1024 * 1024, MaxSendMessageSize = 200 * 1024 * 1024 }); Console.WriteLine("Pershendetje \n \n Ju lutem zgjedhni sherbimin te cilin doni ta shftytezoni."); while (true) { try { Console.WriteLine(" 1. Autentifikohu \n 2. Shto konsumatore ne vazhdimesi \n 3. Shiko konsumatoret ne kohe reale \n 4. Shiko blerjet ne kohe reale"); string choice = Console.ReadLine(); if (choice.ToLower().Equals("stop")) break; switch (choice) { case "1": //Authentication service call try { Console.WriteLine("Jepni username: "); string username = Console.ReadLine(); Console.WriteLine("Jepni password-in: "); string password = Console.ReadLine(); var authClient = new authAdmin.authAdminClient(channel); _token = authClient.StaffAuth(new authInput { Username = username, Password = password }).Token.ToString(); if(_token==null) { Console.WriteLine("Username apo password-i i dhene eshte gabim!"); continue; } channel.Dispose(); channel = CreateAuthenticatedChannel($"https://{Address}"); Console.WriteLine("Sapo u autentifikuat!"); } catch (RpcException e) { Console.WriteLine(e.Status.Detail); Console.WriteLine(e.Status.StatusCode); } break; case "2": //Shto konsumator ne vazhdimsi try { var cClient = new Customer.CustomerClient(channel); using (var call = cClient.AddCustomersStream()) { var response = Task.Run(async () => { while (await call.ResponseStream.MoveNext()) { Console.WriteLine(call.ResponseStream.Current.Message); } }); string name="", username="";char mbyll='a'; while (!mbyll.Equals('q')) { Console.WriteLine("Shenoni te dhenat per konsumatorin e ri"); Console.WriteLine("Emri: "); name = Console.ReadLine(); Console.WriteLine("Username: "); username = Console.ReadLine(); Console.WriteLine("Mobile Nr"); string mobileNr = Console.ReadLine(); if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(username)) { try { bool nr = Int32.TryParse(mobileNr, out int numri); await call.RequestStream.WriteAsync(new newCustomerData { Name = name, Username = username, MobileNr = nr == true ? numri : 0 }); } catch { try { Status status = call.GetStatus(); if (status.StatusCode != StatusCode.OK) Console.WriteLine($"{status.StatusCode}, {status.Detail}"); } catch{ Console.WriteLine("Ka nodhur nje gabim!"); } break; } } else { Console.WriteLine("Emri apo Username nuk eshte plotesuar!"); } Console.WriteLine("Shtypni 'q' per te mbyllur, qfardo tasti tjeter per te vazhduar!"); ConsoleKeyInfo ans = Console.ReadKey(true); mbyll = Char.ToLower(ans.KeyChar); } await call.RequestStream.CompleteAsync(); } } catch (RpcException ex) { Console.WriteLine(ex.StatusCode); Console.WriteLine(ex.Status.Detail); } break; case "3": //Shiko konsumatoret e regjistruar ne Real Time try { var cClient = new Customer.CustomerClient(channel); using (var call = cClient.GetNewCustomers(new Empty() { }, deadline: DateTime.UtcNow.AddSeconds(500))) { Console.WriteLine("Konsumatoret e regjistruar"); var response = Task.Run(()=> { var line = Console.ReadLine(); call.Dispose(); }); while (await call.ResponseStream.MoveNext()) { Console.WriteLine($"Name: {call.ResponseStream.Current.Name}, Username: {call.ResponseStream.Current.Username}, Mobile Number: {call.ResponseStream.Current.MobileNr}"); } } } catch (RpcException e) { Console.WriteLine(e.Status.Detail); Console.WriteLine(e.Status.StatusCode); } break; case "4": //Shiko produktet e blera ne Real Time try { var cClient = new sales.salesClient(channel); using (var call = cClient.getSalesInRealTime(new Google.Protobuf.WellKnownTypes.Empty())) { Console.WriteLine("Produktet e blera REAL TIME"); var response = Task.Run(() => { var line = Console.ReadLine(); call.Dispose(); }); while (await call.ResponseStream.MoveNext()) { Console.WriteLine($"Customer: {call.ResponseStream.Current.Customer}, Product: {call.ResponseStream.Current.Product}, " + $"Cmimi: {call.ResponseStream.Current.Price}, Data Blerjes: {call.ResponseStream.Current.Date}"); } } } catch (RpcException e) { Console.WriteLine(e.Status.Detail); Console.WriteLine(e.Status.StatusCode); } break; default: Console.WriteLine("Ju lutem zgjedhni njerin nga numrat"); break; } } catch (RpcException ex) { Console.WriteLine(ex.StatusCode); Console.WriteLine(ex.Status.Detail); Console.WriteLine("Ju lutem zgjedhni njerin nga numrat!"); } } } private static GrpcChannel CreateAuthenticatedChannel(string address) { var credentials = CallCredentials.FromInterceptor((context, metadata) => { if (!string.IsNullOrEmpty(_token)) { metadata.Add("Authorization", $"Bearer {_token}"); } return Task.CompletedTask; }); // SslCredentials is used here because this channel is using TLS. // Channels that aren't using TLS should use ChannelCredentials.Insecure instead. var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { Credentials = ChannelCredentials.Create(new SslCredentials(), credentials) }); return channel; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Patterns.Pattern.Ef6; namespace Welic.Dominio.Models.Estacionamento.Map { public class EstacionamentoMap: Entity { public int IdEstacionamento { get; set; } public string Descricao { get; set; } public bool ValidaVencimento { get; set; } public int TipoIdentificacao { get; set; } public int Relacao { get; set; } public virtual ICollection<EstacionamentoVagasMap> EstacionamentoVagas { get; set; } public ICollection<SolicitacoesEstacionamentoMap> SolicitacoesEstacionamento { get; set; } public ICollection<SolicitacoesVagasLiberadasMap> SolicitacoesVagasLiberadas { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Qwack.Paths.Features { public interface IVolFeature { } }
using Caliburn.Micro; using CustomTournamentsLibrary.Models; namespace CustomTournamentsLibrary.Interfaces { public interface IEnterResult { TournamentModel CurrentTournament { get; set; } BindableCollection<RoundModel> RoundList { get; set; } RoundModel SelectedRound { get; set; } BindableCollection<GameModel> GameList { get; set; } GameModel SelectedGame { get; set; } BindableCollection<LeagueParticipantModel> LeagueParticipants { get; set; } bool CanEnterResult { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; namespace SlackTemplate.Core { public interface IInlineRenderer { string Render(XElement element); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; //TODO: Add other using statements here namespace com.Sconit.Entity.MRP.MD { public partial class HuToMapping { #region Non O/R Mapping Properties //HuTo Party Flow Item [Display(Name = "HuToMapping_HuToDescription", ResourceType = typeof(Resources.MRP.HuToMapping))] public string HuToDescription { get; set; } [Display(Name = "HuToMapping_PartyName", ResourceType = typeof(Resources.MRP.HuToMapping))] public string PartyName { get; set; } [Display(Name = "HuToMapping_FlowDescription", ResourceType = typeof(Resources.MRP.HuToMapping))] public string FlowDescription { get; set; } [Display(Name = "HuToMapping_ItemDescription", ResourceType = typeof(Resources.MRP.HuToMapping))] public string ItemDescription { get; set; } [Display(Name = "HuToMapping_FgDescription", ResourceType = typeof(Resources.MRP.HuToMapping))] public string FgDescription { get; set; } [Display(Name = "HuToMapping_PartyType", ResourceType = typeof(Resources.MRP.HuToMapping))] public string PartyType { get; set; } public List<string> FgList { get; set; } #endregion } }
using ComInLan.Model; using System; using System.Collections.Generic; namespace ComInLan.Server { public interface IBroadcastServer { string Id { get; } string DomainId { get; } string Name { get; set; } int ListeningPort { get; } bool IsRunning { get; } List<IClient> Clients { get; } bool Start(); void Stop(); void ChangId(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatterns_State { public class Person { private StatePerson state; private string name; public Person(string name) { this.name = name; this.state = WithoutCap.Instance(); } public string WhoAmI() { return (this.name + "com" + this.state); } public void ChangeState(StatePerson state) { this.state = state; Console.WriteLine(this.state.WhoAmI()); } public void TakeCap() { this.state.takeCap(this); } public void PutCap() { this.state.putCap(this); } public void CapBack() { this.state.capBack(this); } public void CapFoward() { this.state.capFoward(this); } } }
using ExitGames.Client.Photon; using Photon.Pun; using Photon.Realtime; using Source.Code.Extensions; using Source.Code.MyPhoton; using Source.Code.Utils; using System.Collections.Generic; using TMPro; using UnityEngine; namespace Source.Code.UI { public class WaitingForPlayersPanel : MonoBehaviourPunCallbacks { [SerializeField] private RectTransform placePlayersNamesTransform; [SerializeField] private GameObject playerNicknamePrefab; private Dictionary<int, GameObject> dontReadyPlayers = new Dictionary<int, GameObject>(); public void Initialize() { gameObject.SetActive(true); var players = PhotonNetwork.PlayerList; Debug.Log("Players Count " + players.Length); foreach (var player in players) { bool isLoaded = PhotonExtensions.GetValueOrReturnDefault<bool>(player.CustomProperties, GlobalConst.PLAYER_LOADED_LEVEL); Debug.Log("isLoaded " + isLoaded); if (!isLoaded) { var nickGO = Instantiate(playerNicknamePrefab, placePlayersNamesTransform); nickGO.GetComponent<TextMeshProUGUI>().text = player.NickName; } } } public override void OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps) { Debug.Log("ProperitesUpdated"); if (changedProps.TryGetValue(GlobalConst.PLAYER_LOADED_LEVEL, out object result)) { if ((bool)result) { if (dontReadyPlayers.TryGetValue(targetPlayer.ActorNumber, out GameObject nickNameGO)) { Destroy(nickNameGO); } } } CheckIsAllReady(); } public void CheckIsAllReady() { Debug.Log("CheckIsAllReady"); if (PhotonNetwork.IsMasterClient) { bool isAllLoaded = true; var players = PhotonNetwork.PlayerList; foreach (var player in players) { bool isLoaded = PhotonExtensions.GetValueOrReturnDefault<bool>(player.CustomProperties, GlobalConst.PLAYER_LOADED_LEVEL); if (isLoaded == false) { isAllLoaded = false; break; } } if (isAllLoaded) { SessionSettings.Instance.GlobalState.SetPreGameTimer(0); } } } } }
using System.Drawing; using System.Windows.Forms; public class Npc { //位置 public int map = -1; //npc所在地图id public int x = 0; //坐标 public int y = 0; public int x_offset = -50; //绘图偏移量 public int y_offset = -90; //显示 public string bitmap_path=""; //图片路径 public Bitmap bitmap; public bool visible = true; //是否可见 //碰撞区域 public int region_x = 35; public int region_y = 35; //动画 public Animation[] anm; //anm 代表这个npc所能使用的所有动画 public int anm_frame = 0; //当前播放的帧 public int current_anm = -1; //当前使用的动画,对应于anm数组的下标。-1表示没有播放 public long last_anm_time = 0; //上一帧播放的时间,用于调控播放速 //人物类 public Comm.Direction face = Comm.Direction.DOWN; public int walk_frame = 0; //行走的动画帧 public long last_walk_time = 0; //最后一次行走的时间 public long walk_interval = 80; // 行走间隔 public int speed = 40; //速度 public Comm.Direction idle_walk_direction = Comm.Direction.DOWN; // 行走方向,上下和左右 public int idle_walk_time = 0; //往每个方向走的帧数,也是控制住每个方向行走的距离 public int idle_walk_time_now = 0; //当前行走的时间 //定义枚举 普通和人物类型npc public enum Npc_type { NORMAL=0, CHARACTER=1, } public Npc_type npc_type = Npc_type.NORMAL; //鼠标碰撞区域 public int mc_xoffset = -20; public int mc_yoffset = -20; public int mc_w = 50; public int mc_h = 50; public static int mc_distance_x = 100; //在一定距离内单击才有效 public static int mc_distance_y = 200; //加载 public void load() { if (bitmap_path != "") { bitmap = new Bitmap(bitmap_path); bitmap.SetResolution(96,96); } if (anm != null) //动画资源 { for (int i = 0; i < anm.Length; i++) anm[i].load(); } //鼠标碰撞区域 if (bitmap != null) { if (mc_w == 0) mc_w = bitmap.Width; if (mc_h == 0) mc_h = bitmap.Height; } else if (npc_type == Npc_type.CHARACTER) { if (mc_w == 0) mc_w = bitmap.Width / 4; if (mc_h == 0) mc_h = bitmap.Height / 4; } else { if (mc_w == 0) mc_w = region_x; if (mc_h == 0) mc_h = region_y; } } //卸载 public void unload() { if (bitmap != null) { bitmap = null; } if (anm != null) //动画资源 { for (int i = 0; i < anm.Length; i++) anm[i].unload(); } } //绘图,判断当前是否播放动画 public void draw(Graphics g, int map_sx, int map_sy) { //绘制角色 if (visible != true) return; if(current_anm < 0) { if (npc_type == Npc_type.NORMAL) { if (bitmap != null) g.DrawImage(bitmap, map_sx + x + x_offset, map_sy + y + y_offset); } else if (npc_type == Npc_type.CHARACTER) { draw_character(g,map_sx,map_sy); //绘制Character类型对象 } } /* if (visible != true) return; if (current_anm < 0) { if (bitmap != null) g.DrawImage(bitmap, map_sx + x + x_offset, map_sy + y + y_offset); //绘制npc } */ else { draw_anm(g,map_sx,map_sy); //绘制动画 } } //碰撞 public bool is_collision(int collision_x, int collision_y) { Rectangle rect = new Rectangle(x-region_x/2,y-region_y/2,region_x,region_y); return rect.Contains(new Point(collision_x,collision_y)); } //线碰撞 public bool is_line_collision(Point p1, Point p2) { if (is_collision(p2.X, p2.Y)) return true; //p2点 int px, py; //1/2点 px = p1.X + (p2.X - p1.Y) / 2; py = p1.Y + (p2.Y - p1.Y) / 2; if (is_collision(px, py)) return true; px = p2.X - (p2.X - p1.X) / 4; //3/4点 py = p2.Y - (p2.Y - p1.Y) / 4; if (is_collision(px, py)) return true; return false; } //定义枚举 触发类型 public enum Collosion_type { KEY=1, ENTER=2, } public Collosion_type collision_type = Collosion_type.KEY; //默认触发为按键 //动画绘图 public void draw_anm(Graphics g, int map_sx, int map_sy) { if (anm == null || current_anm >= anm.Length || anm[current_anm] == null || anm[current_anm].bitmap_path == null) { current_anm = -1; anm_frame = 0; last_anm_time = 0; return; } anm[current_anm].draw(g, anm_frame, map_sx + x + x_offset, y + map_sy + y_offset); //调用Animation类的draw方法 if (Comm.Time() - last_anm_time >= Animation.RATE) { anm_frame = anm_frame + 1; last_anm_time = Comm.Time(); if (anm_frame / anm[current_anm].anm_rate >= anm[current_anm].max_frame) { current_anm = -1; anm_frame = 0; last_anm_time = 0; } } } //事件,设置当前要播放的动画 public void play_anm(int index) { current_anm = index; anm_frame=0; } //画character角色 public void draw_character(Graphics g, int map_sx, int map_sy) { Rectangle rent = new Rectangle(bitmap.Width/4*(walk_frame%4),bitmap.Height/4*((int)face-1),bitmap.Width/4,bitmap.Height/4); Bitmap bitmap0 = bitmap.Clone(rent,bitmap.PixelFormat); g.DrawImage(bitmap0,map_sx+x+x_offset,map_sy+y+y_offset); } //--------------------------------------------------- //isblock为false表示不受地图限制 //处理人物类npc的行走 public void walk(Map[] map, Comm.Direction direction, bool isblock) { //转向 face = direction; //间隔判断 if (Comm.Time() - last_walk_time <= walk_interval) return; //行走 //up if (direction == Comm.Direction.UP && (!isblock || Map.can_through(map, x, y - speed))) { y = y - speed; } //down else if (direction == Comm.Direction.DOWN && (!isblock || Map.can_through(map, x, y + speed))) { y = y + speed; } //left else if (direction == Comm.Direction.LEFT && (!isblock || Map.can_through(map, x - speed, y))) { x = x - speed; } //right else if (direction == Comm.Direction.RIGHT && (!isblock || Map.can_through(map, x + speed, y))) { x = x+ speed; } //动画帧 walk_frame = walk_frame + 1; if (walk_frame >= int.MaxValue) walk_frame = 0; //时间 last_walk_time = Comm.Time(); } //处理停止行走的状态 public void stop_walk() { walk_frame = 0; last_walk_time = 0; } //定时处理npc的一些逻辑//处理行走时间间隔,调用walk来处理npc行走 public void timer_logic(Map[] map) { /* if (idle_walk_time != 0) walk(map,Comm.Direction.DOWN,false); */ if (npc_type == Npc_type.CHARACTER && idle_walk_time != 0) //人物类npc才会执行 { Comm.Direction direction; //根据idle_walk_time_now的正负判断方向大于等于为正 if (idle_walk_time_now >= 0) direction = idle_walk_direction; else direction = Comm.opposite_direction(idle_walk_direction); walk(map,direction,true); //处理行走 if (idle_walk_time_now >= 0) //正方向处理时间 { idle_walk_time_now = idle_walk_time_now + 1; if (idle_walk_time_now > idle_walk_time) idle_walk_time_now = -1; // 转向 } else if (idle_walk_time_now < 0) { idle_walk_time_now = idle_walk_time_now - 1; if (idle_walk_time_now < -idle_walk_time) idle_walk_time_now = 1; } } } //鼠标碰撞 public bool is_mouse_collision(int collision_x, int collisoin_y) { //有图 if (bitmap != null) { if (npc_type == Npc_type.NORMAL) //普通型 { int center_x = x + x_offset + bitmap.Width / 2; int center_y = y + y_offset + bitmap.Height / 2; Rectangle rect = new Rectangle(center_x - mc_w / 2, center_y - mc_h / 2, mc_w, mc_h); return rect.Contains(new Point(collision_x, collisoin_y)); } else //人物型 { int center_x = x + x_offset + bitmap.Width / 4 / 2; int center_y = y + y_offset + bitmap.Height / 4 / 2; Rectangle rect = new Rectangle(center_x - mc_w / 2, center_y - mc_h / 2, mc_w, mc_h); return rect.Contains(new Point(collision_x, collisoin_y)); } } //无图 else { Rectangle rect = new Rectangle(x-mc_w/2,y-mc_h/2,mc_w,mc_h); return rect.Contains(new Point(collision_x, collisoin_y)); } } //距离检测 public bool check_mc_distance(Npc npc, int player_x, int player_y) { Rectangle rect = new Rectangle(npc.x-mc_distance_x/2,npc.y-mc_distance_y/2,mc_distance_x,mc_distance_y); return rect.Contains(new Point(player_x,player_y)); } //鼠标操作 public static void mouse_click(Map[] map, Player[] player, Npc[] npc, Rectangle stage, MouseEventArgs e) { if (Player.status != Player.Status.WALK) return; if (npc == null) return; for (int i = 0; i < npc.Length; i++) { if (npc[i] == null) continue; if (npc[i].map != Map.current_map) continue; int collision_x = e.X - Map.get_map_sx(map,player,stage); //获取坐标 int collision_y = e.Y - Map.get_map_sy(map, player, stage); if (!npc[i].is_mouse_collision(collision_x, collision_y)) //碰撞检测 continue; //距离 if (!npc[i].check_mc_distance(npc[i], Player.get_pos_x(player), Player.get_pos_y(player))) // 距离检测 { Player.stop_walk(player); //距离太远了 Message.showtip("请走近点"); Task.block(); continue; } Player.stop_walk(player); //触发事件 Task.story(i); } } //检测鼠标是否在npc上 public static int check_mouse_collision(Map[] map, Player[] player, Npc[] npc, Rectangle stage, MouseEventArgs e) { if (Player.status != Player.Status.WALK) //状态判断 return 0; if (npc == null) return 0; for (int i = 0; i < npc.Length; i++) { if (npc[i] == null) continue; if (npc[i].map != Map.current_map) continue; int collision_x = e.X - Map.get_map_sx(map, player, stage); //获取碰撞坐标 int collision_y = e.Y - Map.get_map_sy(map, player, stage); if (npc[i].is_mouse_collision(collision_x, collision_y)) //判断是发生碰撞 { return 1; //碰到为1 } } return 0; //没有为0 } }
using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using UnityEngine; public class Network : MonoBehaviour { private Socket m_socket; IPAddress address; IPEndPoint endPoint; SocketError error; // Use this for initialization void Start () { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); address = IPAddress.Parse("192.168.2.217"); endPoint = new IPEndPoint(address, 7000); } private void OnGUI() { if(GUILayout.Button("test",new GUILayoutOption[] {GUILayout.Width(100),GUILayout.Height(100) })) { m_socket.BeginConnect(endPoint, asyncResult => { try{ m_socket.EndConnect(asyncResult); Debug.Log(">>>>>>>"); }catch (SocketException ex) { //无法连接目标主机10060  主动拒绝10061  读写时主机断开10053  Debug.LogError("==connectException=>" + ex.NativeErrorCode); return; } },m_socket); } if (GUILayout.Button("send",new GUILayoutOption[] {GUILayout.Width(100),GUILayout.Height(100)})) { string str = "aaa"; byte[] bytes = System.Text.Encoding.Default.GetBytes(str); m_socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncBack=>{ int length = m_socket.EndSend(asyncBack); Debug.Log(length); },m_socket); } } }
using System.Reflection; using NLog; using Sandbox.Common.ObjectBuilders; using Sandbox.Game.Entities; using Torch.Managers.PatchManager; using VRage; using VRageMath; namespace DataValidateFix { [PatchShim] public static class MySafeZonePatch { private static readonly Logger Log = LogManager.GetCurrentClassLogger(); private static Vector3 _minSize = new Vector3(MySafeZone.MIN_RADIUS * 2); private static Vector3 _maxSize = new Vector3(MySafeZone.MAX_RADIUS * 2); // ReSharper disable once InconsistentNaming private static void InitInternalPatch(ref MyObjectBuilder_SafeZone ob) { var size = ob.Size; if (!size.IsInsideInclusive(ref _minSize, ref _maxSize)) { ob.Size = size.Clamp(ref _minSize, ref _maxSize); } } public static void Patch(PatchContext patchContext) { Log.TryPatching(() => { var initInternal = typeof(MySafeZone) .GetMethod("InitInternal", BindingFlags.Instance | BindingFlags.NonPublic); patchContext.GetPattern(initInternal).Prefixes .Add(((ActionRef<MyObjectBuilder_SafeZone>) InitInternalPatch).Method); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] // The Serializable attribute lets you turn this into bytes // DATA CLASS FOR SAVING PLAYER public class PlayerData { public float xPosition; public float yPosition; public float zPosition; public Player.PlayerState savedState; public bool direction; public string animState; // Constructor public PlayerData(float xPos, float yPos, float zPos, Player.PlayerState state, bool facingRight, string ans) { xPosition = xPos; yPosition = yPos; zPosition = zPos; savedState = state; direction = facingRight; animState = ans; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class NextLevel : MonoBehaviour { public static NextLevel instance = null; private void StartNextLevel(Cell.Type winnerType) { if (winnerType == Cell.Type.Friend) { LevelController.instance.isEndGame(); } else if(winnerType == Cell.Type.Enemy) { SceneManager.LoadScene(LevelController.instance.sceneIndex); } } public void CheckEndGame() { var cellsInScene = FindObjectsOfType<Cell>(); Cell.Type baseType = cellsInScene[0].type; bool isEnded = true; foreach (var cell in cellsInScene) { if (cell.type != baseType) { isEnded = false; break; } } if (isEnded) { StartNextLevel(baseType); } } private void Start() { if (instance == null) { instance = this; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StarSpawner : MonoBehaviour { private List<GameObject> stars = new List<GameObject>(); public GameObject star; [Header("Star Spawn Properties")] public Transform spawnPoint; public float maxSpawnpoint; public float minSpawnpoint; public float maxRotation; public float minRotation; [Space] public float currentTimeOfpool; public float timeToactivateStar; private void Start() { // start # This will spawn a star gameobject that will be stored in stars pool GameObject spawn_object = Instantiate(star, spawnPoint.position, spawnPoint.rotation); spawn_object.SetActive(false); stars.Add(spawn_object); // end } private void Update() { currentTimeOfpool += Time.deltaTime; if (currentTimeOfpool >= timeToactivateStar) { currentTimeOfpool = 0; foreach(GameObject _gameobject in stars) { _gameobject.transform.position = new Vector3(spawnPoint.transform.position.x, spawnPoint.position.y + Random.Range(minSpawnpoint, maxSpawnpoint), 0); _gameobject.transform.eulerAngles = new Vector3(_gameobject.transform.rotation.x, _gameobject.transform.rotation.y, Random.Range(minRotation, maxRotation)); _gameobject.SetActive(true); } } } }
using System; using System.Collections.Generic; using StardewModdingAPI; namespace Entoarox.Framework.Core.AssetHandlers { internal class XnbLoader : IAssetLoader { /********* ** Accessors *********/ internal static Dictionary<string, Tuple<IContentHelper, string>> Map = new Dictionary<string, Tuple<IContentHelper, string>>(); /********* ** Public methods *********/ public bool CanLoad<T>(IAssetInfo asset) { return XnbLoader.Map.ContainsKey(asset.AssetName); } public T Load<T>(IAssetInfo asset) { return XnbLoader.Map[asset.AssetName].Item1.Load<T>(XnbLoader.Map[asset.AssetName].Item2); } } }
using System; using System.IO; using System.Linq; using System.Reflection; using DelftTools.Utils.Reflection; namespace DelftTools.Utils { public static class SettingsHelper { static SettingsHelper() { //set defaults based on executing assembly var info = AssemblyUtils.GetExecutingAssemblyInfo(); ApplicationName = info.Product; ApplicationVersion = info.Version; } public static string ApplicationNameAndVersion { get { return ApplicationName + " " + ApplicationVersion; } } public static string ApplicationName{ get; set; } public static string ApplicationVersion { get; set; } public static string GetApplicationLocalUserSettingsDirectory() { var localSettingsDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var executingAssembly = Assembly.GetExecutingAssembly(); var assemblyInfo = AssemblyUtils.GetAssemblyInfo(executingAssembly); var companySettingsDirectoryPath = Path.Combine(localSettingsDirectoryPath, assemblyInfo.Company); var applicationVersionDirectory = ApplicationName + "-" + ApplicationVersion; var appSettingsDirectoryPath = Path.Combine(companySettingsDirectoryPath, applicationVersionDirectory); if (!Directory.Exists(appSettingsDirectoryPath)) { Directory.CreateDirectory(appSettingsDirectoryPath); } return appSettingsDirectoryPath; } } }
using UnityEngine; using System.Collections; public class CameraBehaviour : MonoBehaviour { [SerializeField] private Transform target; [SerializeField] private float yOffset; // Use this for initialization void Start () { DynamicGI.UpdateEnvironment(); } // Update is called once per frame void LateUpdate () { //transform.position = new Vector3(transform.position.x,target.transform.position.y+yOffset,transform.position.z); Vector3 newYPos = new Vector3(transform.position.x, target.transform.position.y + yOffset, transform.position.z); transform.position = Vector3.Lerp(transform.position,newYPos,Time.fixedDeltaTime * 100f); if (transform.name == "Player Camera") { Vector3 newXZPos = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z); //if (target.transform.position.x > -2.2f && target.transform.position.x < 2.2f && target.transform.position.z < 3f && target.transform.position.z > -1.7f) //{ transform.position = Vector3.Lerp(transform.position, newXZPos, Time.fixedDeltaTime * 2f); //} } } }
using System; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace SyncAppGUI { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if(!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\SyncApp\\")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\SyncApp\\"); } Task.Run(() => FileWatcher.DeletePaths()); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
using System.Collections.Generic; using Crossroads.Web.Common.Security; using MinistryPlatform.Translation.Repositories.Interfaces; using Moq; using NUnit.Framework; using SignInCheckIn.Services; namespace SignInCheckIn.Tests.Services { [TestFixture] public class LoginServiceTest { private Mock<IAuthenticationRepository> _authenticationRepository; private LoginService _fixture; [SetUp] public void SetUp() { _authenticationRepository = new Mock<IAuthenticationRepository>(); _fixture = new LoginService(_authenticationRepository.Object); } [Test] public void ShouldAuthenticateUserSuccess() { // Arrange string username = "test@test.com"; string password = "12345678"; var authData = new AuthToken { AccessToken = "123", ExpiresIn = 123, RefreshToken = "456" }; List<string> authRoles = new List<string> { "Kids Club Tools - CRDS" }; _authenticationRepository.Setup(m => m.AuthenticateUser(username, password, true)).Returns(authData); _authenticationRepository.Setup(m => m.GetUserRolesFromToken(authData.AccessToken)).Returns(authRoles); // Act _fixture.Login(username, password); // Assert _authenticationRepository.VerifyAll(); } } }
using Stock_Exchange_Analyzer.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace Stock_Exchange_Analyzer { static class CurrencyRetriever { public static string getCurrency(string companyName) { string currency; var webClient = new WebClient(); webClient.Encoding = Encoding.UTF8; string getString = "https://finance.yahoo.com/q/hp?s="+ companyName + "+Historical+Prices"; string htmlResult; try { htmlResult = webClient.DownloadString(getString); currency = getBetween(htmlResult, "class=\"yfi_disclaimer\">Currency in ", ".</p>"); if(htmlResult.Contains("Historical quote data is unavailable for the specified date range.")) throw new CurrencyParseFailedException("Failed to get the currency for " + companyName); return currency; } catch { throw new CurrencyParseFailedException("Failed to get the currency for " + companyName); } } public static string getBetween(string strSource, string strStart, string strEnd) { int Start, End; if (string.IsNullOrWhiteSpace(strSource)) return string.Empty; if (String.IsNullOrEmpty(strEnd)) { if (String.IsNullOrEmpty(strStart)) Start = 0; else Start = strSource.IndexOf(strStart, 0) + strStart.Length; End = strSource.Length; return strSource.Substring(Start, End - Start); } else if (strSource.Contains(strStart) && strSource.Contains(strEnd)) { if (String.IsNullOrEmpty(strStart)) Start = 0; else Start = strSource.IndexOf(strStart, 0) + strStart.Length; End = strSource.IndexOf(strEnd, Start); if (End < 0) End = strSource.Length; return strSource.Substring(Start, End - Start); } else { if (String.IsNullOrEmpty(strStart)) Start = 0; else Start = strSource.IndexOf(strStart, 0) + strStart.Length; End = strSource.Length; return strSource.Substring(Start, End - Start); } } } }
using ISE.SM.Common.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ISE.SM.Common.Message { public class AuthorizationRequest { public IdentityToken IdentityToken { get; set; } public SecurityResourceDto Resource { get; set; } public int ResourceTypeId { get; set; } public int AppDomainId { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace DSSCriterias.Logic.Extensions { public static class CriteriaExtensions { public static double[] NewRows(this Criteria criteria) { return new double[(int)criteria.Game.Arr.Rows()]; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CompactorDoor : MonoBehaviour { [SerializeField] private Transform door; [SerializeField] private Transform doorHinge; [SerializeField] private Transform grinder; [SerializeField] private Transform spring; [SerializeField] private Vector2 doorScaleRange = new Vector2 (); [SerializeField] private Vector2 grinderPositionRange = new Vector2 (); [SerializeField] private float drag = 3.0f; [SerializeField] private float velocityMax = 10.0f; [SerializeField] private float speed = 2.0f; [SerializeField] private float velocity = 0.0f; [SerializeField] private bool countingUp = true; [SerializeField] float scale = 0.0f; // Start is called before the first frame update void Start() { } [ContextMenu("Add")] public void Add () { Debug.Log ( Mathf.Abs ( doorHinge.position.y - grinder.position.y ) ); } // Update is called once per frame void LateUpdate() { //grinder.transform.position = new Vector3 ( grinder.transform.position.x, spring.position.y, grinder.transform.position.z ); //return; float d = Mathf.Abs ( doorHinge.position.y - grinder.position.y ); //float s = Mathf.Clamp ( d * 100.0f, doorScaleRange.x, doorScaleRange.y ) + 50; float pNrm = Mathf.InverseLerp ( grinderPositionRange.x, grinderPositionRange.y, d ); float s = Mathf.Lerp ( doorScaleRange.y, doorScaleRange.x, pNrm ); door.localScale = new Vector3 ( 100.0f, 100.0f, s ); //Debug.Log ( "Dist " + d.ToString ( "00.00" ) + " - " + s.ToString ( "00.00" ) ); //Debug.Log ( s ); } //private void LateUpdate () //{ // grinder.transform.position = spring.transform.position; //} //private void LateUpdate () //{ // grinder.transform.position = doorHinge.transform.position; //} }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DPYM { /// <summary> /// 自定义技能,从脚本来读取行为 /// </summary> class CustSkill { } }
using System; namespace FeriaVirtual.Domain.SeedWork.Events { public class DomainEventId { private Guid _id; public Guid Value => _id; public DomainEventId() => _id = GuidGenerator.NewSequentialGuid(); public DomainEventId(Guid id) => _id = id; public DomainEventId(string id) => _id = new Guid(id); public override string ToString() => Value.ToString(); } }
/* * 2020 Microsoft Corp * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System.Security.Claims; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Newtonsoft.Json.Linq; using System.Reflection; using System.Linq.Expressions; using System.ComponentModel.Design; using Microsoft.Azure.Services.AppAuthentication; using FHIRProxy; namespace FHIREventProcessor { public static class OrchestrationProxy { /*A FHIR server proxy providing Function Key Based Authentication for orchestration access to a secure FHIR Server */ private static string _bearerToken = null; private static object _lock = new object(); [FunctionName("OrchestrationProxy")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", "put", "patch", Route = "fhir/{res}/{id?}")] HttpRequest req, ILogger log, ClaimsPrincipal principal, string res, string id) { /* Load the request contents */ string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); /* Get/update/check current bearer token to authenticate the proxy to the FHIR Server * The following parameters must be defined in environment variables: * To use Manged Service Identity or Service Client: * FS_URL = the fully qualified URL to the FHIR Server * FS_RESOURCE = the audience or resource for the FHIR Server for Azure API for FHIR should be https://azurehealthcareapis.com * To use a Service Client Principal the following must also be specified: * FS_TENANT_NAME = the GUID or UPN of the AAD tenant that is hosting FHIR Server Authentication * FS_CLIENT_ID = the client or app id of the private client authorized to access the FHIR Server * FS_SECRET = the client secret to pass to FHIR Server Authentication */ if (!string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("FS_RESOURCE")) && FHIRClient.isTokenExpired(_bearerToken)) { lock (_lock) { if (FHIRClient.isTokenExpired(_bearerToken)) { log.LogInformation($"Obtaining new OAUTH2 Bearer Token for access to FHIR Server"); _bearerToken = FHIRClient.GetOAUTH2BearerToken(System.Environment.GetEnvironmentVariable("FS_RESOURCE"), System.Environment.GetEnvironmentVariable("FS_TENANT_NAME"), System.Environment.GetEnvironmentVariable("FS_CLIENT_ID"), System.Environment.GetEnvironmentVariable("FS_SECRET")).GetAwaiter().GetResult(); } } } List<HeaderParm> auditheaders = new List<HeaderParm>(); auditheaders.Add(new HeaderParm("X-MS-AZUREFHIR-AUDIT-PROXY", "FHIREventProcessor")); /* Preserve FHIR Specific change control headers and include in the proxy call */ List<HeaderParm> customandrestheaders = new List<HeaderParm>(); foreach (string key in req.Headers.Keys) { string s = key.ToLower(); if (s.Equals("etag")) customandrestheaders.Add(new HeaderParm(key, req.Headers[key].First())); else if (s.StartsWith("if-")) customandrestheaders.Add(new HeaderParm(key, req.Headers[key].First())); } /* Add User Audit Headers */ customandrestheaders.AddRange(auditheaders); /* Get a FHIR Client instance to talk to the FHIR Server */ log.LogInformation($"Instanciating FHIR Client Proxy"); FHIRClient fhirClient = new FHIRClient(System.Environment.GetEnvironmentVariable("FS_URL"), _bearerToken); FHIRResponse fhirresp = null; /* Proxy the call to the FHIR Server */ JObject result = null; if (req.Method.Equals("GET")) { var qs = req.QueryString.HasValue ? req.QueryString.Value : null; fhirresp = fhirClient.LoadResource(res + (id == null ? "" : "/" + id), qs, false, customandrestheaders.ToArray()); } else { fhirresp = fhirClient.SaveResource(res,requestBody, req.Method, customandrestheaders.ToArray()); } /* Fix location header to proxy address */ if (fhirresp.Headers.ContainsKey("Location")) { fhirresp.Headers["Location"].Value = fhirresp.Headers["Location"].Value.Replace(Environment.GetEnvironmentVariable("FS_URL"), req.Scheme + "://" + req.Host.Value + req.Path.Value.Substring(0, req.Path.Value.IndexOf(res) - 1)); } var str = fhirresp.Content == null ? "" : (string)fhirresp.Content; /* Fix server locations to proxy address */ str = str.Replace(Environment.GetEnvironmentVariable("FS_URL"), req.Scheme + "://" + req.Host.Value + req.Path.Value.Substring(0, req.Path.Value.IndexOf(res) - 1)); result = JObject.Parse(str); /* Add Headers from FHIR Server Response */ foreach (string key in fhirresp.Headers.Keys) { req.HttpContext.Response.Headers.Remove(key); req.HttpContext.Response.Headers.Add(key, fhirresp.Headers[key].Value); } var jr = new JsonResult(result); jr.StatusCode = (int)fhirresp.StatusCode; return jr; } } }
using EddiConfigService; using EddiCore; using EddiDataDefinitions; using EddiDataProviderService; using EddiEvents; using EddiNavigationService; using EddiStarMapService; using EddiStatusService; using JetBrains.Annotations; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Threading; using Utilities; namespace EddiNavigationMonitor { [UsedImplicitly] public class NavigationMonitor : IEddiMonitor { public FleetCarrier FleetCarrier => EDDI.Instance.FleetCarrier; #region Collections // Observable collection for us to handle changes to Bookmarks public ObservableCollection<NavBookmark> Bookmarks = new ObservableCollection<NavBookmark>(); public ObservableCollection<NavBookmark> GalacticPOIs = new ObservableCollection<NavBookmark>(); // Navigation route data public NavWaypointCollection NavRoute = new NavWaypointCollection() { FillVisitedGaps = true }; // Plotted carrier route data public NavWaypointCollection CarrierPlottedRoute = new NavWaypointCollection() { FillVisitedGaps = true }; // Plotted ship route data public NavWaypointCollection PlottedRoute = new NavWaypointCollection(); #endregion public static readonly object navConfigLock = new object(); private DateTime updateDat; internal Status currentStatus { get; set; } public string MonitorName() { return "Navigation monitor"; } public string LocalizedMonitorName() { return Properties.NavigationMonitor.navigation_monitor_name; } public string MonitorDescription() { return Properties.NavigationMonitor.navigation_monitor_desc; } public bool IsRequired() { return true; } public NavigationMonitor() { BindingOperations.CollectionRegistering += NavigationMonitor_CollectionRegistering; StatusService.StatusUpdatedEvent += OnStatusUpdated; LoadMonitor(); Logging.Info($"Initialized {MonitorName()}"); } private void LoadMonitor() { ReadNavConfig(); GetGalacticPOIs(); } private void GetGalacticPOIs() { // Build a Galactic POI list GalacticPOIs = EDAstro.GetPOIs(); GetBookmarkExtras(GalacticPOIs); } private void NavigationMonitor_CollectionRegistering(object sender, CollectionRegisteringEventArgs e) { if (Application.Current != null) { // Synchronize this collection between threads BindingOperations.EnableCollectionSynchronization(Bookmarks, navConfigLock); BindingOperations.EnableCollectionSynchronization(GalacticPOIs, navConfigLock); BindingOperations.EnableCollectionSynchronization(NavRoute.Waypoints, navConfigLock); BindingOperations.EnableCollectionSynchronization(PlottedRoute.Waypoints, navConfigLock); BindingOperations.EnableCollectionSynchronization(CarrierPlottedRoute.Waypoints, navConfigLock); } else { // If started from VoiceAttack, the dispatcher is on a different thread. Invoke synchronization there. Dispatcher.CurrentDispatcher.Invoke(() => { BindingOperations.EnableCollectionSynchronization(Bookmarks, navConfigLock); }); Dispatcher.CurrentDispatcher.Invoke(() => { BindingOperations.EnableCollectionSynchronization(GalacticPOIs, navConfigLock); }); Dispatcher.CurrentDispatcher.Invoke(() => { BindingOperations.EnableCollectionSynchronization(NavRoute.Waypoints, navConfigLock); }); Dispatcher.CurrentDispatcher.Invoke(() => { BindingOperations.EnableCollectionSynchronization(PlottedRoute.Waypoints, navConfigLock); }); Dispatcher.CurrentDispatcher.Invoke(() => { BindingOperations.EnableCollectionSynchronization(CarrierPlottedRoute.Waypoints, navConfigLock); }); } } public bool NeedsStart() { return false; } public void Start() { } public void Stop() { } public void Reload() { LoadMonitor(); Logging.Info($"Reloaded {MonitorName()}"); } public UserControl ConfigurationTabItem() { return ConfigurationWindow.Instance; } public void HandleProfile(JObject profile) { } public void PreHandle(Event @event) { if (@event.timestamp >= updateDat) { // Handle the events that we care about if (@event is CarrierJumpRequestEvent carrierJumpRequestEvent) { handleCarrierJumpRequestEvent(carrierJumpRequestEvent); } else if (@event is CarrierJumpCancelledEvent carrierJumpCancelledEvent) { handleCarrierJumpCancelledEvent(carrierJumpCancelledEvent); } else if (@event is CarrierJumpedEvent carrierJumpedEvent) { handleCarrierJumpedEvent(carrierJumpedEvent); } else if (@event is CarrierJumpEngagedEvent carrierJumpEngagedEvent) { handleCarrierJumpEngagedEvent(carrierJumpEngagedEvent); } else if (@event is CarrierPurchasedEvent carrierPurchasedEvent) { handleCarrierPurchasedEvent(carrierPurchasedEvent); } else if (@event is CarrierStatsEvent carrierStatsEvent) { handleCarrierStatsEvent(carrierStatsEvent); } else if (@event is CommodityPurchasedEvent commodityPurchasedEvent) { handleCommodityPurchasedEvent(commodityPurchasedEvent); } else if (@event is CommoditySoldEvent commoditySoldEvent) { handleCommoditySoldEvent(commoditySoldEvent); } else if (@event is DockedEvent dockedEvent) { handleDockedEvent(dockedEvent); } else if (@event is EnteredNormalSpaceEvent enteredNormalSpaceEvent) { handleEnteredNormalSpaceEvent(enteredNormalSpaceEvent); } else if (@event is JumpedEvent jumpedEvent) { handleJumpedEvent(jumpedEvent); } else if (@event is LocationEvent locationEvent) { handleLocationEvent(locationEvent); } else if (@event is NavRouteEvent navRouteEvent) { handleNavRouteEvent(navRouteEvent); } else if (@event is RouteDetailsEvent routeDetailsEvent) { handleRouteDetailsEvent(routeDetailsEvent); } else if (@event is FSDTargetEvent fsdTargetEvent) { handleFSDTargetEvent(fsdTargetEvent); } } } public void PostHandle(Event @event) { if (@event is CarrierJumpRequestEvent || @event is CarrierJumpEngagedEvent || @event is CarrierJumpedEvent || @event is CarrierPurchasedEvent || @event is CarrierStatsEvent || @event is CommanderContinuedEvent) { if (!@event.fromLoad) { EDDI.Instance.RefreshFleetCarrierFromFrontierAPI(); } } else if (@event is NavRouteEvent navRouteEvent) { posthandleNavRouteEvent(navRouteEvent); } else if (@event is LiftoffEvent liftoffEvent) { posthandleLiftoffEvent(liftoffEvent); } else if (@event is TouchdownEvent touchdownEvent) { posthandleTouchdownEvent(touchdownEvent); } else if (@event is UndockedEvent undockedEvent) { posthandleUndockedEvent(undockedEvent); } } #region handledEvents private void handleCarrierJumpRequestEvent(CarrierJumpRequestEvent @event) { var updatedCarrier = FleetCarrier?.Copy() ?? new FleetCarrier(@event.carrierId); updatedCarrier.nextStarSystem = @event.systemname; EDDI.Instance.FleetCarrier = updatedCarrier; if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleCarrierJumpCancelledEvent(CarrierJumpCancelledEvent @event) { var updatedCarrier = FleetCarrier?.Copy() ?? new FleetCarrier(@event.carrierId); updatedCarrier.nextStarSystem = null; EDDI.Instance.FleetCarrier = updatedCarrier; if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleCarrierJumpedEvent(CarrierJumpedEvent @event) { var updatedCarrier = FleetCarrier?.Copy() ?? new FleetCarrier(@event.carrierId) { name = @event.carriername }; updatedCarrier.currentStarSystem = @event.systemname; updatedCarrier.Market.name = @event.carriername; updatedCarrier.nextStarSystem = null; EDDI.Instance.FleetCarrier = updatedCarrier; CarrierPlottedRoute.UpdateVisitedStatus(@event.systemAddress); updateNavigationData(@event.timestamp, @event.systemAddress, @event.x, @event.y, @event.z); if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleCarrierJumpEngagedEvent(CarrierJumpEngagedEvent @event) { var updatedCarrier = FleetCarrier?.Copy() ?? new FleetCarrier(@event.carrierId); updatedCarrier.currentStarSystem = @event.systemname; EDDI.Instance.FleetCarrier = updatedCarrier; CarrierPlottedRoute.UpdateVisitedStatus(@event.systemAddress); if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleCarrierPurchasedEvent(CarrierPurchasedEvent @event) { EDDI.Instance.FleetCarrier = new FleetCarrier(@event.carrierId) { callsign = @event.callsign, currentStarSystem = @event.systemname }; if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleCarrierStatsEvent(CarrierStatsEvent @event) { var updatedCarrier = FleetCarrier?.Copy() ?? new FleetCarrier(@event.carrierID) { callsign = @event.callsign, name = @event.name }; updatedCarrier.dockingAccess = @event.dockingAccess; updatedCarrier.notoriousAccess = @event.notoriousAccess; updatedCarrier.fuel = @event.fuel; updatedCarrier.usedCapacity = @event.usedCapacity; updatedCarrier.freeCapacity = @event.freeCapacity; updatedCarrier.bankBalance = @event.bankBalance; updatedCarrier.bankReservedBalance = @event.bankReservedBalance; EDDI.Instance.FleetCarrier = updatedCarrier; if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleCommodityPurchasedEvent(CommodityPurchasedEvent @event) { if (FleetCarrier != null && @event.marketid == FleetCarrier?.carrierID) { if (@event.commodityDefinition?.edname?.ToLowerInvariant() == "tritium") { FleetCarrier.fuelInCargo -= @event.amount; if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } } } private void handleCommoditySoldEvent(CommoditySoldEvent @event) { if (FleetCarrier != null && @event.marketid == FleetCarrier?.carrierID) { if (@event.commodityDefinition?.edname?.ToLowerInvariant() == "tritium") { FleetCarrier.fuelInCargo += @event.amount; if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } } } private void handleDockedEvent(DockedEvent @event) { updateNavigationData(@event.timestamp, @event.systemAddress); if (!@event.fromLoad && @event.timestamp >= updateDat) { lock (navConfigLock) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; // Check if we're at a planetary location and capture our location if true if ((currentStatus?.near_surface ?? false) && new Station { Model = @event.stationModel }.IsPlanetary()) { navConfig.tdLat = currentStatus.latitude; navConfig.tdLong = currentStatus.longitude; navConfig.tdPOI = @event.station; // If we are at our fleet carrier, make sure that the carrier location is up to date. if (@event.marketId != null && FleetCarrier != null && @event.marketId == FleetCarrier.carrierID) { FleetCarrier.currentStarSystem = @event.system; CarrierPlottedRoute.UpdateVisitedStatus(@event.systemAddress); navConfig.carrierPlottedRoute = CarrierPlottedRoute; } } navConfig.updatedat = updateDat; ConfigService.Instance.navigationMonitorConfiguration = navConfig; } } } private void handleLocationEvent(LocationEvent @event) { updateNavigationData(@event.timestamp, @event.systemAddress, @event.x, @event.y, @event.z); if (!@event.fromLoad && @event.timestamp >= updateDat) { // If we are at our fleet carrier, make sure that the carrier location is up to date. lock (navConfigLock) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; if (@event.marketId != null && FleetCarrier != null && @event.marketId == FleetCarrier.carrierID) { FleetCarrier.currentStarSystem = @event.systemname; CarrierPlottedRoute.UpdateVisitedStatus(@event.systemAddress); navConfig.carrierPlottedRoute = CarrierPlottedRoute; } ConfigService.Instance.navigationMonitorConfiguration = navConfig; } updateDat = @event.timestamp; WriteNavConfig(); } } private void handleJumpedEvent(JumpedEvent @event) { updateNavigationData(@event.timestamp, @event.systemAddress, @event.x, @event.y, @event.z); if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleEnteredNormalSpaceEvent(EnteredNormalSpaceEvent @event) { updateNavigationData(@event.timestamp, @event.systemAddress); if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } private void handleNavRouteEvent(NavRouteEvent @event) { if (!@event.fromLoad && @event.timestamp >= updateDat) { var routeList = @event.route?.Select(r => new NavWaypoint(r)).ToList(); if (routeList != null) { if (routeList.Count > 1 && routeList[0].systemName == EDDI.Instance?.CurrentStarSystem?.systemname) { // Update the Nav Route routeList[0].visited = true; NavRoute.Waypoints.Clear(); NavRoute.AddRange(routeList); NavRoute.PopulateMissionIds(ConfigService.Instance.missionMonitorConfiguration.missions?.ToList()); // Update destination data var start = routeList.FirstOrDefault(); var end = routeList.LastOrDefault(); if (start != null && end != null) { var distance = Functions.StellarDistanceLy(start.x, start.y, start.z, end.x, end.y, end.z) ?? 0; UpdateDestinationData(end.systemName, distance); } } // Update the navigation configuration updateDat = @event.timestamp; WriteNavConfig(); } } } private void posthandleNavRouteEvent(NavRouteEvent @event) { if (!@event.fromLoad && @event.timestamp >= updateDat) { var routeList = @event.route?.Select(r => new NavWaypoint(r)).ToList(); if (routeList != null) { if (routeList.Count == 0) { UpdateDestinationData(null, 0); NavRoute.Waypoints.Clear(); } // Update the navigation configuration updateDat = @event.timestamp; WriteNavConfig(); } } } private void posthandleTouchdownEvent(TouchdownEvent @event) { updateNavigationData(@event.timestamp, @event.systemAddress); if (!@event.fromLoad && @event.timestamp >= updateDat) { lock (navConfigLock) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; navConfig.tdLat = @event.latitude; navConfig.tdLong = @event.longitude; navConfig.tdPOI = @event.nearestdestination; navConfig.updatedat = updateDat; ConfigService.Instance.navigationMonitorConfiguration = navConfig; } } } private void posthandleLiftoffEvent(LiftoffEvent @event) { updateNavigationData(@event.timestamp, @event.systemAddress); if (!@event.fromLoad && @event.timestamp >= updateDat) { lock (navConfigLock) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; navConfig.tdLat = null; navConfig.tdLong = null; navConfig.tdPOI = null; navConfig.updatedat = updateDat; ConfigService.Instance.navigationMonitorConfiguration = navConfig; } } } private void posthandleUndockedEvent(UndockedEvent @event) { if (!@event.fromLoad && @event.timestamp >= updateDat) { lock (navConfigLock) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; navConfig.tdLat = null; navConfig.tdLong = null; navConfig.tdPOI = null; navConfig.updatedat = updateDat; ConfigService.Instance.navigationMonitorConfiguration = navConfig; } } } private void handleRouteDetailsEvent(RouteDetailsEvent routeDetailsEvent) { if (routeDetailsEvent.routetype == QueryType.carrier.ToString()) { if (routeDetailsEvent.Route?.Waypoints.GetHashCode() == CarrierPlottedRoute.Waypoints.GetHashCode()) { // Displayed route is correct, nothing to do here } else if (routeDetailsEvent.Route != null) { CarrierPlottedRoute.Waypoints.Clear(); Thread.Sleep(5); // A small delay helps ensure that any straggling entries are removed from the UI DataGrid CarrierPlottedRoute.AddRange(routeDetailsEvent.Route.Waypoints); CarrierPlottedRoute.FillVisitedGaps = routeDetailsEvent.Route.FillVisitedGaps; } else { CarrierPlottedRoute.Waypoints.Clear(); } } else { if (routeDetailsEvent.Route?.Waypoints.GetHashCode() == PlottedRoute.Waypoints.GetHashCode()) { // Displayed route is correct, nothing to do here } else if (routeDetailsEvent.Route != null) { PlottedRoute.Waypoints.Clear(); Thread.Sleep(5); // A small delay helps ensure that any straggling entries are removed from the UI DataGrid PlottedRoute.AddRange(routeDetailsEvent.Route.Waypoints); PlottedRoute.FillVisitedGaps = routeDetailsEvent.Route.FillVisitedGaps; PlottedRoute.PopulateMissionIds(ConfigService.Instance.missionMonitorConfiguration.missions ?.ToList()); } else { PlottedRoute.Waypoints.Clear(); } if (routeDetailsEvent.routetype == QueryType.set.ToString()) { PlottedRoute.GuidanceEnabled = true; } else if (routeDetailsEvent.routetype == QueryType.cancel.ToString()) { PlottedRoute.GuidanceEnabled = false; } } // Update the navigation configuration if (!routeDetailsEvent.fromLoad && routeDetailsEvent.timestamp >= updateDat) { updateDat = routeDetailsEvent.timestamp; WriteNavConfig(); } } private void handleFSDTargetEvent(FSDTargetEvent @event) { // Update our plotted route star class data if this event provides new details about the targeted star class. var wp = PlottedRoute.Waypoints.FirstOrDefault(w => w.systemAddress == (ulong?)@event.systemAddress); if (wp != null && wp.stellarclass != @event.starclass) { wp.stellarclass = @event.starclass; wp.isScoopable = !string.IsNullOrEmpty(@event.starclass) && "KGBFOAM".Contains(@event.starclass); wp.hasNeutronStar = !string.IsNullOrEmpty(@event.starclass) && "N".Contains(@event.starclass); } if (!@event.fromLoad && @event.timestamp >= updateDat) { updateDat = @event.timestamp; WriteNavConfig(); } } #endregion public IDictionary<string, Tuple<Type, object>> GetVariables() { lock ( navConfigLock ) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; return new Dictionary<string, Tuple<Type, object>> { // Bookmark info ["bookmarks"] = new Tuple<Type, object>(typeof(List<NavBookmark>), Bookmarks.ToList() ), ["galacticPOIs"] = new Tuple<Type, object>(typeof(NavBookmark), GalacticPOIs ), // Route plotting info ["navRoute"] = new Tuple<Type, object>(typeof(NavWaypointCollection), NavRoute ), ["carrierPlottedRoute"] = new Tuple<Type, object>(typeof(NavWaypointCollection), CarrierPlottedRoute ), ["shipPlottedRoute"] = new Tuple<Type, object>(typeof(NavWaypointCollection), PlottedRoute ), // NavConfig info ["orbitalpriority"] = new Tuple<Type, object>(typeof(bool), navConfig.prioritizeOrbitalStations ), ["maxStationDistance"] = new Tuple<Type, object>(typeof(int?), navConfig.maxSearchDistanceFromStarLs ) }; } } public void WriteNavConfig() { lock (navConfigLock) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; // Bookmarks navConfig.bookmarks = Bookmarks; // In-game routing navConfig.navRouteList = NavRoute; // Plotted Routes navConfig.plottedRouteList = PlottedRoute; navConfig.carrierPlottedRoute = CarrierPlottedRoute; // Misc navConfig.updatedat = updateDat; ConfigService.Instance.navigationMonitorConfiguration = navConfig; } } private void ReadNavConfig() { lock (navConfigLock) { var navConfig = ConfigService.Instance.navigationMonitorConfiguration; // Restore our bookmarks Bookmarks = navConfig.bookmarks ?? new ObservableCollection<NavBookmark>(); GetBookmarkExtras(Bookmarks); // Restore our in-game routing NavRoute = navConfig.navRouteList ?? new NavWaypointCollection(true); // Restore our plotted routes PlottedRoute = navConfig.plottedRouteList ?? new NavWaypointCollection(); CarrierPlottedRoute = navConfig.carrierPlottedRoute ?? new NavWaypointCollection(true); // Misc updateDat = navConfig.updatedat; } } public void RemoveBookmarkAt(int index) { lock (navConfigLock) { Bookmarks.RemoveAt(index); } } private void updateNavigationData(DateTime timestamp, ulong? systemAddress, decimal? x = null, decimal? y = null, decimal? z = null) { if (systemAddress is null) { return; } // Distances Data if (x != null && y != null && z != null) { foreach (var navBookmark in Bookmarks.AsParallel()) { navBookmark.distanceLy = Functions.StellarDistanceLy(x, y, z, navBookmark.x, navBookmark.y, navBookmark.z); if (navBookmark.systemAddress == systemAddress) { navBookmark.visitLog.Add(timestamp); } } foreach (var poiBookmark in GalacticPOIs.AsParallel()) { poiBookmark.distanceLy = Functions.StellarDistanceLy(x, y, z, poiBookmark.x, poiBookmark.y, poiBookmark.z); if (poiBookmark.systemAddress == systemAddress) { poiBookmark.visitLog.Add(timestamp); } } Application.Current.Dispatcher.Invoke( () => { if ( ConfigurationWindow.Instance.TryFindResource( nameof( GalacticPOIControl.POIView ) ) is ICollectionView poiView ) { poiView.Refresh(); } } ); NavigationService.Instance.SearchDistanceLy = Functions.StellarDistanceLy(x, y, z, NavigationService.Instance.SearchStarSystem?.x, NavigationService.Instance.SearchStarSystem?.y, NavigationService.Instance.SearchStarSystem?.z) ?? 0; } // Visited Data NavRoute.UpdateVisitedStatus((ulong)systemAddress); PlottedRoute.UpdateVisitedStatus((ulong)systemAddress); if (PlottedRoute.GuidanceEnabled && PlottedRoute.Waypoints.All(w => w.visited)) { // Deactivate guidance once we've reached our destination. NavigationService.Instance.NavQuery(QueryType.cancel, null, null, null, null, true); } } public void UpdateDestinationData(string system, decimal distance) { EDDI.Instance.updateDestinationSystem(system); EDDI.Instance.DestinationDistanceLy = distance; } private void OnStatusUpdated(object sender, EventArgs e) { if (sender is Status status) { LockManager.GetLock(nameof(currentStatus), () => { currentStatus = status; }); foreach (var bookmark in Bookmarks) { CheckBookmarkPosition(bookmark, currentStatus); } } } public void CheckBookmarkPosition(NavBookmark bookmark, Status status, bool emitEvent = true) { if (bookmark is null || status is null) { return; } // Calculate our position relative to the bookmark and whether we're nearby if (currentStatus.bodyname == bookmark.bodyname && currentStatus.near_surface) { // Update our bookmark heading and distance var surfaceDistanceKm = bookmark.useStraightPath ? SurfaceConstantHeadingDistanceKm(currentStatus, bookmark.latitude, bookmark.longitude) : SurfaceShortestPathDistanceKm(currentStatus, bookmark.latitude, bookmark.longitude); if (surfaceDistanceKm != null) { var trueDistanceKm = (decimal) Math.Sqrt(Math.Pow((double)surfaceDistanceKm, 2) + Math.Pow((double?) (status.altitude / 1000) ?? 0, 2)); bookmark.distanceKm = trueDistanceKm; bookmark.heading = bookmark.useStraightPath ? SurfaceConstantHeadingDegrees(currentStatus, bookmark.latitude, bookmark.longitude) : SurfaceShortestPathDegrees(currentStatus, bookmark.latitude, bookmark.longitude); var trueDistanceMeters = trueDistanceKm * 1000; if (!bookmark.nearby && trueDistanceMeters < bookmark.arrivalRadiusMeters) { // We've entered the nearby radius of the bookmark bookmark.nearby = true; if (emitEvent) { EDDI.Instance.enqueueEvent(new NearBookmarkEvent(status.timestamp, true, bookmark)); } } else if (bookmark.nearby && trueDistanceMeters >= (bookmark.arrivalRadiusMeters * 1.1M)) { // We've left the nearby radius of the bookmark // (calculated at 110% of the arrival radius to prevent bouncing between nearby and not) bookmark.nearby = false; if (emitEvent) { EDDI.Instance.enqueueEvent(new NearBookmarkEvent(status.timestamp, false, bookmark)); } } } } else if (bookmark.heading != null || bookmark.distanceKm != null) { // We're not at the body, clear bookmark position data bookmark.heading = null; bookmark.distanceKm = null; bookmark.nearby = false; } } private static decimal? SurfaceConstantHeadingDegrees(Status curr, decimal? bookmarkLatitude, decimal? bookmarkLongitude) { var radiusMeters = curr.planetradius ?? (EDDI.Instance?.CurrentStarSystem?.bodies ?.FirstOrDefault(b => b.bodyname == curr.bodyname) ?.radius * 1000); return Functions.SurfaceConstantHeadingDegrees(radiusMeters, curr.latitude, curr.longitude, bookmarkLatitude, bookmarkLongitude) ?? 0; } private static decimal? SurfaceConstantHeadingDistanceKm(Status curr, decimal? bookmarkLatitude, decimal? bookmarkLongitude) { var radiusMeters = curr.planetradius ?? (EDDI.Instance?.CurrentStarSystem?.bodies ?.FirstOrDefault(b => b.bodyname == curr.bodyname) ?.radius * 1000); return Functions.SurfaceConstantHeadingDistanceKm(radiusMeters, curr.latitude, curr.longitude, bookmarkLatitude, bookmarkLongitude) ?? 0; } private static decimal? SurfaceShortestPathDegrees(Status curr, decimal? bookmarkLatitude, decimal? bookmarkLongitude) { return Functions.SurfaceHeadingDegrees(curr.latitude, curr.longitude, bookmarkLatitude, bookmarkLongitude) ?? 0; } private static decimal? SurfaceShortestPathDistanceKm(Status curr, decimal? bookmarkLatitude, decimal? bookmarkLongitude) { var radiusMeters = curr.planetradius ?? (EDDI.Instance?.CurrentStarSystem?.bodies ?.FirstOrDefault(b => b.bodyname == curr.bodyname) ?.radius * 1000); return Functions.SurfaceDistanceKm(radiusMeters, curr.latitude, curr.longitude, bookmarkLatitude, bookmarkLongitude) ?? 0; } private async void GetBookmarkExtras<T>(ObservableCollection<T> bookmarks) where T : NavBookmark { // Retrieve extra details to supplement our bookmarks var bookmarkSystems = bookmarks.Select(n => new StarSystem() { systemname = n.systemname, systemAddress = n.systemAddress }).ToList(); var visitedBookmarkSystems = await Task.Run(() => { return new DataProviderService(new StarMapService(null, true)) .syncFromStarMapService(bookmarkSystems) .Where(s => s.visits > 0); }).ConfigureAwait(false); foreach (var system in visitedBookmarkSystems) { var poi = bookmarks.FirstOrDefault(s => s.systemAddress == system.systemAddress) ?? bookmarks.FirstOrDefault(s => s.systemname == system.systemname); if (poi != null) { poi.systemAddress = system.systemAddress; poi.visitLog = system.visitLog; bookmarks.Remove(poi); bookmarks.Add(poi); } } } } }
using Avaliador_Codigo_Fonte.Util; using System; namespace Avaliador_Codigo_Fonte { class Run { static void Main(string[] args) { Console.WriteLine("Digite o caminho do DataSet"); string caminho = Console.ReadLine(); caminho = caminho.Replace("\"","\\"); Reader reader = new Reader(); Console.WriteLine("Quantidade de pastas à serem analisadas: " + reader.ContaPastasTotal(caminho)); Console.WriteLine("Arquivos e seus respectivos diretórios:"); reader.NomesArquivos(caminho); // salvar no desktop csv reader.SetDataSource(); //salvar na pasta dataset csv //reader.SetDataSource(caminho); Console.WriteLine(); Console.WriteLine("**** AGUARDE ****"); reader.CaminhaDiretorioArquivo(caminho); Console.WriteLine("Favor, checar arquivo csv presente em: " + reader.GetDataSource()); } } }
using AW.Data.Domain; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AW.Data.Context { public sealed class WithdrawDbContextFactory : IDesignTimeDbContextFactory<WithdrawDbContext> { public WithdrawDbContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder<WithdrawDbContext>(); builder.UseSqlServer("Data Source=localhost;Initial Catalog=Withdraw.Prime;Trusted_Connection=True;", x => x.MigrationsHistoryTable("MigrationHistory")); return new WithdrawDbContext(builder.Options); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ResolutionAdapter : MonoBehaviour { private readonly float normalAspect = 0.5625f; private void Start() { var currentAspect = (float) Screen.width / Screen.height; transform.localScale = new Vector3(currentAspect / normalAspect, 1, 1); } }