text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using PhobiaX.SDL2; using SDL2; namespace PhobiaX.Actions { public class ActionBinder { private readonly SDLKeyboardStates keyboardStates; private Dictionary<GameAction, Action> gameActions = new Dictionary<GameAction, Action>(); private Dictionary<SDL.SDL_Scancode, bool> pressedKeys = new Dictionary<SDL.SDL_Scancode, bool>(); public ActionBinder(SDLKeyboardStates keyboardStates) { this.keyboardStates = keyboardStates ?? throw new ArgumentNullException(nameof(keyboardStates)); } public void Clear() { keyboardStates.Clear(); gameActions.Clear(); pressedKeys.Clear(); } public void AssignKeysToGameAction(GameAction action, bool isKeyReleased, params SDL.SDL_Scancode[] scancodes) { if (scancodes.Length == 1) { keyboardStates.RegisterEvents(scancodes[0], isKeyReleased, () => Evaluate(action)); } else if (scancodes.Length > 1) { foreach (var scancode in scancodes) { pressedKeys.Add(scancode, true); keyboardStates.RegisterEvents(scancode, !isKeyReleased, () => { pressedKeys[scancode] = !isKeyReleased; }); keyboardStates.RegisterEvents(scancode, isKeyReleased, () => { pressedKeys[scancode] = isKeyReleased; bool canExecute = true; foreach (var lscancode in scancodes) { canExecute &= pressedKeys[lscancode] == isKeyReleased; } if (canExecute) { Evaluate(action); } }); } } } public void RegisterPressAction(GameAction gameAction, Action actionMethod) { gameActions.Add(gameAction, actionMethod); } private void Evaluate(GameAction action) { if (gameActions.ContainsKey(action)) { gameActions[action](); } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class TopDownCameraController : MonoBehaviour { public Transform target; public Quaternion defaultRotation = Quaternion.Euler(0, 180, 0); public Vector3 offset; private TopDownCamera topDownCamera; private void Awake () { topDownCamera = new TopDownCamera(target, offset); // @ Rotate to face owner this.transform.rotation = defaultRotation; } private void LateUpdate () { topDownCamera.FollowTarget(this.transform); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class LevelController : MonoBehaviour { public GameObject SQLPrefab; public GameObject PriviligedEscilationPrefab; public GameObject DDoSPrefab; public GameObject MalwarePrefab; public GameObject InsiderThreatPrefab; public GameObject PasstheHashAttachPrefab; public GameObject EventLogAnalyzerPowerUp; public GameObject ADSolutionsPowerUp; public GameObject PasswordManagerProPowerUp; public GameObject spawners; public GameObject powerUpSpawners; public GameObject gameOverUI; public Text WaveText; public int currentWave = 1; private IEnumerator WaveOne; private IEnumerator WaveTwo; private IEnumerator WaveThree; private IEnumerator WaveFour; private IEnumerator WaveFive; private IEnumerator WaveSix; private IEnumerator Endless; // Use this for initialization void Start () { WaveOne = WaveOneCo (); WaveTwo = WaveTwoCo (); WaveThree = WaveThreeCo (); WaveFour = WaveFourCo (); WaveFive = WaveFiveCo (); WaveSix = WaveSixCo (); Endless = EndlessCo (); StartCoroutine(WaveOne); } // Update is called once per frame void Update () { } public void GameOver () { Debug.Log ("GameOver"); PlayerPrefs.SetInt("Player Score", GetComponent<ScoreKeeper>().score); GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy"); for (int i = 0; i < enemies.Length; i++) { Destroy (enemies [i]); } GameObject[] powerUp = GameObject.FindGameObjectsWithTag ("PowerUp"); for (int i = 0; i < powerUp.Length; i++) { Destroy (powerUp [i]); } StopCoroutine (WaveOne); StopCoroutine (WaveTwo); StopCoroutine (WaveThree); StopCoroutine (WaveFour); StartCoroutine (SwitchScene ()); } private IEnumerator SwitchScene() { WaveText.GetComponent<Text> ().text = "Game Over"; yield return new WaitForSeconds (2); Fading fade = GameObject.Find ("Fade").GetComponent<Fading> (); fade.fadeSpeed = 0.8f; float fadeTime = fade.BeginFade (1); yield return new WaitForSeconds (fadeTime); Application.LoadLevel(2); } private IEnumerator WaveOneCo() { Debug.Log ("Wave One"); yield return new WaitForSeconds(4); WaveText.GetComponent<Text> ().text = "WARNING: SQL Injections Detected"; yield return new WaitForSeconds(4); WaveText.GetComponent<Text> ().text = ""; Instantiate(SQLPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(4); Instantiate(SQLPrefab, spawners.transform.GetChild(2).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(4).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(10); StartCoroutine(WaveTwo); } private IEnumerator WaveTwoCo() { Debug.Log ("Wave Two"); currentWave = 2; WaveText.GetComponent<Text> ().text = "WARNING: DDoS Attacks Detected"; yield return new WaitForSeconds(3); WaveText.GetComponent<Text> ().text = ""; Instantiate(DDoSPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(7); Instantiate(DDoSPrefab, spawners.transform.GetChild(4).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(DDoSPrefab, spawners.transform.GetChild(0).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(8); Instantiate(SQLPrefab, spawners.transform.GetChild(0).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(DDoSPrefab, spawners.transform.GetChild(4).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(DDoSPrefab, spawners.transform.GetChild(8).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(0.75f); Instantiate(SQLPrefab, spawners.transform.GetChild(2).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(DDoSPrefab, spawners.transform.GetChild(7).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(3); Instantiate(EventLogAnalyzerPowerUp, powerUpSpawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(8); StartCoroutine(WaveThree); } private IEnumerator WaveThreeCo() { Debug.Log ("Wave Three"); currentWave = 3; WaveText.GetComponent<Text> ().text = "WARNING: Priviliged Escilation Attacks Detected"; yield return new WaitForSeconds(3); WaveText.GetComponent<Text> ().text = ""; Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(5); Instantiate(SQLPrefab, spawners.transform.GetChild(0).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(2); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(4).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(4); Instantiate(SQLPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(2).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds (1); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds (3); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(4); StartCoroutine(WaveFour); } private IEnumerator WaveFourCo() { Debug.Log ("Wave four"); currentWave = 4; WaveText.GetComponent<Text> ().text = "Warning: Malware Detected"; yield return new WaitForSeconds(3); WaveText.GetComponent<Text> ().text = ""; Instantiate(MalwarePrefab); yield return new WaitForSeconds(5); Instantiate(SQLPrefab, spawners.transform.GetChild(0).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(MalwarePrefab); yield return new WaitForSeconds(5); Instantiate(ADSolutionsPowerUp, powerUpSpawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(MalwarePrefab); Instantiate(DDoSPrefab, spawners.transform.GetChild(8).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(1); Instantiate(SQLPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(1); Instantiate(MalwarePrefab); Instantiate(SQLPrefab, spawners.transform.GetChild(2).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(7).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(2); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(7).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(8); StartCoroutine(WaveFive); } private IEnumerator WaveFiveCo (){ Debug.Log ("Wave five"); currentWave = 5; WaveText.GetComponent<Text> ().text = "WARNING: Inside Threats Detected"; yield return new WaitForSeconds(3); WaveText.GetComponent<Text> ().text = ""; Instantiate(InsiderThreatPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(5); Instantiate(SQLPrefab, spawners.transform.GetChild(0).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(InsiderThreatPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(5); Instantiate(MalwarePrefab); Instantiate(DDoSPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(InsiderThreatPrefab, spawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(10); StartCoroutine(WaveSix); } private IEnumerator WaveSixCo (){ Debug.Log ("Wave Six"); currentWave = 6; WaveText.GetComponent<Text> ().text = "Warning: Pass-the-Hash Attacks Detected"; yield return new WaitForSeconds(3); WaveText.GetComponent<Text> ().text = ""; Instantiate(PasstheHashAttachPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(5); Instantiate(SQLPrefab, spawners.transform.GetChild(0).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PasstheHashAttachPrefab, spawners.transform.GetChild(5).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PasswordManagerProPowerUp, powerUpSpawners.transform.GetChild(2).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(5); Instantiate(MalwarePrefab); Instantiate(DDoSPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(SQLPrefab, spawners.transform.GetChild(3).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(1).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(10); StartCoroutine(Endless); } private IEnumerator EndlessCo () { Debug.Log ("Endless"); currentWave = 0; WaveText.GetComponent<Text> ().text = "Endless"; yield return new WaitForSeconds(4); WaveText.GetComponent<Text> ().text = ""; while (true) { yield return new WaitForSeconds(3); Instantiate(SQLPrefab, spawners.transform.GetChild(2).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(MalwarePrefab); yield return new WaitForSeconds(3); Instantiate(PasswordManagerProPowerUp, powerUpSpawners.transform.GetChild(2).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(PriviligedEscilationPrefab, spawners.transform.GetChild(4).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(DDoSPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); yield return new WaitForSeconds(4); Instantiate(PasstheHashAttachPrefab, spawners.transform.GetChild(4).transform.position, Quaternion.Euler(0, 0, 0)); Instantiate(InsiderThreatPrefab, spawners.transform.GetChild(6).transform.position, Quaternion.Euler(0, 0, 0)); } } }
using System.Collections.Generic; using System.Linq; using TexturePacker.Editor.Repository; using UnityEditor; using UnityEngine; namespace TexturePacker.Editor.Editors { [CustomEditor(typeof(TexturePackerSpriteSelector))] public class TexturePackerSpriteSelectorEditor : UnityEditor.Editor { private const int MaxDepth = 100; private const int IndentWidth = 20; private const string SimpleItemPrefix = "├─"; private const string LastItemPrefix = "└─"; private readonly Color _defaultLabelColor = new Color(.7f, .7f, .7f); private TextureRepository _textureRepository; private List<TextureRepository> _textureRepositories; private string[] _textureRepositoryNames; private Vector2 _textureRepositoryTreeScroll; private SpriteRenderer _spriteRenderer; private Sprite Sprite { get { return _spriteRenderer.sprite; } set { _spriteRenderer.sprite = value; } } private void OnEnable() { LoadTextureRepositories(); } public override void OnInspectorGUI() { FindProperties(); Init(); if (_textureRepositories.Count == 0) { EditorGUILayout.HelpBox("You don't have any instance of TextureRepository", MessageType.Error); return; } DrawTextureRepositorySelectorEditor(); DrawTextureRepositoryTree(); } private void FindProperties() { _spriteRenderer = serializedObject.FindProperty("_spriteRenderer").objectReferenceValue as SpriteRenderer; } private void Init() { if (_textureRepositories == null) LoadTextureRepositories(); } private void LoadTextureRepositories() { _textureRepositories = AssetDatabaseHelper.LoadAllAssets<TextureRepository>(); _textureRepositoryNames = _textureRepositories.Select(x => x.name).ToArray(); if (_textureRepositories.Count > 0) _textureRepository = _textureRepositories[0]; } private void DrawTextureRepositorySelectorEditor() { var index = _textureRepositories.IndexOf(_textureRepository); index = EditorGUILayout.Popup("Texture repository", index, _textureRepositoryNames); _textureRepository = _textureRepositories[index]; } private void DrawTextureRepositoryTree() { _textureRepositoryTreeScroll = EditorGUILayout.BeginScrollView(_textureRepositoryTreeScroll, GUI.skin.box); DrawFolder(_textureRepository.Root, 0); EditorGUI.indentLevel = 0; EditorGUILayout.EndScrollView(); } private void DrawFolder(Folder folder, int depth) { if (depth > MaxDepth) { Debug.LogError("Limit of depth"); return; } foreach (var f in folder.Folders) { EditorGUILayout.BeginHorizontal(); GUILayout.Space(depth * IndentWidth); GUILayout.Label(SimpleItemPrefix, GUILayout.Width(IndentWidth)); if (GUILayout.Button(f.Name, EditorStyles.miniButton)) f.Collapsed = !f.Collapsed; EditorGUILayout.EndHorizontal(); if (!f.Collapsed) DrawFolder(f, depth+1); } for (var index = 0; index < folder.SpriteDescriptions.Count; index++) { var spriteDescription = folder.SpriteDescriptions[index]; EditorGUILayout.BeginHorizontal(); GUILayout.Space(depth * IndentWidth); GUILayout.Label(index == folder.SpriteDescriptions.Count-1 ? LastItemPrefix : SimpleItemPrefix, GUILayout.Width(IndentWidth)); if (!CheckForSelection(spriteDescription)) GUI.color = _defaultLabelColor; if (GUILayout.Button(spriteDescription.FileName, GUI.skin.label)) Select(spriteDescription); GUI.color = Color.white; EditorGUILayout.EndHorizontal(); } } private bool CheckForSelection(SpriteDescription spriteDescription) { return Sprite == spriteDescription.Sprite; } private void Select(SpriteDescription spriteDescription) { if (Sprite == spriteDescription.Sprite) { Sprite = null; return; } Sprite = spriteDescription.Sprite; } } }
namespace HelloName { using System; public class StartUp { public static void Main() { string name = Console.ReadLine(); PrintGreetingByName(name); } public static void PrintGreetingByName(string name) { Console.WriteLine($"Hello, {name}!"); } } }
using System; using System.Collections.Generic; namespace Ludotek.Api.Dto { public partial class LudoTagDto { /// <summary> /// Id item /// </summary> public int LudothequeId { get; set; } /// <summary> /// Id tag /// </summary> public int TagId { get; set; } /// <summary> /// Foreign keys /// </summary> public LudothequeDto Ludotheque { get; set; } public TagDto Tag { get; set; } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Bot Framework: http://botframework.com // // Personality Chat based Dialogs for Bot Builder: // https://github.com/Microsoft/BotBuilder-PersonalityChat // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Microsoft.Bot.Builder.PersonalityChat.Sample.Basic { using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; [BotAuthentication] public class MessagesController : ApiController { /// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task<HttpResponseMessage> Post([FromBody]Activity activity) { if (activity.Type == ActivityTypes.Message) { await Conversation.SendAsync(activity, () => new BasicPersonalityChatBotDialog()); } else { this.HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return response; } private Activity HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { // Handle conversation state changes, like members being added and removed // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info // Not available in all channels } else if (message.Type == ActivityTypes.ContactRelationUpdate) { // Handle add/remove from contact lists // Activity.From + Activity.Action represent what happened } else if (message.Type == ActivityTypes.Typing) { // Handle knowing that the user is typing } else if (message.Type == ActivityTypes.Ping) { } return null; } } }
using System; namespace Admin.ResultModels { public class EditOrderStatusResult { public bool Success {get;set;} } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace ServiceQuotes.Infrastructure.Migrations { public partial class AddedMaterialEntity : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Material", columns: table => new { Id = table.Column<Guid>(type: "uuid", nullable: false), ServiceRequestId = table.Column<Guid>(type: "uuid", nullable: false), Description = table.Column<string>(type: "text", nullable: true), Quantity = table.Column<int>(type: "integer", nullable: false), UnitPrice = table.Column<decimal>(type: "numeric", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Material", x => x.Id); table.ForeignKey( name: "FK_Material_ServiceRequests_ServiceRequestId", column: x => x.ServiceRequestId, principalTable: "ServiceRequests", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Material_ServiceRequestId", table: "Material", column: "ServiceRequestId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Material"); } } }
using System.Collections.Generic; namespace DomainEventsTest.SharingContext.DataDrivenTests { public class InternalHealthDamageTestData { public static IEnumerable<object[]> TestData { get { yield return new object[] { 0, 100 }; yield return new object[] { 1, 99 }; yield return new object[] { 25, 75 }; yield return new object[] { 50, 50 }; yield return new object[] { -1, 101 }; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using SimpleJSON; public class GetOut : MonoBehaviour { public GameObject ValidationError, vanny; private IEnumerator LoginOut() { string url = Link.url + "logout"; WWWForm form = new WWWForm(); form.AddField(Link.DEVICE_ID, PlayerPrefs.GetString(Link.DEVICE_ID)); form.AddField(Link.EMAIL, PlayerPrefs.GetString(Link.EMAIL)); form.AddField(Link.PASSWORD, PlayerPrefs.GetString(Link.PASSWORD)); WWW www = new WWW(url, form); yield return www; if (www.error == null) { var jsonString = JSON.Parse(www.text); LogoutKey(); //PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); //PlayerPrefs.DeleteKey("SummonTutor"); SceneManagerHelper.LoadScene(Link.Register); //PlayerPrefs.DeleteKey("tutorhitung"); //PlayerPrefs.DeleteKey(Link.LOGIN_BY); } } private void LogoutKey() { PlayerPrefs.DeleteKey(Link.ID); PlayerPrefs.DeleteKey(Link.LOGIN_BY); PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); PlayerPrefs.DeleteKey(Link.STATUS_BATTLE); PlayerPrefs.DeleteKey(Link.EMAIL); PlayerPrefs.DeleteKey(Link.USER_NAME); PlayerPrefs.DeleteKey(Link.FULL_NAME); PlayerPrefs.DeleteKey(Link.AP); PlayerPrefs.DeleteKey(Link.AR); PlayerPrefs.DeleteKey(Link.PASSWORD); PlayerPrefs.DeleteKey(Link.DEVICE_ID); PlayerPrefs.DeleteKey(Link.PASSWORD); PlayerPrefs.DeleteKey(Link.Stage); PlayerPrefs.DeleteKey(Link.IBURU); PlayerPrefs.DeleteKey(Link.IGOLD); PlayerPrefs.DeleteKey(Link.IENERGY); PlayerPrefs.DeleteKey(Link.GOLD); PlayerPrefs.DeleteKey(Link.ENERGY); PlayerPrefs.DeleteKey(Link.COMMON); PlayerPrefs.DeleteKey(Link.RARE); PlayerPrefs.DeleteKey(Link.LEGENDARY); PlayerPrefs.DeleteKey(Link.COMMONGem); PlayerPrefs.DeleteKey(Link.RAREGem); PlayerPrefs.DeleteKey(Link.LEGENDARYGem); PlayerPrefs.DeleteKey(Link.FOR_CONVERTING); PlayerPrefs.DeleteKey(Link.LAT); PlayerPrefs.DeleteKey(Link.LOT); PlayerPrefs.DeleteKey("GMode"); PlayerPrefs.DeleteKey("ItemID"); PlayerPrefs.DeleteKey("PLAY_TUTORIAL"); PlayerPrefs.DeleteKey("Tutorgame"); PlayerPrefs.DeleteKey("HantuNaikGrade"); for(int i=1; i<=5 ;i++) { PlayerPrefs.DeleteKey("hantukorban"+i+"ID"); } PlayerPrefs.DeleteKey("nextlevel"); PlayerPrefs.DeleteKey("SummonMissionStats"); PlayerPrefs.DeleteKey("SummonMissionQD"); PlayerPrefs.DeleteKey("SoloMissionStats"); PlayerPrefs.DeleteKey("CatchMissionStats"); PlayerPrefs.DeleteKey("SoloMissionQD"); PlayerPrefs.DeleteKey("CatchMissionQD"); } public void LogOut() { // PlayerPrefs.DeleteAll(); StartCoroutine(LoginOut()); } IEnumerator checkID() { string url = Link.url + "checkDID"; WWWForm form = new WWWForm(); form.AddField(Link.ID, PlayerPrefs.GetString(Link.ID)); form.AddField("DID", PlayerPrefs.GetString(Link.DEVICE_ID)); WWW www = new WWW(url, form); yield return www; if (www.error == null) { var jsonString = JSON.Parse(www.text); Debug.Log(www.text); PlayerPrefs.SetString(Link.FOR_CONVERTING, jsonString["code"]); if (PlayerPrefs.GetString(Link.FOR_CONVERTING) == "33") { if (vanny != null) { vanny.SetActive(false); ValidationError.SetActive(true); } else { ValidationError.SetActive(true); } } else { Debug.Log("Nothing Happen"); } } } }
// ReSharper disable All using System; namespace iSukces.Code.Tests.EqualityGenerator { partial class EqualityGeneratorTests { partial class ClassWithEnumProperties1 : iSukces.Code.AutoCode.IAutoEquatable<EqualityGeneratorTests.ClassWithEnumProperties1> { public override bool Equals(object other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return other is ClassWithEnumProperties1 otherCasted && Equals(otherCasted); } public bool Equals(ClassWithEnumProperties1 other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return N1 == other.N1 && O1 == other.O1 && N2 == other.N2 && O2 == other.O2; } public override int GetHashCode() { unchecked { return (((int)N1 * 8 + (int)O1 - 5) * 3 + (int)N2) * 8 + (int)O2 - 5; } } public static bool operator !=(ClassWithEnumProperties1 left, ClassWithEnumProperties1 right) { return !Equals(left, right); } public static bool operator ==(ClassWithEnumProperties1 left, ClassWithEnumProperties1 right) { return Equals(left, right); } } } }
using System; namespace BankAccountAPI.Repositories { public class Class1 { } }
using System.Windows; using System.Windows.Media; namespace Crystal.Plot2D.Charts { /// <summary> /// Represents a rectangle with corners bound to viewport coordinates. /// </summary> public sealed class RectangleHighlight : ViewportShape { /// <summary> /// Initializes a new instance of the <see cref="RectangleHighlight"/> class. /// </summary> public RectangleHighlight() { } /// <summary> /// Initializes a new instance of the <see cref="RectangleHighlight"/> class. /// </summary> /// <param name="bounds">The bounds.</param> public RectangleHighlight(Rect bounds) { Bounds = bounds; } private DataRect rect = DataRect.Empty; public DataRect Bounds { get { return rect; } set { if (rect != value) { rect = value; UpdateUIRepresentation(); } } } protected override void UpdateUIRepresentationCore() { var transform = Plotter.Viewport.Transform; Point p1 = rect.XMaxYMax.DataToScreen(transform); Point p2 = rect.XMinYMin.DataToScreen(transform); rectGeometry.Rect = new Rect(p1, p2); } private readonly RectangleGeometry rectGeometry = new(); protected override Geometry DefiningGeometry { get { return rectGeometry; } } } }
/****************************************************************************** * File : pLab_UTMCoordinates.cs * Lisence : BSD 3-Clause License * Copyright : Lapland University of Applied Sciences * Authors : Arto Söderström * BSD 3-Clause License * * Copyright (c) 2019, Lapland University of Applied Sciences * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.Collections; using System.Collections.Generic; using UnityEngine; public class pLab_UTMCoordinates { private double utmX = 0; private double utmY = 0; public double UTMX { get { return utmX; } set { utmX = value; } } public double UTMY { get { return utmY; } set { utmY = value; } } public pLab_UTMCoordinates() { } public pLab_UTMCoordinates(double utmX, double utmY) { this.utmX = utmX; this.utmY = utmY; } public pLab_UTMCoordinates(pLab_LatLon latLon) { if (latLon != null) { pLab_GeoTools.LatLongtoUTM(latLon.Lat, latLon.Lon, out this.utmY, out this.utmX); } } public override string ToString() { return string.Format("UTM X: {0}, UTM Y: {1}", utmX, utmY); } /// <summary> /// Calculate distance between this and other UTM Coordinates /// </summary> /// <param name="otherPoint"></param> /// <returns></returns> public double DistanceToUTMCoordinates(pLab_UTMCoordinates otherPoint) { return DifferenceToUTMCoordinates(otherPoint).magnitude; } public Vector2 DifferenceToUTMCoordinates(double otherPointUTMX, double otherPointUTMY) { return new Vector2((float) (otherPointUTMX - utmX), (float) (otherPointUTMY - utmY)); } /// <summary> /// Calculate difference from this point to other point /// </summary> /// <param name="otherPoint"></param> /// <returns></returns> public Vector2 DifferenceToUTMCoordinates(pLab_UTMCoordinates otherPoint) { return new Vector2((float) (otherPoint.UTMX - utmX), (float) (otherPoint.UTMY - utmY)); } }
using System; namespace TastyApp { class Program { static void Main(string[] args) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Hello World, ain't this tasty!"); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(""); } } }
using Autofac; using AutoService.Core.Contracts; namespace AutoService.Core.Providers { public class ProcessorLocator : IProcessorLocator { private readonly IComponentContext container; public ProcessorLocator(IComponentContext container) { this.container = container; } T IProcessorLocator.GetProcessor<T>() { return container.Resolve<T>(); } } }
using System; using System.Linq; using iSukces.Code.Interfaces; using JetBrains.Annotations; namespace iSukces.Code.AutoCode { public partial class CsExpression { public CsExpression([NotNull] string code, CsOperatorPrecendence precedence = CsOperatorPrecendence.Expression) { if (string.IsNullOrEmpty(code)) throw new ArgumentException(nameof(code)); Code = code ?? throw new ArgumentNullException(nameof(code)); Precedence = precedence; } protected CsExpression(CsOperatorPrecendence precedence) { Precedence = precedence; } public static string AddBrackets(string code, CsOperatorPrecendence codePrecedence, CsOperatorPrecendence outerExpression, ExpressionAppend append) { var add = CsOperatorPrecendenceUtils.AddBrackets(codePrecedence, outerExpression, append); return add ? "(" + code + ")" : code; } public static CsExpression operator +(CsExpression l, CsExpression r) => new Binary(l, r, CsOperatorPrecendence.Additive, "+"); public static CsExpression operator +(int l, CsExpression r) { if (l == 0) return r; return new Binary(l, r, CsOperatorPrecendence.Additive, "+"); } public static CsExpression operator +(CsExpression l, int r) { if (r == 0) return l; return new Binary(l, r, CsOperatorPrecendence.Additive, "+"); } public static CsExpression operator /(CsExpression a, CsExpression b) => new Binary(a, b, CsOperatorPrecendence.Multiplicative, "/"); public static CsExpression operator ^(CsExpression a, CsExpression b) { const CsOperatorPrecendence op = CsOperatorPrecendence.BitwiseExOr; var code1 = a.GetCode(op, ExpressionAppend.Before); var code2 = b.GetCode(op, ExpressionAppend.After); return new CsExpression(code1 + " ^ " + code2, op); } public static explicit operator CsExpression(string code) => new CsExpression(code); public static implicit operator CsExpression(int code) => new CsExpression(code.ToString()); public static implicit operator CsExpression(bool code) => new CsExpression(code ? "true" : "false"); public static implicit operator CsExpression(double code) => new CsExpression(code.ToCsString() + "d"); public static CsExpression operator *(CsExpression a, CsExpression b) => new Binary(a, b, CsOperatorPrecendence.Multiplicative, "*"); public static CsExpression operator *(CsExpression a, int b) { if (b == 1) return a; return new Binary(a, b, CsOperatorPrecendence.Multiplicative, "*"); } public static CsExpression operator *(int a, CsExpression b) { if (a == 1) return b; return new Binary(a, b, CsOperatorPrecendence.Multiplicative, "*"); } public static CsExpression operator -(CsExpression a, CsExpression b) => new Binary(a, b, CsOperatorPrecendence.Additive, "-"); public static CsExpression operator -(CsExpression a, int b) { if (b == 0) return a; return new Binary(a, b, CsOperatorPrecendence.Additive, "-"); } public static CsExpression TypeCast(string type, CsExpression expression) { return new Cast(type, expression); } public CsExpression TypeCast(string type) { return new Cast(type, this); } public CsExpression CallMethod(string methodName, params CsExpression[] args) { var code = GetCode(CsOperatorPrecendence.Expression, ExpressionAppend.Before); code += "." + methodName + "(" + string.Join(", ", args.Select(a => a.Code)) + ")"; return new CsExpression(code); } public CsExpression CallProperty(string propertyName) { var code = GetCode(CsOperatorPrecendence.Expression, ExpressionAppend.Before); return new CsExpression(code + "." + propertyName); } public CsExpression Coalesce([NotNull] CsExpression expr) { if (expr == null) throw new ArgumentNullException(nameof(expr)); const CsOperatorPrecendence op = CsOperatorPrecendenceUtils.DoubleQuestion; var code1 = GetCode(op, ExpressionAppend.Before); var code2 = expr.GetCode(op, ExpressionAppend.After); return new CsExpression(code1 + " ?? " + code2, op); } public CsExpression Conditional(CsExpression trueEx, CsExpression falseEx) { const CsOperatorPrecendence op = CsOperatorPrecendence.ConditionalExpression; var conditionCode = GetCode(op, ExpressionAppend.Before); var trueExpressionCode = trueEx.GetCode(op, ExpressionAppend.After); var falseExpressionCode = falseEx.GetCode(op, ExpressionAppend.After); return new CsExpression($"{conditionCode} ? {trueExpressionCode} : {falseExpressionCode}", op); } public CsExpression Format(params object[] args) { var code = string.Format(Code, args); return new CsExpression(code, Precedence); } public string GetCode(CsOperatorPrecendence outerPrecedence, ExpressionAppend append) => AddBrackets(Code, Precedence, outerPrecedence, append); public CsExpression Is(string isWhat) { // todo I don't know if it's relational but seems to be // (a < b) is bool requires () // a >> b is T not requires () const CsOperatorPrecendence resultPrecedence = CsOperatorPrecendence.Relational; var code = GetCode(resultPrecedence, ExpressionAppend.After); return new CsExpression(code + " is " + isWhat, resultPrecedence); } public CsExpression OptionalNull() { // todo I don't know if it's Expression but seems to be // I've checked Unary and it's wrong const CsOperatorPrecendence resultPrecedence = CsOperatorPrecendence.Expression; var code = GetCode(resultPrecedence, ExpressionAppend.Before); return new CsExpression(code + "?", resultPrecedence); } public override string ToString() => Code; public virtual CsOperatorPrecendence Precedence { get; } public virtual string Code { get; } } }
using System; using System.IO; namespace MalwareScanner.Contracts { public interface IMalwareScanner { IMalwareScanningResult Scan(Func<Stream> getFileFunc, string fileName = null); } }
// <copyright file="TripletEncoding.cs" company="WaterTrans"> // © 2020 WaterTrans and Contributors // </copyright> using System; namespace WaterTrans.GlyphLoader.Internal.WOFF2 { /// <summary> /// The triplet encoding. /// </summary> internal class TripletEncoding { /// <summary> /// The triplet encoding items. /// </summary> internal static readonly TripletEncoding[] Items = new TripletEncoding[] { new TripletEncoding(2, 0, 8, 0, 0, 0, -1), new TripletEncoding(2, 0, 8, 0, 0, 0, 1), new TripletEncoding(2, 0, 8, 0, 256, 0, -1), new TripletEncoding(2, 0, 8, 0, 256, 0, 1), new TripletEncoding(2, 0, 8, 0, 512, 0, -1), new TripletEncoding(2, 0, 8, 0, 512, 0, 1), new TripletEncoding(2, 0, 8, 0, 768, 0, -1), new TripletEncoding(2, 0, 8, 0, 768, 0, 1), new TripletEncoding(2, 0, 8, 0, 1024, 0, -1), new TripletEncoding(2, 0, 8, 0, 1024, 0, 1), new TripletEncoding(2, 8, 0, 0, 0, -1, 0), new TripletEncoding(2, 8, 0, 0, 0, 1, 0), new TripletEncoding(2, 8, 0, 256, 0, -1, 0), new TripletEncoding(2, 8, 0, 256, 0, 1, 0), new TripletEncoding(2, 8, 0, 512, 0, -1, 0), new TripletEncoding(2, 8, 0, 512, 0, 1, 0), new TripletEncoding(2, 8, 0, 768, 0, -1, 0), new TripletEncoding(2, 8, 0, 768, 0, 1, 0), new TripletEncoding(2, 8, 0, 1024, 0, -1, 0), new TripletEncoding(2, 8, 0, 1024, 0, 1, 0), new TripletEncoding(2, 4, 4, 1, 1, -1, -1), new TripletEncoding(2, 4, 4, 1, 1, 1, -1), new TripletEncoding(2, 4, 4, 1, 1, -1, 1), new TripletEncoding(2, 4, 4, 1, 1, 1, 1), new TripletEncoding(2, 4, 4, 1, 17, -1, -1), new TripletEncoding(2, 4, 4, 1, 17, 1, -1), new TripletEncoding(2, 4, 4, 1, 17, -1, 1), new TripletEncoding(2, 4, 4, 1, 17, 1, 1), new TripletEncoding(2, 4, 4, 1, 33, -1, -1), new TripletEncoding(2, 4, 4, 1, 33, 1, -1), new TripletEncoding(2, 4, 4, 1, 33, -1, 1), new TripletEncoding(2, 4, 4, 1, 33, 1, 1), new TripletEncoding(2, 4, 4, 1, 49, -1, -1), new TripletEncoding(2, 4, 4, 1, 49, 1, -1), new TripletEncoding(2, 4, 4, 1, 49, -1, 1), new TripletEncoding(2, 4, 4, 1, 49, 1, 1), new TripletEncoding(2, 4, 4, 17, 1, -1, -1), new TripletEncoding(2, 4, 4, 17, 1, 1, -1), new TripletEncoding(2, 4, 4, 17, 1, -1, 1), new TripletEncoding(2, 4, 4, 17, 1, 1, 1), new TripletEncoding(2, 4, 4, 17, 17, -1, -1), new TripletEncoding(2, 4, 4, 17, 17, 1, -1), new TripletEncoding(2, 4, 4, 17, 17, -1, 1), new TripletEncoding(2, 4, 4, 17, 17, 1, 1), new TripletEncoding(2, 4, 4, 17, 33, -1, -1), new TripletEncoding(2, 4, 4, 17, 33, 1, -1), new TripletEncoding(2, 4, 4, 17, 33, -1, 1), new TripletEncoding(2, 4, 4, 17, 33, 1, 1), new TripletEncoding(2, 4, 4, 17, 49, -1, -1), new TripletEncoding(2, 4, 4, 17, 49, 1, -1), new TripletEncoding(2, 4, 4, 17, 49, -1, 1), new TripletEncoding(2, 4, 4, 17, 49, 1, 1), new TripletEncoding(2, 4, 4, 33, 1, -1, -1), new TripletEncoding(2, 4, 4, 33, 1, 1, -1), new TripletEncoding(2, 4, 4, 33, 1, -1, 1), new TripletEncoding(2, 4, 4, 33, 1, 1, 1), new TripletEncoding(2, 4, 4, 33, 17, -1, -1), new TripletEncoding(2, 4, 4, 33, 17, 1, -1), new TripletEncoding(2, 4, 4, 33, 17, -1, 1), new TripletEncoding(2, 4, 4, 33, 17, 1, 1), new TripletEncoding(2, 4, 4, 33, 33, -1, -1), new TripletEncoding(2, 4, 4, 33, 33, 1, -1), new TripletEncoding(2, 4, 4, 33, 33, -1, 1), new TripletEncoding(2, 4, 4, 33, 33, 1, 1), new TripletEncoding(2, 4, 4, 33, 49, -1, -1), new TripletEncoding(2, 4, 4, 33, 49, 1, -1), new TripletEncoding(2, 4, 4, 33, 49, -1, 1), new TripletEncoding(2, 4, 4, 33, 49, 1, 1), new TripletEncoding(2, 4, 4, 49, 1, -1, -1), new TripletEncoding(2, 4, 4, 49, 1, 1, -1), new TripletEncoding(2, 4, 4, 49, 1, -1, 1), new TripletEncoding(2, 4, 4, 49, 1, 1, 1), new TripletEncoding(2, 4, 4, 49, 17, -1, -1), new TripletEncoding(2, 4, 4, 49, 17, 1, -1), new TripletEncoding(2, 4, 4, 49, 17, -1, 1), new TripletEncoding(2, 4, 4, 49, 17, 1, 1), new TripletEncoding(2, 4, 4, 49, 33, -1, -1), new TripletEncoding(2, 4, 4, 49, 33, 1, -1), new TripletEncoding(2, 4, 4, 49, 33, -1, 1), new TripletEncoding(2, 4, 4, 49, 33, 1, 1), new TripletEncoding(2, 4, 4, 49, 49, -1, -1), new TripletEncoding(2, 4, 4, 49, 49, 1, -1), new TripletEncoding(2, 4, 4, 49, 49, -1, 1), new TripletEncoding(2, 4, 4, 49, 49, 1, 1), new TripletEncoding(3, 8, 8, 1, 1, -1, -1), new TripletEncoding(3, 8, 8, 1, 1, 1, -1), new TripletEncoding(3, 8, 8, 1, 1, -1, 1), new TripletEncoding(3, 8, 8, 1, 1, 1, 1), new TripletEncoding(3, 8, 8, 1, 257, -1, -1), new TripletEncoding(3, 8, 8, 1, 257, 1, -1), new TripletEncoding(3, 8, 8, 1, 257, -1, 1), new TripletEncoding(3, 8, 8, 1, 257, 1, 1), new TripletEncoding(3, 8, 8, 1, 513, -1, -1), new TripletEncoding(3, 8, 8, 1, 513, 1, -1), new TripletEncoding(3, 8, 8, 1, 513, -1, 1), new TripletEncoding(3, 8, 8, 1, 513, 1, 1), new TripletEncoding(3, 8, 8, 257, 1, -1, -1), new TripletEncoding(3, 8, 8, 257, 1, 1, -1), new TripletEncoding(3, 8, 8, 257, 1, -1, 1), new TripletEncoding(3, 8, 8, 257, 1, 1, 1), new TripletEncoding(3, 8, 8, 257, 257, -1, -1), new TripletEncoding(3, 8, 8, 257, 257, 1, -1), new TripletEncoding(3, 8, 8, 257, 257, -1, 1), new TripletEncoding(3, 8, 8, 257, 257, 1, 1), new TripletEncoding(3, 8, 8, 257, 513, -1, -1), new TripletEncoding(3, 8, 8, 257, 513, 1, -1), new TripletEncoding(3, 8, 8, 257, 513, -1, 1), new TripletEncoding(3, 8, 8, 257, 513, 1, 1), new TripletEncoding(3, 8, 8, 513, 1, -1, -1), new TripletEncoding(3, 8, 8, 513, 1, 1, -1), new TripletEncoding(3, 8, 8, 513, 1, -1, 1), new TripletEncoding(3, 8, 8, 513, 1, 1, 1), new TripletEncoding(3, 8, 8, 513, 257, -1, -1), new TripletEncoding(3, 8, 8, 513, 257, 1, -1), new TripletEncoding(3, 8, 8, 513, 257, -1, 1), new TripletEncoding(3, 8, 8, 513, 257, 1, 1), new TripletEncoding(3, 8, 8, 513, 513, -1, -1), new TripletEncoding(3, 8, 8, 513, 513, 1, -1), new TripletEncoding(3, 8, 8, 513, 513, -1, 1), new TripletEncoding(3, 8, 8, 513, 513, 1, 1), new TripletEncoding(4, 12, 12, 0, 0, -1, -1), new TripletEncoding(4, 12, 12, 0, 0, 1, -1), new TripletEncoding(4, 12, 12, 0, 0, -1, 1), new TripletEncoding(4, 12, 12, 0, 0, 1, 1), new TripletEncoding(5, 16, 16, 0, 0, -1, -1), new TripletEncoding(5, 16, 16, 0, 0, 1, -1), new TripletEncoding(5, 16, 16, 0, 0, -1, 1), new TripletEncoding(5, 16, 16, 0, 0, 1, 1), }; /// <summary> /// Initializes a new instance of the <see cref="TripletEncoding"/> class. /// </summary> /// <param name="byteCount">Byte count.</param> /// <param name="xbits">Number of bits used to represent X coordinate value (X bits).</param> /// <param name="ybits">Number of bits used to represent Y coordinate value (Y bits).</param> /// <param name="deltaX">An additional incremental amount to be added to X bits value (delta X).</param> /// <param name="deltaY">An additional incremental amount to be added to Y bits value (delta Y).</param> /// <param name="xsign">The sign of X coordinate value (X sign).</param> /// <param name="ysign">The sign of Y coordinate value (Y sign).</param> internal TripletEncoding(byte byteCount, byte xbits, byte ybits, ushort deltaX, ushort deltaY, sbyte xsign, sbyte ysign) { ByteCount = byteCount; Xbits = xbits; Ybits = ybits; DeltaX = deltaX; DeltaY = deltaY; Xsign = xsign; Ysign = ysign; } /// <summary> /// Byte count. /// </summary> public byte ByteCount { get; } /// <summary> /// Number of bits used to represent X coordinate value (X bits). /// </summary> public byte Xbits { get; } /// <summary> /// Number of bits used to represent Y coordinate value (Y bits). /// </summary> public byte Ybits { get; } /// <summary> /// An additional incremental amount to be added to X bits value (delta X). /// </summary> public ushort DeltaX { get; } /// <summary> /// An additional incremental amount to be added to Y bits value (delta Y). /// </summary> public ushort DeltaY { get; } /// <summary> /// The sign of X coordinate value (X sign). /// </summary> public sbyte Xsign { get; } /// <summary> /// The sign of Y coordinate value (Y sign). /// </summary> public sbyte Ysign { get; } /// <summary> /// Translate X. /// </summary> /// <param name="coordinates">The coordinates byte array.</param> /// <returns>X coordinate.</returns> public int TranslateX(byte[] coordinates) { switch (Xbits) { case 0: return 0; case 4: return ((coordinates[0] >> 4) + DeltaX) * Xsign; case 8: return (coordinates[0] + DeltaX) * Xsign; case 12: return ((coordinates[0] << 4) | (coordinates[1] >> 4) + DeltaX) * Xsign; case 16: return (((coordinates[0] << 8) | coordinates[1]) + DeltaX) * Xsign; default: throw new InvalidOperationException(); } } /// <summary> /// Translate Y. /// </summary> /// <param name="coordinates">The coordinates byte array.</param> /// <returns>Y coordinate.</returns> public int TranslateY(byte[] coordinates) { switch (Ybits) { case 0: return 0; case 4: return ((coordinates[0] & 0xF) + DeltaY) * Ysign; case 8: return Xbits == 0 ? (coordinates[0] + DeltaY) * Ysign : (coordinates[1] + DeltaY) * Ysign; case 12: return ((((coordinates[1] & 0xF) << 8) | coordinates[2]) + DeltaY) * Ysign; case 16: return (((coordinates[2] << 8) | coordinates[3]) + DeltaY) * Ysign; default: throw new InvalidOperationException(); } } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Zesty.Core; using Zesty.Core.Controllers; using Zesty.Core.Entities; namespace Zesty.Web.Controllers { [Produces("application/json")] [ApiController] [Route("api/[controller]")] public class SecuredController : SecureController { /// <summary> /// Secured api. It's secured :) /// </summary> /// <returns></returns> [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status501NotImplemented)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] [HttpGet("Secured")] public IActionResult Secured() { return GetOutput($"Hi {Context.Current.User.Username}", 200, ContentType.TextPlain); } /// <summary> /// Free api. It's public :) /// </summary> /// <returns></returns> [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status501NotImplemented)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] [HttpGet("Free")] public IActionResult Free() { return GetOutput("Hi i'm free", 200, ContentType.TextPlain); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using dropkick.Wmi; using dropkick.StringInterpolation; namespace dropkick.Configuration.Dsl.Authentication { public static class Extension { public static ProtoServer WithAuthentication(this ProtoServer server, string remoteUserName, string remotePassword) { var interpolator = new CaseInsensitiveInterpolator(); remoteUserName = interpolator.ReplaceTokens(HUB.Settings, remoteUserName); remotePassword = interpolator.ReplaceTokens(HUB.Settings, remotePassword); WmiService.WithAuthentication(remoteUserName, remotePassword); return server; } } }
using Framework.Core.Config; namespace Tests.Data.ActionID { public class EcpTestAdmin { public string UserName = AppConfig.OberonTestUserName; public string Password = AppConfig.OberonTestPassword; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Media; using System.IO; namespace MathTutor { public partial class mainWin : Form { public static bool level1 = true; public static bool bAdd = false; public static bool bSub = false; public static bool bMult = false; public static bool bDiv = false; public int ranMax, ranMin, ranMid; public mainWin() { InitializeComponent(); } private void mainWin_Load(object sender, EventArgs e) { } private void num1_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "1"); } private void num2_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "2"); } private void num3_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "3"); } private void num4_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "4"); } private void num5_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "5"); } private void num6_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "6"); } private void num7_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "7"); } private void num8_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "8"); } private void num9_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "9"); } private void num0_Click(object sender, EventArgs e) { answerBox.Text = (answerBox.Text + "0"); } private void numClear_Click(object sender, EventArgs e) { answerBox.Text = (""); } private void answerBt_Click(object sender, EventArgs e) { if (bAdd == true && bSub == false && bMult == false && bDiv == false) { AdditionSolver(); } if (bAdd == false && bSub == true && bMult == false && bDiv == false) { SubtractionSolver(); } if (bAdd == false && bSub == false && bMult == true && bDiv == false) { MultiplicationSolver(); } if (bAdd == false && bSub == false && bMult == false && bDiv == true) { DivisionSolver(); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } #region Addition menu private void level1ToolStripMenuItem_Click(object sender, EventArgs e) { bAdd = true; bSub = false; bMult = false; bDiv = false; assign.Text = "A1"; correctBt.Text = "0"; wrongBt.Text = "0"; label1.Text = "+"; wrongAswBox.Visible = false; Random startNum = new Random(); int firstNum = startNum.Next(0, 5); int secondNum = startNum.Next(0, 5); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } public void level2ToolStripMenuItem_Click(object sender, EventArgs e) { bAdd = true; bSub = false; bMult = false; bDiv = false; assign.Text = "A2"; correctBt.Text = "0"; wrongBt.Text = "0"; label1.Text = "+"; wrongAswBox.Visible = false; Random startNum = new Random(); int firstNum = startNum.Next(5, 10); int secondNum = startNum.Next(5, 10); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } private void level3ToolStripMenuItem_Click(object sender, EventArgs e) { bAdd = true; bSub = false; bMult = false; bDiv = false; assign.Text = "A3"; correctBt.Text = "0"; wrongBt.Text = "0"; label1.Text = "+"; wrongAswBox.Visible = false; Random startNum = new Random(); int firstNum = startNum.Next(10, 20); int secondNum = startNum.Next(10, 20); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } private void level4ToolStripMenuItem_Click(object sender, EventArgs e) { bAdd = true; bSub = false; bMult = false; bDiv = false; assign.Text = "A4"; correctBt.Text = "0"; wrongBt.Text = "0"; label1.Text = "+"; wrongAswBox.Visible = false; Random startNum = new Random(); int firstNum = startNum.Next(10, 50); int secondNum = startNum.Next(10, 50); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } private void level5ToolStripMenuItem_Click(object sender, EventArgs e) { bAdd = true; bSub = false; bMult = false; bDiv = false; assign.Text = "A5"; correctBt.Text = "0"; wrongBt.Text = "0"; label1.Text = "+"; wrongAswBox.Visible = false; Random startNum = new Random(); int firstNum = startNum.Next(100, 500); int secondNum = startNum.Next(100, 500); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } #endregion #region Subtraction Menu private void level1ToolStripMenuItem1_Click(object sender, EventArgs e) { int tempNum; bAdd = false; bSub = true; bMult = false; bDiv = false; label1.Text = "-"; assign.Text = "S1"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 10); int secondNum = startNum.Next(0, 10); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } } private void level2ToolStripMenuItem1_Click(object sender, EventArgs e) { int tempNum; bAdd = false; bSub = true; bMult = false; bDiv = false; label1.Text = "-"; assign.Text = "S2"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 20); int secondNum = startNum.Next(1, 10); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } } private void level3ToolStripMenuItem1_Click(object sender, EventArgs e) { int tempNum; bAdd = false; bSub = true; bMult = false; bDiv = false; label1.Text = "-"; assign.Text = "S3"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 40); int secondNum = startNum.Next(2, 15); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } } private void level4ToolStripMenuItem1_Click(object sender, EventArgs e) { int tempNum; bAdd = false; bSub = true; bMult = false; bDiv = false; label1.Text = "-"; assign.Text = "S4"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 100); int secondNum = startNum.Next(2, 25); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } } #endregion #region Multiplication Menu private void level1ToolStripMenuItem2_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = true; bDiv = false; label1.Text = "*"; assign.Text = "M1"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 5); int secondNum = startNum.Next(0, 5); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } private void level2ToolStripMenuItem2_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = true; bDiv = false; label1.Text = "*"; assign.Text = "M2"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 10); int secondNum = startNum.Next(0, 5); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } private void level3ToolStripMenuItem2_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = true; bDiv = false; label1.Text = "*"; assign.Text = "M3"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 10); int secondNum = startNum.Next(0, 10); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } private void level4ToolStripMenuItem2_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = true; bDiv = false; label1.Text = "*"; assign.Text = "M4"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(0, 15); int secondNum = startNum.Next(0, 10); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } #endregion #region Division Menu private void level1ToolStripMenuItem3_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = false; bDiv = true; label1.Text = " /"; assign.Text = "D1"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(1, 5); int secondNum = startNum.Next(1, 5); int tempDivision = firstNum * secondNum; questOne.Text = (tempDivision + ""); questTwo.Text = (secondNum + ""); } private void level2ToolStripMenuItem3_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = false; bDiv = true; label1.Text = " /"; assign.Text = "D2"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(1, 10); int secondNum = startNum.Next(1, 10); int tempDivision = firstNum * secondNum; questOne.Text = (tempDivision + ""); questTwo.Text = (secondNum + ""); } private void level3ToolStripMenuItem3_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = false; bDiv = true; label1.Text = " /"; assign.Text = "D3"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(1, 15); int secondNum = startNum.Next(1, 5); int tempDivision = firstNum * secondNum; questOne.Text = (tempDivision + ""); questTwo.Text = (secondNum + ""); } private void level4ToolStripMenuItem3_Click(object sender, EventArgs e) { bAdd = false; bSub = false; bMult = false; bDiv = true; label1.Text = " /"; assign.Text = "D4"; correctBt.Text = "0"; wrongBt.Text = "0"; Random startNum = new Random(); int firstNum = startNum.Next(1, 20); int secondNum = startNum.Next(1, 10); int tempDivision = firstNum * secondNum; questOne.Text = (tempDivision + ""); questTwo.Text = (secondNum + ""); } #endregion private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) { checkBox1.Text = "Disable Answers"; wrongAswBox.Visible = true; } if (checkBox1.Checked == false) { checkBox1.Text = "Enable Answers"; wrongAswBox.Visible = false; } } public void AdditionSolver() { int additionAnswer; int a, b, c; int correctNum, wrongNum; int ranMax, ranMin; #region Level Assign if (assign.Text == "A1") { ranMax = 5; ranMin = 0; } else if (assign.Text == "A2") { ranMax = 10; ranMin = 5; } else if (assign.Text == "A3") { ranMax = 20; ranMin = 10; } else if (assign.Text == "A4") { ranMax = 50; ranMin = 10; } else if (assign.Text == "A5") { ranMax = 100; ranMin = 50; } else { ranMax = 500; ranMin = 100; } #endregion if (answerBox.Text != "") { a = Convert.ToUInt16(questOne.Text); b = Convert.ToUInt16(questTwo.Text); c = Convert.ToUInt16(answerBox.Text); correctNum = Convert.ToUInt16(correctBt.Text); wrongNum = Convert.ToUInt16(wrongBt.Text); #region Addition Solver additionAnswer = a + b; if (additionAnswer == c) { Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); answerBox.Text = (""); msgBt.Text = ""; correctNum += 1; correctBt.Text = Convert.ToString(correctNum); SystemSounds.Asterisk.Play(); } else if (additionAnswer != c) { wrongAswBox.Text = (questOne.Text + " + " + questTwo.Text + " = " + additionAnswer); Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); answerBox.Text = (""); wrongNum += 1; wrongBt.Text = Convert.ToString(wrongNum); SystemSounds.Hand.Play(); /*answerBox.Text = (""); msgBt.Text = "Try Again!"; wrongNum += 1; wrongBt.Text = Convert.ToString(wrongNum); SystemSounds.Hand.Play(); */ } #endregion } } public void SubtractionSolver() { int subtractionAnswer; int a, b, c; int correctNum, wrongNum, tempNum; #region Sub Levels if (assign.Text == "S1") { ranMax = 10; ranMid = 0; ranMin = 0; } else if (assign.Text == "S2") { ranMax = 20; ranMid = 10; ranMin = 1; } else if (assign.Text == "S3") { ranMax = 40; ranMid = 15; ranMin = 2; } else if (assign.Text == "S4") { ranMax = 100; ranMid = 25; ranMin = 2; } #endregion if (answerBox.Text != "") { a = Convert.ToUInt16(questOne.Text); b = Convert.ToUInt16(questTwo.Text); c = Convert.ToUInt16(answerBox.Text); correctNum = Convert.ToUInt16(correctBt.Text); wrongNum = Convert.ToUInt16(wrongBt.Text); #region Subtraction Solver subtractionAnswer = a - b; if (assign.Text == "S1") { if (subtractionAnswer == c) { Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } answerBox.Text = (""); msgBt.Text = ""; correctNum += 1; correctBt.Text = Convert.ToString(correctNum); SystemSounds.Asterisk.Play(); } else if (subtractionAnswer != c) { wrongAswBox.Text = (questOne.Text + " - " + questTwo.Text + " = " + subtractionAnswer); Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } answerBox.Text = (""); wrongNum += 1; wrongBt.Text = Convert.ToString(wrongNum); SystemSounds.Hand.Play(); } } else // if it is not the first level for subtraction { if (subtractionAnswer == c) { Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMid); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } answerBox.Text = (""); msgBt.Text = ""; correctNum += 1; correctBt.Text = Convert.ToString(correctNum); SystemSounds.Asterisk.Play(); } else if (subtractionAnswer != c) { wrongAswBox.Text = (questOne.Text + " - " + questTwo.Text + " = " + subtractionAnswer); Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); if (firstNum >= secondNum) { questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } else if (secondNum > firstNum) { tempNum = secondNum; secondNum = firstNum; firstNum = tempNum; questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); } answerBox.Text = (""); wrongNum += 1; wrongBt.Text = Convert.ToString(wrongNum); SystemSounds.Hand.Play(); } } #endregion } } public void MultiplicationSolver() { int multiplicationAnswer; int a, b, c; int correctNum, wrongNum; #region Multi Levels if (assign.Text == "M1") { ranMax = 5; ranMid = 0; ranMin = 0; } if (assign.Text == "M2") { ranMax = 10; ranMid = 10; ranMin = 0; } if (assign.Text == "M3") { ranMax = 15; ranMid = 5; ranMin = 0; } if (assign.Text == "M4") { ranMax = 20; ranMid = 10; ranMin = 0; } #endregion if (answerBox.Text != "") { a = Convert.ToUInt16(questOne.Text); b = Convert.ToUInt16(questTwo.Text); c = Convert.ToUInt16(answerBox.Text); correctNum = Convert.ToUInt16(correctBt.Text); wrongNum = Convert.ToUInt16(wrongBt.Text); #region Multiplication Solver multiplicationAnswer = (a * b); if (multiplicationAnswer == c) { Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); answerBox.Text = (""); msgBt.Text = ""; correctNum += 1; correctBt.Text = Convert.ToString(correctNum); SystemSounds.Asterisk.Play(); } else if (multiplicationAnswer != c) { wrongAswBox.Text = (questOne.Text + " * " + questTwo.Text + " = " + multiplicationAnswer); Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); questOne.Text = (firstNum + ""); questTwo.Text = (secondNum + ""); answerBox.Text = (""); wrongNum += 1; wrongBt.Text = Convert.ToString(wrongNum); SystemSounds.Hand.Play(); } #endregion } } public void DivisionSolver() { int divisionAnswer; int a, b, c; int correctNum, wrongNum; #region Div Levels if (assign.Text == "D1") { ranMax = 5; ranMid = 5; ranMin = 1; } if (assign.Text == "D2") { ranMax = 10; ranMid = 10; ranMin = 1; } if (assign.Text == "D3") { ranMax = 15; ranMid = 5; ranMin = 1; } if (assign.Text == "D4") { ranMax = 20; ranMid = 10; ranMin = 1; } #endregion if (answerBox.Text != "") { a = Convert.ToUInt16(questOne.Text); b = Convert.ToUInt16(questTwo.Text); c = Convert.ToUInt16(answerBox.Text); correctNum = Convert.ToUInt16(correctBt.Text); wrongNum = Convert.ToUInt16(wrongBt.Text); #region Miltiplication Solver divisionAnswer = (a / b); if (divisionAnswer == c) { Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMid); int tempDivision = firstNum * secondNum; questOne.Text = (tempDivision + ""); questTwo.Text = (secondNum + ""); answerBox.Text = (""); msgBt.Text = ""; correctNum += 1; correctBt.Text = Convert.ToString(correctNum); SystemSounds.Asterisk.Play(); } else if (divisionAnswer != c) { wrongAswBox.Text = (questOne.Text + " / " + questTwo.Text + " = " + divisionAnswer); Random startNum = new Random(); int firstNum = startNum.Next(ranMin, ranMax); int secondNum = startNum.Next(ranMin, ranMax); int tempDivision = firstNum * secondNum; questOne.Text = (tempDivision + ""); questTwo.Text = (secondNum + ""); answerBox.Text = (""); wrongNum += 1; wrongBt.Text = Convert.ToString(wrongNum); SystemSounds.Hand.Play(); } #endregion } } } }
namespace ChatServer.HAuthentication.HAuthenticationBackends { // Base class for authentication method that is inherited by each backend. class HAuthenticationBackend { } }
using System; namespace Basic13 { public static class Excercises { public static void PrintNumbers() { for (int i = 1; i < 256; i++) { Console.WriteLine(i); } } public static void PrintOdds() { for (int i = 1; i <= 255; i += 2) { Console.WriteLine(i); } } public static void PrintSum() { int total = 0; for (int i = 1; i < 256; i++) { total += i; Console.WriteLine($"New number: {i} Sum: {total}"); } } public static void LoopArray(int[] numbers) { int count = numbers.Length; for (int idx = 0; idx < count; idx++) { Console.WriteLine(numbers[idx]); } } public static int FindMax(int[] numbers) { int count = numbers.Length; int max = numbers[0]; for (int idx = 0; idx < count; idx++) { if (numbers[idx] > max) { max = numbers[idx]; } } return max; } public static void GetAverage(int[] numbers) { int count = numbers.Length; double average; int total = 0; for (int idx = 0; idx < count; idx++) { total += numbers[idx]; } average = Convert.ToDouble(total) / Convert.ToDouble(count); Console.WriteLine($"Average: {average}"); } public static int[] OddArray() { int size = (255 / 2) + 1; int[] oddArray = new int[size]; int idx = 0; for (int num = 1; num <= 255; num += 2) { oddArray[idx] = num; idx++; } return oddArray; } public static int GreaterThanY(int[] numbers, int y) { int length = numbers.Length; int count = 0; for (int idx = 0; idx < length; idx++) { if (numbers[idx] > y) { count++; } } return count; } public static void SquareArrayValues(int[] numbers) { int count = numbers.Length; for (int idx = 0; idx < count; idx++) { numbers[idx] = numbers[idx] * numbers[idx]; } foreach (var num in numbers) { Console.WriteLine(num); } } public static void EliminateNegatives(int[] numbers) { int count = numbers.Length; for (int idx = 0; idx < count; idx++) { if (numbers[idx] < 0) { numbers[idx] = 0; } } foreach (var num in numbers) { Console.WriteLine(num); } } public static void MinMaxAverage(int[] numbers) { int count = numbers.Length; int min = numbers[0]; int max = numbers[0]; int total = 0; double average; for (int idx = 0; idx < count; idx++) { total += numbers[idx]; if (numbers[idx] < min) { min = numbers[idx]; } if (numbers[idx] > max) { max = numbers[idx]; } } average = Convert.ToDouble(total) / Convert.ToDouble(count); Console.WriteLine($"Min Value: {min} | Max Value: {max} | Average: {average}"); } public static void ShiftValues(int[] numbers) { int count = numbers.Length; for (int idx = 0; idx < count - 1; idx++) { numbers[idx] = numbers[idx + 1]; } numbers[count - 1] = 0; foreach (var num in numbers) { Console.WriteLine(num); } } public static object[] NumToString(int[] numbers) { int size = numbers.Length; object[] box = new object[size]; for (int idx = 0; idx < size; idx++) { if (numbers[idx] >= 0) { box[idx] = numbers[idx]; } else { box[idx] = "Dojo"; } } return box; } } }
using System; using System.Drawing; using System.Collections.Generic; using System.Text; using BoardSizeEnum; using Ex05_GameSettingForm; using Ex05_CheckerGameForm; namespace Ex05_UI { public class UI { private int k_SixOnSixWidth = 350, k_SixOnSixHeight = 420, k_SixOnSixPlayerOneXLocation = 80, k_SixOnSixPlayerTwoXLocation = 30; private int k_EightOnEightWidth = 450, k_EightOnEightHeight = 520, k_EightOnEightPlayerOneXLocation = 110, k_EightOnEightPlayerTwoXLocation = 50; private int k_TenOnTenWidth = 550, k_TenOnTenHeight = 620, k_TenOnTenPlayerOneXLocation = 140, k_TenOnTenPlayerTwoXLocation = 70; private GameSettingsForm m_GameSettingForm; private CheckersGameForm m_CheckerGameForm; private eBoardSize m_BoardSize = eBoardSize.NOT_INITIAL; private void initialCheckersGameForm() { if (m_BoardSize == eBoardSize.SIX_ON_SIX) { m_CheckerGameForm = new CheckersGameForm( (int)m_BoardSize, k_SixOnSixWidth, k_SixOnSixHeight, k_SixOnSixPlayerOneXLocation, k_SixOnSixPlayerTwoXLocation, m_GameSettingForm.PlayerOneName, m_GameSettingForm.PlayerTwoName); } else if (m_BoardSize == eBoardSize.EIGHT_ON_EIGHT) { m_CheckerGameForm = new CheckersGameForm( (int)m_BoardSize, k_EightOnEightWidth, k_EightOnEightHeight, k_EightOnEightPlayerOneXLocation, k_EightOnEightPlayerTwoXLocation, m_GameSettingForm.PlayerOneName, m_GameSettingForm.PlayerTwoName); } else { m_CheckerGameForm = new CheckersGameForm( (int)m_BoardSize, k_TenOnTenWidth, k_TenOnTenHeight, k_TenOnTenPlayerOneXLocation, k_TenOnTenPlayerTwoXLocation, m_GameSettingForm.PlayerOneName, m_GameSettingForm.PlayerTwoName); } } public void Run() { m_GameSettingForm = new GameSettingsForm(); m_GameSettingForm.ShowDialog(); m_BoardSize = m_GameSettingForm.BoardSize; initialCheckersGameForm(); m_CheckerGameForm.ShowDialog(); } } }
//Name: NextRoomInfo.cs //Project: Spectral: The Silicon Domain //Author(s) Conor Hughes - conormpkhughes@yahoo.com //Description: This script displays information relating to the current room. using UnityEngine; using UnityEngine.UI; using System.Collections; public class NextRoomInfo : MonoBehaviour { private RawImage backgroundImage; //the background image of the info panel private RectTransform backgroundTransform; //the transform of the background private float sizeDifference = 1000, //used to calculate how close the panel is to its full size backgroundHeight, //the y scale of the background frameTimer; //amount of frames the panel is visible for private bool showInfo = true, //determines if info is displayed runOnce = false; //displays info once public bool playerBesideDoor = false; //indicates that player is beside door private RawImage[] colorIcons; //array of coloured icons on panel private Text levelText, //level name text roomText; //room name text private Vector3 hiddenSize, //panel invisible size visibleSize; //panel visible size private Color hiddenColor, //panel hidden color visibleColor, //panel visible color disabledColor, //panel disabled color newColor; //temporary color value used in array private Level lvl; //instance of level script // Use this for initialization void Start () { lvl = GameObject.Find("Level").GetComponent<Level>();; backgroundImage = transform.Find("Background").GetComponent<RawImage>(); backgroundTransform = transform.Find("Background").GetComponent<RectTransform>(); backgroundHeight = backgroundTransform.sizeDelta.y; hiddenSize = new Vector3(2000, 0, 0); visibleSize = backgroundTransform.sizeDelta; backgroundTransform.sizeDelta = hiddenSize; roomText = transform.Find("Background").Find("CurrentRoomNameText").GetComponent<Text>(); levelText = transform.Find("Background").Find("CurrentLevelNameText").GetComponent<Text>(); levelText.text = Application.loadedLevelName.ToUpper(); visibleColor = new Color(1,1,1,1); hiddenColor = new Color(1,1,1,0); roomText.color = hiddenColor; levelText.color = hiddenColor; colorIcons = new RawImage[5]; colorIcons[0] = transform.Find("Colors").Find("1").GetComponent<RawImage>(); colorIcons[1] = transform.Find("Colors").Find("2").GetComponent<RawImage>(); colorIcons[2] = transform.Find("Colors").Find("3").GetComponent<RawImage>(); colorIcons[3] = transform.Find("Colors").Find("4").GetComponent<RawImage>(); colorIcons[4] = transform.Find("Colors").Find("5").GetComponent<RawImage>(); disabledColor = new Color(0,0,0,0); for(int i = 0; i < colorIcons.Length; i++){ colorIcons[i].color = new Color(colorIcons[i].color.r, colorIcons[i].color.g, colorIcons[i].color.b, 0); } DisplayNewRoomInfo(GameObject.Find("[0,0]").GetComponent<Room>().roomName, Application.loadedLevelName); } //Refreshes the current room colors void RefreshCurrentRoomColors(){ print(lvl.transform.Find("Rooms").Find("["+lvl.currentX+","+lvl.currentZ+"]")); for(int i = 0; i < colorIcons.Length; i++){ newColor = lvl.transform.Find("Rooms").Find("["+lvl.currentX+","+lvl.currentZ+"]").GetComponent<Room>().roomColors[i]; colorIcons[i].color = new Color(newColor.r, newColor.g, newColor.b, 0); } } // Update is called once per frame void FixedUpdate () { if(showInfo){ sizeDifference = Vector3.Distance(backgroundTransform.sizeDelta, visibleSize); backgroundTransform.sizeDelta = Vector3.Lerp(backgroundTransform.sizeDelta, visibleSize, 0.05f); if(sizeDifference < 10f){ roomText.color = Color.Lerp(roomText.color, visibleColor, 0.05f); levelText.color = Color.Lerp(levelText.color, visibleColor, 0.05f); for(int i = 0; i < colorIcons.Length; i++){ newColor = lvl.transform.Find("Rooms").Find("["+lvl.currentX+","+lvl.currentZ+"]").GetComponent<Room>().roomColors[i]; if(newColor != disabledColor)colorIcons[i].color = Color.Lerp(colorIcons[i].color, new Color(newColor.r, newColor.g, newColor.b, 1), 0.05f); } } if(sizeDifference < 0.1f){ if(playerBesideDoor)frameTimer = 0; else{ frameTimer += Time.deltaTime; if(frameTimer > 3)HideRoomInfo(); } } } else{ roomText.color = Color.Lerp(roomText.color, hiddenColor, 0.2f); levelText.color = Color.Lerp(levelText.color, hiddenColor, 0.2f); sizeDifference = Vector3.Distance(backgroundTransform.sizeDelta, hiddenSize); backgroundTransform.sizeDelta = Vector3.Lerp(backgroundTransform.sizeDelta, hiddenSize, 0.1f); for(int i = 0; i < colorIcons.Length; i++){ newColor = lvl.transform.Find("Rooms").Find("["+lvl.currentX+","+lvl.currentZ+"]").GetComponent<Room>().roomColors[i]; if(newColor != disabledColor) colorIcons[i].color = Color.Lerp(colorIcons[i].color, new Color(newColor.r, newColor.g, newColor.b, 0), 0.4f); } } } //Sets the room info and displays it public void DisplayNewRoomInfo(string roomName, string levelName){ roomText.text = roomName; levelText.text = levelName; showInfo = true; } //Displays room info public void ShowRoomInfo(){ showInfo = true; } //Sets name of room public void SetRoomName(string roomName){ roomText.text = roomName; } //Hides room info public void HideRoomInfo(){ showInfo = false; frameTimer = 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Engine { [Serializable] [DataContract] public class ModelTextures { [DataMember] public Texture NormalMap; [DataMember] public Texture Texture; [DataMember] public string TextureFileName; } [Serializable] [DataContract] public class ModelRenderer : Renderer { public BoundingSphere BoundingSphere; [DataMember] public Vector4 DiffuseColorMultiplier = Vector4.One; [DataMember] public bool IsDefaultEffect = false; [DataMember] public bool IsWithNormalMap = false; public bool WriteZBuffer = true; [DataMember] public Model Model { get; set; } public bool Collides(ModelRenderer modelRenderer) { return modelRenderer.BoundingSphere.Transform(modelRenderer.GameObject.GlobalTransform).Intersects( BoundingSphere.Transform(GameObject.GlobalTransform)); } public override void Start() { foreach (ModelMesh mesh in Model.Meshes) { foreach (ModelMeshPart meshPart in mesh.MeshParts) { if (!(meshPart.Tag is ModelTextures)) { var modelTextures = new ModelTextures(); if (meshPart.Tag is string) { var fileName = meshPart.Tag as string; string[] separableFilename = fileName.Split('_', '\\'); modelTextures.TextureFileName = separableFilename[separableFilename.Count() - 2]; } meshPart.Tag = modelTextures; } var mt = meshPart.Tag as ModelTextures; if (mt.Texture == null) mt.Texture = ((BasicEffect)meshPart.Effect).Texture; if (mt.NormalMap == null && !string.IsNullOrEmpty(mt.TextureFileName) && IsWithNormalMap) mt.NormalMap = GameState.CurrentContentManager.Load<Texture>(string.Format("Bumps/{0}-Bump", mt.TextureFileName)); } } CalculateBoundingSphere(); base.Start(); } protected void CalculateBoundingSphere() { BoundingSphere = new BoundingSphere(); foreach (ModelMesh mesh in Model.Meshes) if (BoundingSphere.Radius == 0) BoundingSphere = mesh.BoundingSphere; else BoundingSphere = BoundingSphere.CreateMerged(BoundingSphere, mesh.BoundingSphere); } public override void Render(Camera camera) { if (!WriteZBuffer) GameState.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead; if (IsDefaultEffect) { foreach (ModelMesh mesh in Model.Meshes) { foreach (Effect effect in mesh.Effects) { var basicEffect = effect as BasicEffect; basicEffect.World = GameObject.GlobalTransform; basicEffect.View = Matrix.Invert(camera.GameObject.GlobalTransform); basicEffect.Projection = camera.Projection; basicEffect.PreferPerPixelLighting = true; basicEffect.EnableDefaultLighting(); } mesh.Draw(); } } else { Effect effect = GameState.DefaultEffect; List<PointLight> pointLights = GameState.PointLights; if (IsWithNormalMap) effect.CurrentTechnique = effect.Techniques["TechniqueWithTextureWithNormMap"]; else effect.CurrentTechnique = effect.Techniques["TechniqueWithTextureWithoutNormMap"]; effect.Parameters["World"].SetValue(GameObject.GlobalTransform); effect.Parameters["ViewProj"].SetValue(Matrix.Invert(camera.GameObject.GlobalTransform) * camera.Projection); List<PointLight> newPixelLights = new List<PointLight>(); foreach (var pointLight in pointLights) { BoundingSphere bs = BoundingSphere.Transform(GameObject.GlobalTransform); if (((bs.Center - pointLight.GameObject.GlobalPosition).Length() < bs.Radius + pointLight.LightRange) && pointLight.Enabled && pointLight.IsImpotrant) newPixelLights.Add(pointLight); } int pixelPointLightsCount = Math.Min(GameState.PixelLightCountForDrawing, newPixelLights.Count); if (pixelPointLightsCount > 0) { effect.Parameters["PixelLightsCount"].SetValue(pixelPointLightsCount); for (int i = 0; i < pixelPointLightsCount; i++) { effect.Parameters["PixelLights"].Elements[i].StructureMembers["LightPosition"].SetValue( newPixelLights[i].GlobalPosition); effect.Parameters["PixelLights"].Elements[i].StructureMembers["DiffuseColor"].SetValue( newPixelLights[i].DiffuseColor); effect.Parameters["PixelLights"].Elements[i].StructureMembers["LightRange"].SetValue( newPixelLights[i].LightRange); effect.Parameters["PixelLights"].Elements[i].StructureMembers["AmbientLightColor"].SetValue( newPixelLights[i].AmbientLightColor); effect.Parameters["PixelLights"].Elements[i].StructureMembers["LightDiffuseColor"].SetValue( DiffuseColorMultiplier); } foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); foreach (ModelMesh mesh in Model.Meshes) { foreach (ModelMeshPart meshPart in mesh.MeshParts) { meshPart.Effect = effect; effect.Parameters["DiffuseTexture"].SetValue(((ModelTextures)meshPart.Tag).Texture); effect.Parameters["NormalMap"].SetValue(((ModelTextures)meshPart.Tag).NormalMap); } mesh.Draw(); } } } } GameState.RecoverDeviceState(); base.Render(camera); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ProgramGame { public class Shop { public int ShopingArmor(int healthHero) { Console.WriteLine(); Console.WriteLine("Введите номер необходимого снаряжения"); Console.WriteLine("1. Легкая броня........+7 к HP"); Console.WriteLine("2. Тяжелая броня......+10 к HP"); switch (Console.ReadLine()) { case "1": Console.WriteLine(); Console.WriteLine("Вы купили Легкую броню (+7 к HP)"); Console.WriteLine($"Ваше здоровье - {healthHero + 7} НР"); return healthHero += 7; case "2": Console.WriteLine(); Console.WriteLine("Вы купили тяжелую броню (+10 к НР)"); Console.WriteLine($"Ваше здоровье - {healthHero + 10} НР"); return healthHero += 10; default: break; } Thread.Sleep(3000); return healthHero; } public int ShopingWeapon(int weaponHeroMaxAttack) { Console.WriteLine(); Console.WriteLine("Перечень оружия:"); Console.WriteLine("1. Меч........+7 к Урону"); Console.WriteLine("2. Топор......+8 к Урону"); switch (Console.ReadLine()) { case "1": Console.WriteLine(); Console.WriteLine("Вы купили Меч (+7 к Урону)"); Console.WriteLine($"Ваш урон - {weaponHeroMaxAttack + 7}"); return weaponHeroMaxAttack += 7; case "2": Console.WriteLine(); Console.WriteLine("Вы купили топор (+8 к Урону)"); Console.WriteLine($"Ваш урон - {weaponHeroMaxAttack + 8}"); return weaponHeroMaxAttack += 8; default: break; } Thread.Sleep(3000); return weaponHeroMaxAttack; } } }
using Library.DataProcessing.Contracts.DataServices; using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.Logging; using Library.Entities.Models; using Library.DataStorage.Contracts; using Library.DataProcessing.Contracts.Validation; using Library.Extensions; using Library.DataProcessing.Implementation.Validation; using Library.DataProcessing.Implementation.Helpers; namespace Library.DataProcessing.Implementation.DataServices { class GenericService<T>: IGenericService<T> where T: IBaseEntity { private readonly ILogger logger; private readonly IRepository<T> repository; public GenericService(ILogger<T> logger, IRepository<T> repository) { this.logger = logger; this.repository = repository; } public IEnumerable<T> Get() { return repository.Get(); } public IEntityResult<T> Post(T item) { using (logger.BeginScope(item)) { logger.LogInformation(nameof(Post)); var validations = new List<IValidationError>(); repository.CaptureErrors( r => r.AddOrUpdate(new[] { item }), validations); return new EntityResult<T>(item, validations); } } public IEntityResult<T> Delete(T item) { using (logger.BeginScope(item)) { logger.LogInformation(nameof(Post)); var validations = new List<IValidationError>(); repository.CaptureErrors( r => r.Remove(item), validations); return new EntityResult<T>(item, validations); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VladislavSafarovTasksEPAM { class Program { static void Main(string[] args) { Start: try { Console.WriteLine("Task 00 INTRO"); Console.WriteLine(" 1. SEQUENCE \n 2. SIMPLE \n 3. SQUARE \n 4. ARRAY \n 0. Exit"); Console.Write("Select the number of task: "); int selectTask = int.Parse(Console.ReadLine()); int temp; switch (selectTask) { case 1: Console.WriteLine("Task 1 SEQUENCE"); Console.Write("Input length of a sequence: "); temp = int.Parse(Console.ReadLine()); if (temp > 0) { Console.Write("N = {0}: ", temp); int[] array = Sequence(temp); for (int i = 0; i < array.Length; i++) { Console.Write(" {0}", array[i]); } Console.WriteLine(); } else { throw new ArgumentException("Exception: Invalid argument"); } goto Start; case 2: Console.WriteLine("Task 2 SIMPLE"); Console.Write("Input a positive number: "); temp = int.Parse(Console.ReadLine()); if (temp <= 0) { throw new ArgumentException("Exception: The number isn\'t positive"); } if (IsSimple(temp)) { Console.WriteLine("{0} is prime(simple) number", temp); } else { Console.WriteLine("{0} isn\'t prime(simple) number", temp); } goto Start; case 3: Console.WriteLine("Task 3 SQUARE"); Console.Write("Input a positive odd number: "); temp = int.Parse(Console.ReadLine()); if (temp <= 1 || temp % 2 == 0) { throw new ArgumentException("Exception: The number isn\'t positive or even number or number equals one"); } else { Console.WriteLine("N = {0}", temp); ShowSquare(temp); } goto Start; case 4: Console.WriteLine("Task 4 ARRAY"); Console.Write("Input a rank of array : "); int rank = int.Parse(Console.ReadLine()); int[][] gearArray = new int[rank][]; for (int i = 0; i < rank; i++) { Console.Write("Input a rank of {0} array : ", i + 1); gearArray[i] = new int[int.Parse(Console.ReadLine())]; } gearArray = RandomFillArray(gearArray); Console.WriteLine("Gear array(Rank is {0}) :", rank); ShowArray(gearArray); Console.WriteLine(" Choose the sorting method \n 1. By elements \n 2. By length \n 3. By elements and length"); Console.Write("Select the number of sorting: "); temp = int.Parse(Console.ReadLine()); switch (temp) { case 1: Console.WriteLine("Gear array with sorted arrays by elements :"); for (int i = 0; i < gearArray.Length; i++) { SortArrayByElements(gearArray[i]); } ShowArray(gearArray); break; case 2: Console.WriteLine("Gear array with sorted arrays by length :"); SortArrayByLength(gearArray); ShowArray(gearArray); break; case 3: Console.WriteLine("Gear array with sorted arrays by length and elements :"); SortArrayByLengthAndElements(gearArray); ShowArray(gearArray); break; default: throw new ArgumentException("Exception: Task with this number doesn\'t exist"); } goto Start; case 0: break; default: throw new ArgumentException("Exception: Task with this number doesn\'t exist"); } } catch (Exception ex) { Console.WriteLine(ex.Message); goto Start; } finally { Console.WriteLine("Press any button to continue."); Console.ReadKey(); Console.Clear(); } } static int[] Sequence(int n) { int[] array = new int[n]; for (int i = 0; i < array.Length; i++) { array[i] = i + 1; } return array; } static bool IsSimple(int n) { if (n == 1) { return true; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } static void ShowSquare(int n) { int y = n / 2 + 1; for (int i = 1; i <= n; i++) { if (i != y) { Console.WriteLine(new string('*', n)); } else { Console.WriteLine(new string('*', y - 1) + " " + new string('*', y - 1)); } } } static int[][] RandomFillArray(int[][] gearArray) { Random rand = new Random(); for (int i = 0; i < gearArray.Length; i++) { for (int j = 0; j < gearArray[i].Length; j++) { gearArray[i][j] = rand.Next(0, 101); } } return gearArray; } static void ShowArray(int[][] gearArray) { Console.Write("{ "); for (int i = 0; i < gearArray.Length; i++) { Console.Write("{"); for (int j = 0; j < gearArray[i].Length; j++) { if (j == gearArray[i].Length - 1 && i == gearArray.Length - 1) // условие проверки является ли элемент самым последним в массиве и в зубчатом массиве { Console.Write("{0}}} ", gearArray[i][j]); } else if (j == gearArray[i].Length - 1) // условие проверки является ли элемент самым последним в массиве { Console.Write("{0}}} , ", gearArray[i][j]); } else { Console.Write("{0},", gearArray[i][j]); } } } Console.WriteLine("}"); } static void SortArrayByElements(int[] array) { int temp; for (int i = 0; i < array.Length; i++) { for (int j = i + 1; j < array.Length; j++) { if (array[i] > array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } } static void SortArrayByLength(int[][] gearArray) { int[] temp; for (int i = 0; i < gearArray.Length; i++) { for (int j = i + 1; j < gearArray.Length; j++) { if (gearArray[i].Length > gearArray[j].Length) { temp = gearArray[i]; gearArray[i] = gearArray[j]; gearArray[j] = temp; } } } } static void SortArrayByLengthAndElements(int[][] gearArray) { SortArrayByLength(gearArray); int lenghtArray = 0; for (int i = 0; i < gearArray.Length; i++) // не нашел свойства возврата суммы кол-ва элементов всех массивов зубчатого массива. Здесь происходит расчет этого значения. { lenghtArray += gearArray[i].Length; } int[] temp = new int[lenghtArray]; for (int i = 0, cntr = 0; i < gearArray.Length; i++) { for (int j = 0; j < gearArray[i].Length; j++, cntr++) { temp[cntr] = gearArray[i][j]; } } SortArrayByElements(temp); for (int i = 0, cntr = 0; i < gearArray.Length; i++) { for (int j = 0; j < gearArray[i].Length; j++, cntr++) { gearArray[i][j] = temp[cntr]; } } } } }
using System.IO; using UnityEngine; public class GameHandler : MonoBehaviour { void Start() { /* Debug.Log("Game Handler has started."); PlayerData playerData = new PlayerData(); playerData.position = new Vector3(4, 0, 4); playerData.highScore = 511; string json = JsonUtility.ToJson(playerData); Debug.Log(json); File.WriteAllText(Application.dataPath + "/saveFile.json", json); */ string json = File.ReadAllText(Application.dataPath + "saveFile.json"); PlayerData loadedPlayerData = JsonUtility.FromJson<PlayerData>(json); Debug.Log("Position: " + loadedPlayerData.position); Debug.Log("Highscore: " + loadedPlayerData.highScore); } private class PlayerData { public Vector3 position; public int highScore; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class HeroStateMachine : MonoBehaviour { //Hero state machine script is attached to each hero to be used in battle state machine private BattleStateMachine BSM; //global battle state machine public BaseHero hero; //this hero public enum TurnState { PROCESSING, ADDTOLIST, WAITING, ACTION, DEAD } public TurnState currentState; public enum CursorStates { MOVING, ACTION, CHOOSINGTARGET, IDLE } public CursorStates cursorState; public enum ActionStates { PREACTION, ACTION, MAGIC, ITEM, IDLE } public ActionStates actionState; string chosenAction; public int cursorOnAction; Transform tileCursor; Transform cursor; float cursorVisibleScale = .82f; float panelItemSpacer = 19.5f; float panelItemScrollSpacer = 19.7f; int tempScrollDiff; Text detailsText; GameObject heroDetailsPanel; GameObject enemyDetailsPanel; GameObject magicSelected; GameObject itemSelected; bool dpadPressed; bool confirmPressed; bool cancelPressed; public bool waitForDamageToFinish; //for ProgressBar public float cur_cooldown = 0f; private float max_cooldown = 5f; private Image ProgressBar; public GameObject ActionTarget; //target to be actioned on private bool actionStarted = false; [HideInInspector] public Vector2 startPosition; //starting position before running to target private float animSpeed = 10f; //for moving to target //dead private bool alive = true; //heroPanel private HeroPanelStats stats; public GameObject HeroPanel; private Transform HeroPanelSpacer; //for the spacer on the Hero Panel (for Vertical Layout Group) public List<BaseEffect> activeStatusEffects = new List<BaseEffect>(); public int effectDamage; public int magicDamage; public int itemDamage; List<BaseAddedEffect> checkAddedEffects = new List<BaseAddedEffect>(); public List<BaseDamage> finalDamages = new List<BaseDamage>(); private PlayerMove playerMove; private bool calculatedTilesToMove; public int heroTurn; protected List<GameObject> targetsInRange = new List<GameObject>(); Pattern pattern = new Pattern(); public List<GameObject> targets = new List<GameObject>(); List<GameObject> targetsAccountedFor = new List<GameObject>(); public bool choosingTarget; List<Tile> tilesInRange = new List<Tile>(); Animator heroAnim; void Start() { HeroPanelSpacer = GameObject.Find("BattleCanvas/BattleUI").transform.Find("HeroPanel").transform.Find("HeroPanelSpacer"); //find spacer and make connection CreateHeroPanel(); //create panel and fill in info if (hero.curHP == 0) //if hero starts battle at 0 HP { ProgressBar.transform.localScale = new Vector2(0, ProgressBar.transform.localScale.y); //reduces ATB gauge to 0 cur_cooldown = 0; //Sets ATB gauge to 0 currentState = HeroStateMachine.TurnState.DEAD; //sets hero in dead state } else //if hero is alive { cur_cooldown = Random.Range(0, 2.5f); //Sets random point for ATB gauge to start //currentState = TurnState.PROCESSING; //begins hero processing phase currentState = TurnState.WAITING; } heroTurn = 1; BSM = GameObject.Find("BattleManager").GetComponent<BattleStateMachine>(); //make connection to the global battle state manager startPosition = transform.position; //sets start position to hero's position for animation purposes playerMove = GetComponent<PlayerMove>(); tileCursor = GameObject.Find("GridMap/TileCursor").transform; cursor = GameObject.Find("BattleCanvas/Cursor").transform; detailsText = GameObject.Find("BattleCanvas/BattleUI/BattleDetailsPanel/BattleDetailsText").GetComponent<Text>(); heroDetailsPanel = GameObject.Find("BattleCanvas/HeroDetailsPanel"); enemyDetailsPanel = GameObject.Find("BattleCanvas/EnemyDetailsPanel"); actionState = ActionStates.IDLE; HideTileCursor(); } void Update() { //Debug.Log("HeroStateMachine - currentState: " + currentState); switch(currentState) { case (TurnState.PROCESSING): if (!waitForDamageToFinish) { if (BSM.activeATB) { UpgradeProgressBar(); //fills hero ATB gauge } else { if (BSM.pendingTurn == false) { UpgradeProgressBar(); //fills hero ATB gauge } } } break; case (TurnState.ADDTOLIST): if (!calculatedTilesToMove) { playerMove.tilesToMove = playerMove.move; calculatedTilesToMove = true; } playerMove.BeginTurn(); BSM.HeroesToManage.Add(this.gameObject); //adds hero to heros who can make selection playerMove.GetCurrentTile(); tileCursor.position = playerMove.currentTile.transform.position; ShowTileCursor(); HideBattleUI(); cursorState = CursorStates.MOVING; currentState = TurnState.WAITING; break; case (TurnState.WAITING): //idle break; case (TurnState.ACTION): //Debug.Log("in hero action"); TimeForAction(); //processes hero action break; case (TurnState.DEAD): //run after every time enemy takes damage that brings them to or below 0 hp if (!alive) //if alive value is set to false, exits the turn state. this is set to false in below code { return; } else { this.gameObject.tag = "DeadHero"; //change tag of hero to DeadHero BSM.HeroesInBattle.Remove(this.gameObject); //not hero attackable by enemy BSM.HeroesToManage.Remove(this.gameObject); //not able to manage hero with player //reset GUI BSM.HidePanel(BSM.actionPanel); BSM.HidePanel(BSM.enemySelectPanel); //remove hero's handleturn from performlist (if there was one) if (BSM.HeroesInBattle.Count > 0) { for (int i = 0; i < BSM.PerformList.Count; i++) //go through all actions in perform list { if (i != 0) //can remove later if heros can kill themselves. otherwise only checks for items in the perform list after 0 (as 0 would be the enemy's action) { if (BSM.PerformList[i].AttackersGameObject == this.gameObject) //if the attacker in the loop is this hero { BSM.PerformList.Remove(BSM.PerformList[i]); //removes this action from the perform list } if (BSM.PerformList[i].AttackersTarget == this.gameObject) //if target in loop in the perform list is the dead hero { BSM.PerformList[i].AttackersTarget = BSM.HeroesInBattle[Random.Range(0, BSM.HeroesInBattle.Count)];//changes the target from the dead hero to a random hero so dead hero cannot be attacked } } } } //gameObject.GetComponent<SpriteRenderer>().material.color = new Color32(105, 105, 105, 255); //change color/ play animation gameObject.GetComponent<Animator>().SetBool("onDeath", true); Debug.Log(hero.name + " - DEAD"); BSM.battleState = battleStates.CHECKALIVE; alive = false; } break; } if (BSM.HeroesToManage.Count > 0 && this.gameObject == BSM.HeroesToManage[0]) { switch (cursorState) { case (CursorStates.MOVING): if (Input.GetAxisRaw("DpadHorizontal") == -1 && !dpadPressed) //left { dpadPressed = true; if (IfTileExists(new Vector3(tileCursor.position.x - 1f, tileCursor.position.y, 0))) { tileCursor.position = new Vector3(tileCursor.position.x - 1f, tileCursor.position.y, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (Input.GetAxisRaw("DpadHorizontal") == 1 && !dpadPressed) //right { dpadPressed = true; if (IfTileExists(new Vector3(tileCursor.position.x + 1f, tileCursor.position.y, 0))) { tileCursor.position = new Vector3(tileCursor.position.x + 1f, tileCursor.position.y, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (Input.GetAxisRaw("DpadVertical") == 1 && !dpadPressed) //up { dpadPressed = true; if (IfTileExists(new Vector3(tileCursor.position.x, tileCursor.position.y + 1f, 0))) { tileCursor.position = new Vector3(tileCursor.position.x, tileCursor.position.y + 1f, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (Input.GetAxisRaw("DpadVertical") == -1 && !dpadPressed) //down { dpadPressed = true; if (IfTileExists(new Vector3(tileCursor.position.x, tileCursor.position.y - 1f, 0))) { tileCursor.position = new Vector3(tileCursor.position.x, tileCursor.position.y - 1f, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (GetUnitOnTile() != null) { if (GetUnitOnTile().tag == "Hero") { heroDetailsPanel.transform.Find("NameText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.name; heroDetailsPanel.transform.Find("LevelText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.currentLevel.ToString(); heroDetailsPanel.transform.Find("HPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.curHP.ToString() + "/" + GetUnitOnTile().GetComponent<HeroStateMachine>().hero.finalMaxHP.ToString(); heroDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetProgressBarValuesHP(GetUnitOnTile().GetComponent<HeroStateMachine>().hero), 0, 1), heroDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale.y); heroDetailsPanel.transform.Find("MPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.curMP.ToString() + "/" + GetUnitOnTile().GetComponent<HeroStateMachine>().hero.finalMaxMP.ToString(); heroDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetProgressBarValuesMP(GetUnitOnTile().GetComponent<HeroStateMachine>().hero), 0, 1), heroDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale.y); BSM.HidePanel(enemyDetailsPanel); BSM.ShowPanel(heroDetailsPanel); } else if (GetUnitOnTile().tag == "Enemy") { enemyDetailsPanel.transform.Find("NameText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.name; enemyDetailsPanel.transform.Find("LevelText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.level.ToString(); enemyDetailsPanel.transform.Find("HPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.curHP.ToString() + "/" + GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.baseHP.ToString(); enemyDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetEnemyProgressBarValuesHP(GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy), 0, 1), enemyDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale.y); enemyDetailsPanel.transform.Find("MPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.curMP.ToString() + "/" + GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.baseMP.ToString(); enemyDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetEnemyProgressBarValuesMP(GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy), 0, 1), enemyDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale.y); DrawThreatBar(GetUnitOnTile().GetComponent<EnemyBehavior>()); BSM.HidePanel(heroDetailsPanel); BSM.ShowPanel(enemyDetailsPanel); } } else { BSM.HidePanel(heroDetailsPanel); BSM.HidePanel(enemyDetailsPanel); } if (Input.GetButtonDown("Cancel") && !cancelPressed) { cancelPressed = true; /*if (tileCursor.position.x == playerMove.currentTile.transform.position.x && tileCursor.position.y == playerMove.currentTile.transform.position.y) { HideTileCursor(); BattleCameraManager.instance.camState = camStates.CHOOSEACTION; ShowBattleUI(); cursorOnAction = 0; ShowCursor(); cursorState = CursorStates.ACTION; actionState = ActionStates.PREACTION; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); BSM.HidePanel(heroDetailsPanel); BSM.HidePanel(enemyDetailsPanel); } else {*/ AudioManager.instance.PlaySE(AudioManager.instance.backSE); playerMove.GetCurrentTile(); tileCursor.position = new Vector3(playerMove.currentTile.transform.position.x, playerMove.currentTile.transform.position.y, 0); //} } if (Input.GetButtonDown("Confirm") && !confirmPressed) { confirmPressed = true; playerMove.GetCurrentTile(); if (tileCursor.position.x == playerMove.currentTile.transform.position.x && tileCursor.position.y == playerMove.currentTile.transform.position.y) { HideTileCursor(); BattleCameraManager.instance.camState = camStates.CHOOSEACTION; ShowBattleUI(); cursorOnAction = 0; ShowCursor(); cursorState = CursorStates.ACTION; actionState = ActionStates.PREACTION; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); BSM.HidePanel(heroDetailsPanel); BSM.HidePanel(enemyDetailsPanel); } else { if (GetTileOnCursor().selectable && GetUnitOnTile() == null) { playerMove.currentTile.SelectMoveTile(playerMove); } else { AudioManager.instance.PlaySE(AudioManager.instance.cantActionSE); } } } //show unit details window based on cursor position here break; case (CursorStates.ACTION): if (actionState == ActionStates.PREACTION) { if (Input.GetAxisRaw("DpadVertical") == -1 && !dpadPressed && cursorOnAction == 0) //down { dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); cursorOnAction = 1; } if (Input.GetAxisRaw("DpadVertical") == 1 && !dpadPressed && cursorOnAction == 1) //up { dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); cursorOnAction = 0; } if (Input.GetButtonDown("Cancel") && !cancelPressed) { cancelPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.backSE); playerMove.GetCurrentTile(); tileCursor.position = playerMove.currentTile.transform.position; HideCursor(); ShowTileCursor(); HideBattleUI(); cursorState = CursorStates.MOVING; BattleCameraManager.instance.camState = camStates.HEROTURN; } if (cursorOnAction == 0) { cursor.transform.localPosition = new Vector3(-348f, -145f, 0f); detailsText.text = "Perform an attack, cast magic, or use an item"; } else if (cursorOnAction == 1) { cursor.transform.localPosition = new Vector3(-348f, -199f, 0f); detailsText.text = "Take 50% damage until next turn"; } if (Input.GetButtonDown("Confirm") && !confirmPressed) { confirmPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); if (cursorOnAction == 0) { BSM.ActionInput(); actionState = ActionStates.ACTION; } else if (cursorOnAction == 1) { BSM.DefendInput(); detailsText.text = ""; cursorState = CursorStates.IDLE; actionState = ActionStates.IDLE; HideCursor(); } } } if (actionState == ActionStates.ACTION) { if (Input.GetAxisRaw("DpadVertical") == -1 && !dpadPressed && cursorOnAction >= 0 && cursorOnAction <= 1) //down { dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); cursorOnAction = cursorOnAction + 1; } if (Input.GetAxisRaw("DpadVertical") == 1 && !dpadPressed && cursorOnAction <= 2 && cursorOnAction >= 1) //up { dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); cursorOnAction = cursorOnAction - 1; } if (Input.GetButtonDown("Cancel") && !cancelPressed) { cancelPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.backSE); cursorOnAction = 0; BSM.HidePanel(GameObject.Find("BattleCanvas/BattleUI/ActionPanel")); BSM.ShowPanel(GameObject.Find("BattleCanvas/BattleUI/MoveActionPanel")); actionState = ActionStates.PREACTION; } if (Input.GetButtonDown("Confirm") && !confirmPressed) { confirmPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); if (cursorOnAction == 0) //attack { BSM.AttackInput(); HideCursor(); ShowTileCursor(); HideBattleUI(); chosenAction = "Attack"; cursorState = CursorStates.CHOOSINGTARGET; } else if (cursorOnAction == 1) //magic { BSM.MagicInput(); cursorOnAction = 0; chosenAction = "Magic"; actionState = ActionStates.MAGIC; } else if (cursorOnAction == 2) //item { BSM.ItemInput(); cursorOnAction = 0; chosenAction = "Item"; actionState = ActionStates.ITEM; } } if (cursorOnAction == 0) { cursor.localPosition = new Vector3(-348f, -136f, 0f); detailsText.text = "Perform a physical attack"; } else if (cursorOnAction == 1) { cursor.localPosition = new Vector3(-348f, -172f, 0f); detailsText.text = "Perform a magic attack"; } else if (cursorOnAction == 2) { cursor.localPosition = new Vector3(-348f, -208f, 0f); detailsText.text = "Use an item from your inventory"; } } if (actionState == ActionStates.MAGIC) { int magicCount = GameObject.Find("BattleCanvas/BattleUI/MagicPanel/MagicScroller/MagicSpacer").transform.childCount; int scrollDiff = magicCount - 5; if (magicCount <= 5) { tempScrollDiff = 0; } RectTransform spacerScroll = GameObject.Find("BattleCanvas/BattleUI/MagicPanel/MagicScroller/MagicSpacer").GetComponent<RectTransform>(); //Debug.Log(cursorOnItem); if (!dpadPressed && cursorOnAction == 0 && tempScrollDiff == 0) { if (magicCount > 1) { if (Input.GetAxisRaw("DpadVertical") == -1) //down { cursorOnAction = cursorOnAction + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } } else if (!dpadPressed && cursorOnAction == 0 && tempScrollDiff > 0) { if (Input.GetAxisRaw("DpadVertical") == -1) //down { cursorOnAction = cursorOnAction + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == 1) //up { spacerScroll.anchoredPosition = new Vector3(0.0f, (panelItemScrollSpacer * (tempScrollDiff - 1)), 0.0f); tempScrollDiff = tempScrollDiff - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction > 0 && cursorOnAction < 4) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = cursorOnAction - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == -1) //down { cursorOnAction = cursorOnAction + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff == 0 && scrollDiff > 0) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = cursorOnAction - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == -1) //down { spacerScroll.anchoredPosition = new Vector3(0.0f, panelItemScrollSpacer, 0.0f); tempScrollDiff = tempScrollDiff + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff == 0 && scrollDiff == 0) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = cursorOnAction - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff > 0 && (cursorOnAction + tempScrollDiff) < (magicCount - 1)) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = 3; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == -1) //down { spacerScroll.anchoredPosition = new Vector3(0.0f, (panelItemScrollSpacer * (tempScrollDiff + 1)), 0.0f); //and use tempScrollDiff - 1 to go up tempScrollDiff = tempScrollDiff + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff > 0 && (cursorOnAction + tempScrollDiff) == (magicCount - 1)) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = 3; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } if (magicCount != 0) { if (cursorOnAction == magicCount) { cursorOnAction = magicCount - 1; } if (cursorOnAction == 0 && tempScrollDiff == 0) { cursor.localPosition = new Vector3(-377f, -132.5f, 0f); magicSelected = GameObject.Find("BattleCanvas/BattleUI/MagicPanel/MagicScroller/MagicSpacer").transform.GetChild(0).gameObject; } else if (cursorOnAction == 0 && tempScrollDiff > 0) { cursor.localPosition = new Vector3(-377f, -132.5f, 0f); magicSelected = GameObject.Find("BattleCanvas/BattleUI/MagicPanel/MagicScroller/MagicSpacer").transform.GetChild(tempScrollDiff).gameObject; } else if (cursorOnAction > 0 && tempScrollDiff > 0) { cursor.localPosition = new Vector3(-377f, (-132.5f - (panelItemSpacer * cursorOnAction)), 0f); magicSelected = GameObject.Find("BattleCanvas/BattleUI/MagicPanel/MagicScroller/MagicSpacer").transform.GetChild(cursorOnAction + tempScrollDiff).gameObject; } else { cursor.localPosition = new Vector3(-377f, (-132.5f - (panelItemSpacer * cursorOnAction)), 0f); magicSelected = GameObject.Find("BattleCanvas/BattleUI/MagicPanel/MagicScroller/MagicSpacer").transform.GetChild(cursorOnAction).gameObject; } detailsText.text = AttackDB.instance.GetAttack(int.Parse(magicSelected.name.Replace("MagicButton - ID ", ""))).description; } if (Input.GetButtonDown("Cancel") && !cancelPressed) { cancelPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.backSE); cursorOnAction = 1; BSM.HidePanel(GameObject.Find("BattleCanvas/BattleUI/MagicPanel")); BSM.ShowPanel(GameObject.Find("BattleCanvas/BattleUI/ActionPanel")); actionState = ActionStates.ACTION; } if (Input.GetButtonDown("Confirm") && !confirmPressed) { confirmPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); Debug.Log("cast: " + magicSelected.transform.Find("ButtonCanvas/AttackName").GetComponent<Text>().text); magicSelected.GetComponent<MagicAttackButton>().CastMagicAttack(); playerMove.GetCurrentTile(); tileCursor.position = new Vector3(playerMove.currentTile.transform.position.x, playerMove.currentTile.transform.position.y, 0f); HideCursor(); ShowTileCursor(); HideBattleUI(); cursorState = CursorStates.CHOOSINGTARGET; } } if (actionState == ActionStates.ITEM) { int itemCount = GameObject.Find("BattleCanvas/BattleUI/ItemPanel/ItemScroller/ItemSpacer").transform.childCount; int scrollDiff = itemCount - 5; if (itemCount <= 5) { tempScrollDiff = 0; } RectTransform spacerScroll = GameObject.Find("BattleCanvas/BattleUI/ItemPanel/ItemScroller/ItemSpacer").GetComponent<RectTransform>(); //Debug.Log(cursorOnItem); if (!dpadPressed && cursorOnAction == 0 && tempScrollDiff == 0) { if (itemCount > 1) { if (Input.GetAxisRaw("DpadVertical") == -1) //down { cursorOnAction = cursorOnAction + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } } else if (!dpadPressed && cursorOnAction == 0 && tempScrollDiff > 0) { if (Input.GetAxisRaw("DpadVertical") == -1) //down { cursorOnAction = cursorOnAction + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == 1) //up { spacerScroll.anchoredPosition = new Vector3(0.0f, (panelItemScrollSpacer * (tempScrollDiff - 1)), 0.0f); tempScrollDiff = tempScrollDiff - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction > 0 && cursorOnAction < 4) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = cursorOnAction - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == -1) //down { cursorOnAction = cursorOnAction + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff == 0 && scrollDiff > 0) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = cursorOnAction - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == -1) //down { spacerScroll.anchoredPosition = new Vector3(0.0f, panelItemScrollSpacer, 0.0f); tempScrollDiff = tempScrollDiff + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff == 0 && scrollDiff == 0) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = cursorOnAction - 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff > 0 && (cursorOnAction + tempScrollDiff) < (itemCount - 1)) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = 3; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } if (Input.GetAxisRaw("DpadVertical") == -1) //down { spacerScroll.anchoredPosition = new Vector3(0.0f, (panelItemScrollSpacer * (tempScrollDiff + 1)), 0.0f); //and use tempScrollDiff - 1 to go up tempScrollDiff = tempScrollDiff + 1; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } else if (!dpadPressed && cursorOnAction == 4 && tempScrollDiff > 0 && (cursorOnAction + tempScrollDiff) == (itemCount - 1)) { if (Input.GetAxisRaw("DpadVertical") == 1) //up { cursorOnAction = 3; dpadPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); } } if (itemCount != 0) { if (cursorOnAction == itemCount) { cursorOnAction = itemCount - 1; } if (cursorOnAction == 0 && tempScrollDiff == 0) { cursor.localPosition = new Vector3(-377f, -132.5f, 0f); itemSelected = GameObject.Find("BattleCanvas/BattleUI/ItemPanel/ItemScroller/ItemSpacer").transform.GetChild(0).gameObject; } else if (cursorOnAction == 0 && tempScrollDiff > 0) { cursor.localPosition = new Vector3(-377f, -132.5f, 0f); itemSelected = GameObject.Find("BattleCanvas/BattleUI/ItemPanel/ItemScroller/ItemSpacer").transform.GetChild(tempScrollDiff).gameObject; } else if (cursorOnAction > 0 && tempScrollDiff > 0) { cursor.localPosition = new Vector3(-377f, (-132.5f - (panelItemSpacer * cursorOnAction)), 0f); itemSelected = GameObject.Find("BattleCanvas/BattleUI/ItemPanel/ItemScroller/ItemSpacer").transform.GetChild(cursorOnAction + tempScrollDiff).gameObject; } else { cursor.localPosition = new Vector3(-377f, (-132.5f - (panelItemSpacer * cursorOnAction)), 0f); itemSelected = GameObject.Find("BattleCanvas/BattleUI/ItemPanel/ItemScroller/ItemSpacer").transform.GetChild(cursorOnAction).gameObject; } detailsText.text = ItemDB.instance.GetItem(int.Parse(itemSelected.name.Replace("ItemButton - ID ", ""))).item.description; } if (Input.GetButtonDown("Cancel") && !cancelPressed) { cancelPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.backSE); cursorOnAction = 2; BSM.HidePanel(GameObject.Find("BattleCanvas/BattleUI/ItemPanel")); BSM.ShowPanel(GameObject.Find("BattleCanvas/BattleUI/ActionPanel")); actionState = ActionStates.ACTION; } if (Input.GetButtonDown("Confirm") && !confirmPressed) { confirmPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); Debug.Log("use: " + itemSelected.transform.Find("ButtonCanvas/ItemName").GetComponent<Text>().text); itemSelected.GetComponent<ItemBattleMenuButton>().UseItem(); playerMove.GetCurrentTile(); tileCursor.position = new Vector3(playerMove.currentTile.transform.position.x, playerMove.currentTile.transform.position.y, 0f); HideCursor(); ShowTileCursor(); HideBattleUI(); cursorState = CursorStates.CHOOSINGTARGET; } } break; case (CursorStates.CHOOSINGTARGET): RaycastHit2D[] resetHits = Physics2D.RaycastAll(tileCursor.position, Vector2.zero); Tile tileToAttack = null; if (Input.GetAxisRaw("DpadHorizontal") == -1 && !dpadPressed) //left { dpadPressed = true; foreach (RaycastHit2D hit in resetHits) { if (hit.collider != null && hit.collider.gameObject.tag == "Tile") { hit.collider.gameObject.GetComponent<Tile>().ResetTilesInRange(); } } if (IfTileExists(new Vector3(tileCursor.position.x - 1f, tileCursor.position.y, 0))) { tileCursor.position = new Vector3(tileCursor.position.x - 1f, tileCursor.position.y, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (Input.GetAxisRaw("DpadHorizontal") == 1 && !dpadPressed) //right { dpadPressed = true; foreach (RaycastHit2D hit in resetHits) { if (hit.collider != null && hit.collider.gameObject.tag == "Tile") { hit.collider.gameObject.GetComponent<Tile>().ResetTilesInRange(); } } if (IfTileExists(new Vector3(tileCursor.position.x + 1f, tileCursor.position.y, 0))) { tileCursor.position = new Vector3(tileCursor.position.x + 1f, tileCursor.position.y, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (Input.GetAxisRaw("DpadVertical") == 1 && !dpadPressed) //up { dpadPressed = true; foreach (RaycastHit2D hit in resetHits) { if (hit.collider != null && hit.collider.gameObject.tag == "Tile") { hit.collider.gameObject.GetComponent<Tile>().ResetTilesInRange(); } } if (IfTileExists(new Vector3(tileCursor.position.x, tileCursor.position.y + 1f, 0))) { tileCursor.position = new Vector3(tileCursor.position.x, tileCursor.position.y + 1f, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (Input.GetAxisRaw("DpadVertical") == -1 && !dpadPressed) //down { dpadPressed = true; foreach (RaycastHit2D hit in resetHits) { if (hit.collider != null && hit.collider.gameObject.tag == "Tile") { hit.collider.gameObject.GetComponent<Tile>().ResetTilesInRange(); } } if (IfTileExists(new Vector3(tileCursor.position.x, tileCursor.position.y - 1f, 0))) { tileCursor.position = new Vector3(tileCursor.position.x, tileCursor.position.y - 1f, 0); AudioManager.instance.PlaySE(AudioManager.instance.moveTileCursorSE); } } if (GetUnitOnTile() != null) { if (GetUnitOnTile().tag == "Hero") { heroDetailsPanel.transform.Find("NameText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.name; heroDetailsPanel.transform.Find("LevelText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.currentLevel.ToString(); heroDetailsPanel.transform.Find("HPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.curHP.ToString() + "/" + GetUnitOnTile().GetComponent<HeroStateMachine>().hero.finalMaxHP.ToString(); heroDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetProgressBarValuesHP(GetUnitOnTile().GetComponent<HeroStateMachine>().hero), 0, 1), heroDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale.y); heroDetailsPanel.transform.Find("MPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<HeroStateMachine>().hero.curMP.ToString() + "/" + GetUnitOnTile().GetComponent<HeroStateMachine>().hero.finalMaxMP.ToString(); heroDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetProgressBarValuesMP(GetUnitOnTile().GetComponent<HeroStateMachine>().hero), 0, 1), heroDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale.y); BSM.HidePanel(enemyDetailsPanel); BSM.ShowPanel(heroDetailsPanel); } else if (GetUnitOnTile().tag == "Enemy") { enemyDetailsPanel.transform.Find("NameText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.name; enemyDetailsPanel.transform.Find("LevelText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.level.ToString(); enemyDetailsPanel.transform.Find("HPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.curHP.ToString() + "/" + GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.baseHP.ToString(); enemyDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetEnemyProgressBarValuesHP(GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy), 0, 1), enemyDetailsPanel.transform.Find("HPProgressBarBG/HPProgressBar").transform.localScale.y); enemyDetailsPanel.transform.Find("MPText").GetComponent<Text>().text = GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.curMP.ToString() + "/" + GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy.baseMP.ToString(); enemyDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale = new Vector2(Mathf.Clamp(GetEnemyProgressBarValuesMP(GetUnitOnTile().GetComponent<EnemyStateMachine>().enemy), 0, 1), enemyDetailsPanel.transform.Find("MPProgressBarBG/MPProgressBar").transform.localScale.y); DrawThreatBar(GetUnitOnTile().GetComponent<EnemyBehavior>()); BSM.HidePanel(heroDetailsPanel); BSM.ShowPanel(enemyDetailsPanel); } } else { BSM.HidePanel(heroDetailsPanel); BSM.HidePanel(enemyDetailsPanel); } if (Input.GetButtonDown("Cancel") && !cancelPressed) { cancelPressed = true; AudioManager.instance.PlaySE(AudioManager.instance.backSE); if (chosenAction == "Attack") { cursorOnAction = 0; BSM.ShowPanel(GameObject.Find("BattleCanvas/BattleUI/ActionPanel")); playerMove.GetCurrentTile(); tileCursor.position = new Vector3(playerMove.currentTile.transform.position.x, playerMove.currentTile.transform.position.y, 0); HideTileCursor(); ShowCursor(); ShowBattleUI(); cursorState = CursorStates.ACTION; actionState = ActionStates.ACTION; } else if (chosenAction == "Magic") { BSM.ShowPanel(GameObject.Find("BattleCanvas/BattleUI/MagicPanel")); HideTileCursor(); ShowCursor(); ShowBattleUI(); cursorState = CursorStates.ACTION; actionState = ActionStates.MAGIC; } else if (chosenAction == "Item") { BSM.ShowPanel(GameObject.Find("BattleCanvas/BattleUI/ItemPanel")); HideTileCursor(); ShowCursor(); ShowBattleUI(); cursorState = CursorStates.ACTION; actionState = ActionStates.ITEM; } break; } RaycastHit2D[] updateHits = Physics2D.RaycastAll(tileCursor.position, Vector2.zero); foreach (RaycastHit2D hit in updateHits) { if (hit.collider != null && hit.collider.gameObject.tag == "Tile") { tileToAttack = hit.collider.gameObject.GetComponent<Tile>(); tileToAttack.UpdateTilesInRange(); } } if (Input.GetButtonDown("Confirm") && !confirmPressed) { confirmPressed = true; if (!GetTileOnCursor().IfTargetsInRange()) { AudioManager.instance.PlaySE(AudioManager.instance.cantActionSE); } else { AudioManager.instance.PlaySE(AudioManager.instance.confirmSE); tileToAttack.SelectActionTile(); BSM.HidePanel(heroDetailsPanel); BSM.HidePanel(enemyDetailsPanel); HideCursor(); HideTileCursor(); ShowBattleUI(); cursorState = CursorStates.IDLE; actionState = ActionStates.IDLE; } } break; case (CursorStates.IDLE): break; } } if (Input.GetButtonUp("Confirm")) { confirmPressed = false; } if (Input.GetButtonUp("Cancel")) { cancelPressed = false; } if (Input.GetAxisRaw("DpadVertical") == 0 && Input.GetAxisRaw("DpadHorizontal") == 0) { dpadPressed = false; } } void HideTileCursor() { tileCursor.localScale = new Vector3(0.0f, 0.0f, 1.0f); } void ShowTileCursor() { tileCursor.localScale = new Vector3(cursorVisibleScale, cursorVisibleScale, 1.0f); } void HideCursor() { cursor.gameObject.GetComponent<CanvasGroup>().alpha = 0; } void ShowCursor() { cursor.gameObject.GetComponent<CanvasGroup>().alpha = 1; } void HideBattleUI() { GameObject.Find("BattleCanvas/BattleUI").GetComponent<CanvasGroup>().alpha = 0; GameObject.Find("BattleCanvas/BattleUI").GetComponent<CanvasGroup>().interactable = false; GameObject.Find("BattleCanvas/BattleUI").GetComponent<CanvasGroup>().blocksRaycasts = false; } void ShowBattleUI() { GameObject.Find("BattleCanvas/BattleUI").GetComponent<CanvasGroup>().alpha = 1; GameObject.Find("BattleCanvas/BattleUI").GetComponent<CanvasGroup>().interactable = true; GameObject.Find("BattleCanvas/BattleUI").GetComponent<CanvasGroup>().blocksRaycasts = true; } bool IfTileExists(Vector3 checkPos) { RaycastHit2D[] updateHits = Physics2D.RaycastAll(checkPos, Vector2.zero); foreach (RaycastHit2D hit in updateHits) { if (hit.collider != null && hit.collider.gameObject.tag == "Tile") { return true; } } return false; } Tile GetTileOnCursor() { RaycastHit2D[] updateHits = Physics2D.RaycastAll(tileCursor.transform.position, Vector2.zero); foreach (RaycastHit2D hit in updateHits) { if (hit.collider != null && hit.collider.gameObject.tag == "Tile") { return hit.collider.gameObject.GetComponent<Tile>(); } } return null; } GameObject GetUnitOnTile() { RaycastHit2D[] updateHits = Physics2D.RaycastAll(tileCursor.transform.position, Vector3.forward); foreach (RaycastHit2D hit in updateHits) { if (hit.collider != null && (hit.collider.gameObject.tag == "Enemy" || hit.collider.gameObject.tag == "Hero")) { return hit.collider.gameObject; } } return null; } /// <summary> /// Calculates the HP for progress bar for given hero - returns their current HP / their max HP /// </summary> /// <param name="hero">Hero to gather HP data from</param> float GetProgressBarValuesHP(BaseHero hero) { float heroHP = hero.curHP; float heroBaseHP = hero.finalMaxHP; float calc_HP; calc_HP = heroHP / heroBaseHP; return calc_HP; } /// <summary> /// Calculates the MP for progress bar for given hero - returns their current MP / their max MP /// </summary> /// <param name="hero">Hero to gather MP data from</param> float GetProgressBarValuesMP(BaseHero hero) { float heroMP = hero.curMP; float heroBaseMP = hero.finalMaxMP; float calc_MP; calc_MP = heroMP / heroBaseMP; return calc_MP; } /// <summary> /// Calculates the HP for progress bar for given enemy - returns their current HP / their max HP /// </summary> /// <param name="enemy">Enemy to gather HP data from</param> float GetEnemyProgressBarValuesHP(BaseEnemy enemy) { float enemyHP = enemy.curHP; float enemyBaseHP = enemy.baseHP; float calc_HP; calc_HP = enemyHP / enemyBaseHP; return calc_HP; } /// <summary> /// Calculates the MP for progress bar for given enemy - returns their current MP / their max MP /// </summary> /// <param name="enemy">Enemy to gather MP data from</param> float GetEnemyProgressBarValuesMP(BaseEnemy enemy) { float enemyMP = enemy.curMP; float enemyBaseMP = enemy.baseMP; float calc_MP; calc_MP = enemyMP / enemyBaseMP; return calc_MP; } /// <summary> /// Sets Threat Bar on enemyDetailsPanel /// </summary> public void DrawThreatBar(EnemyBehavior eb) { GameObject hero = BSM.HeroesToManage[0]; Image threatBar = enemyDetailsPanel.transform.Find("ThreatProgressBarBG/ThreatProgressBar").GetComponent<Image>(); foreach (BaseThreat threat in eb.threatList) { if (threat.heroObject == hero && threat.threat > 0) { float threatVal = threat.threat; float calc_Threat = threatVal / eb.maxThreat; //does math of % of ATB gauge to be filled threatBar.transform.localScale = new Vector2(Mathf.Clamp(calc_Threat, 0, 1), threatBar.transform.localScale.y); //shows graphic of threat gauge increasing if (calc_Threat == 1) { threatBar.color = eb.maxThreatColor; } else if (calc_Threat >= .75f && calc_Threat <= .99f) { threatBar.color = eb.highThreatColor; } else if (calc_Threat >= .50f && calc_Threat <= .75f) { threatBar.color = eb.moderateThreatcolor; } else if (calc_Threat >= .25f && calc_Threat <= .50f) { threatBar.color = eb.lowThreatcolor; } else { threatBar.color = eb.veryLowThreatColor; } enemyDetailsPanel.transform.Find("ThreatText").GetComponent<Text>().text = threat.threat.ToString(); return; } } //if hero is not in threat list threatBar.color = Color.clear; enemyDetailsPanel.transform.Find("ThreatText").GetComponent<Text>().text = "0"; } /// <summary> /// Instantiates hero panel with hero details /// </summary> void CreateHeroPanel() { HeroPanel = Instantiate(HeroPanel) as GameObject; //creates gameobject of heroPanel prefab (display in BattleCanvas which shows ATB gauge and HP, MP, etc) stats = HeroPanel.GetComponent<HeroPanelStats>(); //gets the hero panel's stats script stats.HeroName.text = hero.name; //sets hero name in the hero panel to the current hero's name stats.HeroHP.text = "HP: " + hero.curHP + "/" + hero.finalMaxHP; //sets HP in the hero panel to the current hero's HP stats.HeroMP.text = "MP: " + hero.curMP + "/" + hero.finalMaxMP; //sets MP in the hero panel to the current hero's MP ProgressBar = stats.ProgressBar; //sets ATB gauge in the hero panel to the hero's ATB HeroPanel.transform.SetParent(HeroPanelSpacer, false); //sets the hero panel to the hero panel's spacer for vertical layout group HeroPanel.name = "BattleHeroPanel - ID " + hero.ID; } /// <summary> /// Returns list of gameobjects in the given affect range /// </summary> /// <param name="affectIndex">Given affect index from attack</param> /// <param name="targetChoice">Given target to be in the center of the affect range</param> List<GameObject> GetTargetsInAffect(int affectIndex, GameObject targetChoice) { GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile"); RaycastHit2D[] tileHits = Physics2D.RaycastAll(targetChoice.transform.position, Vector3.back, 1); foreach (RaycastHit2D tile in tileHits) { if (tile.collider.gameObject.tag == "Tile") { Tile t = tile.collider.gameObject.GetComponent<Tile>(); pattern.GetAffectPattern(t, affectIndex); tilesInRange = pattern.pattern; break; } } foreach (Tile t in tilesInRange) { RaycastHit2D[] tilesHit = Physics2D.RaycastAll(t.transform.position, Vector3.forward, 1); foreach (RaycastHit2D target in tilesHit) { Debug.Log(target.collider.gameObject.name); if (!targets.Contains(target.collider.gameObject) && target.collider.gameObject.tag != "Tile" && target.collider.gameObject.tag != "Shieldable") { Debug.Log("adding " + target.collider.gameObject + " to targets"); if (!targetsAccountedFor.Contains(target.collider.gameObject)) { targets.Add(target.collider.gameObject); //adds all objects inside target range to targets list to be affected targetsAccountedFor.Add(target.collider.gameObject); } } } } targetsAccountedFor.Clear(); return targets; } /// <summary> /// Enables inAffect on given tiles for provided attack /// </summary> /// <param name="attack">Given attack to gather affect pattern</param> /// <param name="parentTile">Parent tile to be the center of the affect pattern</param> void ShowAffectPattern(BaseAttack attack, Tile parentTile) { List<Tile> affectPattern = pattern.GetAffectPattern(parentTile, attack.patternIndex); foreach (Tile rangeTile in affectPattern.ToArray()) { RaycastHit2D[] hits = Physics2D.RaycastAll(rangeTile.transform.position, Vector3.forward, 1); foreach (RaycastHit2D target in hits) { if (target.collider.gameObject.tag != "Shieldable") { Debug.Log(target.collider.gameObject.name + " is shieldable - inAffect"); rangeTile.inAffect = true; } } } } /// <summary> /// Enables inRange on given tiles for provided attack /// </summary> /// <param name="attack">Given attack to gather range pattern</param> /// <param name="parentTile">Parent tile to be the center of the range pattern</param> void ShowRangePattern(BaseAttack attack, Tile parentTile) { List<Tile> rangePattern = pattern.GetRangePattern(parentTile, attack.rangeIndex); foreach (Tile rangeTile in rangePattern.ToArray()) { RaycastHit2D[] hits = Physics2D.RaycastAll(rangeTile.transform.position, Vector3.forward, 1); foreach (RaycastHit2D target in hits) { if (target.collider.gameObject.tag != "Shieldable") { Debug.Log(target.collider.gameObject.name + " is shieldable - inRange"); rangeTile.inRange = true; } } } } /// <summary> /// Disables inAffect and inRange for all tile gameObjects /// </summary> void ClearTiles() { GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile"); foreach (GameObject tileObj in tiles) { Tile tile = tileObj.GetComponent<Tile>(); tile.inAffect = false; tile.inRange = false; } } /// <summary> /// Called when hero action choice is made to process necessary methods /// </summary> private void TimeForAction() { BSM.lastHeroToProcess = gameObject; if (BSM.PerformList[0].actionType == ActionType.ATTACK) { StartCoroutine(AttackAnimation()); } if (BSM.PerformList[0].actionType == ActionType.MAGIC) { StartCoroutine(MagicAnimation()); } if (BSM.PerformList[0].actionType == ActionType.ITEM) { StartCoroutine(ItemAnimation()); } if (BSM.battleState != battleStates.WIN && BSM.battleState != battleStates.LOSE) //if the battle is still going (didn't win or lose) { BSM.battleState = battleStates.WAIT; //sets battle state machine back to WAIT cur_cooldown = 0f; //reset the hero's ATB gauge to 0 currentState = TurnState.PROCESSING; //starts the turn over back to filling up the ATB gauge } else { currentState = TurnState.WAITING; //if the battle is in win or lose state, turns the hero back to WAITING (idle) state } } /// <summary> /// Coroutine. Processes attack animation and damage /// </summary> public IEnumerator AttackAnimation() { if (actionStarted) { yield break; //breaks from the IEnumerator if we have gone through it already } actionStarted = true; BattleCameraManager.instance.physAttackObj = targets[0]; BattleCameraManager.instance.camState = camStates.ATTACK; //animate the hero to the enemy (this is where attack animations will go) //Vector2 enemyPosition = new Vector2(ActionTarget.transform.position.x + 1.5f, ActionTarget.transform.position.y); //sets enemyPosition to the chosen enemy's position + a few pixels on the x axis //while (MoveToTarget(enemyPosition)) { yield return null; } //moves the hero to the calculated position above heroAnim = gameObject.GetComponent<Animator>(); SetHeroFacingDir(targets[0], "atkDirX", "atkDirY"); while (!BattleCameraManager.instance.physAttackCameraZoomFinished) { yield return null; } yield return new WaitForSeconds(.2f); //wait a bit heroAnim.SetBool("onPhysAtk", true); yield return new WaitForSeconds(.25f); AttackAnimation animation = GameObject.Find("BattleManager/AttackAnimationManager").GetComponent<AttackAnimation>(); animation.attack = BSM.PerformList[0].chosenAttack; animation.target = targets[0]; animation.BuildAnimation(); StartCoroutine(animation.PlayAnimation()); yield return new WaitForSeconds(animation.attackDur); //wait a bit BattleCameraManager.instance.physAttackAnimFinished = true; Debug.Log("addedEffect: " + animation.addedEffectAchieved); BaseAddedEffect BAE = new BaseAddedEffect(); BAE.target = targets[0]; BAE.addedEffectProcced = animation.addedEffectAchieved; checkAddedEffects.Add(BAE); animation.addedEffectAchieved = false; heroAnim.SetBool("onPhysAtk", false); Animator tarAnim = targets[0].GetComponent<Animator>(); SetTargetFacingDir(targets[0], "rcvDamX", "rcvDamY"); int hitRoll = GetRandomInt(0, 100); if (hitRoll <= hero.GetHitChance(hero.finalHitRating, hero.finalAgility)) { Debug.Log("turning on takeDamage - " + targets[0].name); tarAnim.SetBool("onRcvDam", true); Debug.Log("Hero hits!"); int critRoll = GetRandomInt(0, 100); if (critRoll <= hero.GetCritChance(hero.finalCritRating, hero.finalDexterity)) { Debug.Log("Hero crits!"); ProcessAttack(targets[0], true); //do damage with calculations (this will change later) } else { Debug.Log("Hero doesn't crit."); ProcessAttack(targets[0], false); //do damage with calculations (this will change later) } Debug.Log(hero.GetCritChance(hero.finalCritRating, hero.finalDexterity) + "% chance to crit, roll was: " + critRoll); } else { StartCoroutine(BSM.ShowMiss(ActionTarget)); Debug.Log(hero.name + " missed!"); } Debug.Log(hero.GetHitChance(hero.finalHitRating, hero.finalAgility) + "% chance to hit, roll was: " + hitRoll); //animate the enemy back to start position //Vector2 firstPosition = startPosition; //changes the hero's position back to the starting position //while (MoveToTarget(firstPosition)) { yield return null; } //move the hero back to the starting position yield return new WaitForSeconds(BSM.damageDisplayTime); PostAnimationCleanup(); actionStarted = false; } /// <summary> /// Coroutine. Processes magic animation and damage /// </summary> public IEnumerator MagicAnimation() { if (actionStarted) { yield break; //breaks from the IEnumerator if we have gone through it already } actionStarted = true; BattleCameraManager.instance.camState = camStates.ATTACK; Debug.Log("Casting: " + BSM.PerformList[0].chosenAttack.name); heroAnim = gameObject.GetComponent<Animator>(); SetHeroFacingDir(targets[0], "atkDirX", "atkDirY"); yield return new WaitForSeconds(.2f); //wait a bit StartCoroutine(BSM.ShowAttackName(BSM.PerformList[0].chosenAttack.name, AudioManager.instance.magicCast.length)); heroAnim.SetBool("onMagAtk", true); AttackAnimation animation = GameObject.Find("BattleManager/AttackAnimationManager").GetComponent<AttackAnimation>(); animation.attack = BSM.PerformList[0].chosenAttack; animation.PlayCastingAnimation(gameObject); yield return new WaitForSeconds(AudioManager.instance.magicCast.length); BattleCameraManager.instance.magicCastingAnimFinished = true; foreach (GameObject target in targets) { BattleCameraManager.instance.currentMagicTarget = target; animation.target = target; animation.BuildAnimation(); StartCoroutine(animation.PlayAnimation()); yield return new WaitForSeconds(animation.attackDur); //wait a bit Debug.Log("addedEffect: " + animation.addedEffectAchieved); BaseAddedEffect BAE = new BaseAddedEffect(); BAE.target = target; BAE.addedEffectProcced = animation.addedEffectAchieved; checkAddedEffects.Add(BAE); animation.addedEffectAchieved = false; } Destroy(GameObject.Find("Casting animation")); if (!targets.Contains(gameObject)) { heroAnim.SetBool("onMagAtk", false); } foreach (GameObject target in targets) { Animator tarAnim = target.GetComponent<Animator>(); SetTargetFacingDir(target, "rcvDamX", "rcvDamY"); if (BSM.PerformList[0].chosenAttack.magicClass != BaseAttack.MagicClass.WHITE) tarAnim.SetBool("onRcvDam", true); ProcessAttack(target, false); if (BSM.PerformList[0].chosenAttack.magicClass == BaseAttack.MagicClass.WHITE) { StartCoroutine(BSM.ShowHeal(magicDamage, target)); } else { foreach (BaseDamage BD in finalDamages) { //Debug.Log("BD obj name:" + BD.obj.name); //Debug.Log("BD dmg: " + BD.finalDamage); if (BD.obj == target) { StartCoroutine(BSM.ShowDamage(BD.finalDamage, target)); break; } } } } yield return new WaitForSeconds(BSM.damageDisplayTime); gameObject.GetComponent<HeroStateMachine>().hero.curMP -= BSM.PerformList[0].chosenAttack.MPCost; heroAnim.SetBool("onMagAtk", false); PostAnimationCleanup(); actionStarted = false; } /// <summary> /// Coroutine. Processes item animation and effects /// </summary> public IEnumerator ItemAnimation() { if (actionStarted) { yield break; //breaks from the IEnumerator if we have gone through it already } actionStarted = true; BattleCameraManager.instance.camState = camStates.ATTACK; StartCoroutine(BSM.ShowAttackName(BSM.PerformList[0].chosenItem.name, AudioManager.instance.magicCast.length)); yield return new WaitForSeconds(1.0f); //wait a bit AttackAnimation animation = GameObject.Find("BattleManager/AttackAnimationManager").GetComponent<AttackAnimation>(); animation.item = BSM.PerformList[0].chosenItem; animation.PlayUsingItemAnimation(gameObject); BattleCameraManager.instance.itemAnimFinished = true; PerformItem(); //process the item foreach (GameObject target in targets) { BattleCameraManager.instance.itemUsedUnit = target; animation.target = target; animation.BuildItemAnimation(); StartCoroutine(animation.PlayItemAnimation()); yield return new WaitForSeconds(animation.itemDur); //wait a bit if (BSM.PerformList[0].chosenItem.type == Item.Types.RESTORATIVE) { StartCoroutine(BSM.ShowHeal(itemDamage, target)); } } yield return new WaitForSeconds(BSM.damageDisplayTime); BSM.ResetItemList(); PostAnimationCleanup(); actionStarted = false; } /// <summary> /// Processes post animation methods /// </summary> void PostAnimationCleanup() { GetStatusEffectsFromCurrentAttack(); checkAddedEffects.Clear(); finalDamages.Clear(); UpdateHeroStats(); GameObject[] attackAnims = GameObject.FindGameObjectsWithTag("AttackAnimation"); foreach (GameObject obj in attackAnims) { Destroy(obj); } playerMove.EndTurn(this); } void SetTargetFacingDir(GameObject target, string paramNameX, string paramNameY) { Animator tarAnim = target.GetComponent<Animator>(); float xDiff = gameObject.transform.position.x - target.transform.position.x; float yDiff = gameObject.transform.position.y - target.transform.position.y; tarAnim.SetFloat(paramNameX, 0); tarAnim.SetFloat(paramNameY, 0); if (xDiff < 0) { tarAnim.SetFloat(paramNameX, -1f); } else if (xDiff > 0) { tarAnim.SetFloat(paramNameX, 1f); } if (yDiff < 0) { tarAnim.SetFloat(paramNameY, -1f); } else if (yDiff > 0) { tarAnim.SetFloat(paramNameY, 1f); } } void SetHeroFacingDir(GameObject target, string paramNameX, string paramNameY) { heroAnim.SetFloat(paramNameX, 0); heroAnim.SetFloat(paramNameY, 0); float xDiff = gameObject.transform.position.x - target.transform.position.x; float yDiff = gameObject.transform.position.y - target.transform.position.y; if (xDiff < 0) { heroAnim.SetFloat(paramNameX, 1f); heroAnim.SetFloat("moveX", 1f); } else if (xDiff > 0) { heroAnim.SetFloat(paramNameX, -1f); heroAnim.SetFloat("moveX", -1f); } if (yDiff < 0) { heroAnim.SetFloat(paramNameY, 1f); heroAnim.SetFloat("moveY", 1f); } else if (yDiff > 0) { heroAnim.SetFloat(paramNameY, -1f); heroAnim.SetFloat("moveY", -1f); } } /// <summary> /// Processes animation for hero gameObject to run to given target position /// </summary> /// <param name="target">Target position to run to for action animation</param> private bool MoveToTarget(Vector3 target) { return target != (transform.position = Vector2.MoveTowards(transform.position, target, animSpeed * Time.deltaTime)); //moves toward target until position is same as target position } /// <summary> /// Processes lowering HP for hero based on given value /// </summary> /// <param name="getDamageAmount">Damage for hero to receive</param> public void TakeDamage(int getDamageAmount) //receives damage from enemy { hero.curHP -= getDamageAmount; //subtracts hero's current HP from getDamageAmount parameter if (hero.curHP <= 0) { hero.curHP = 0; //sets hero's HP to 0 if it is 0 or below currentState = TurnState.DEAD; //changes hero's state to DEAD } UpdateHeroStats(); //updates UI to show current HP and MP } /// <summary> /// Increases given threat value for provided enemy from provided hero /// </summary> /// <param name="enemy">Enemy to receive threat</param> /// <param name="hero">Hero to have threat added from</param> /// <param name="threat">Threat value to add</param> public void IncreaseThreat(GameObject enemy, BaseHero hero, float threat) { EnemyBehavior eb = enemy.GetComponent<EnemyBehavior>(); foreach (BaseThreat t in eb.threatList) { if (hero.name == t.hero.name) { int threatToAdd = Mathf.RoundToInt(threat); t.threat += threatToAdd; if (t.threat > eb.maxThreat) { eb.maxThreat = t.threat; Debug.Log("Setting max threat: " + t.threat); } Debug.Log("Adding " + threat + " threat from hero " + hero.name + " to " + enemy.GetComponent<EnemyStateMachine>().enemy.name); break; } } } /// <summary> /// Lowers HP of target by simulating damage from hero /// </summary> /// <param name="target">GameObject of who is being attacked</param> /// <param name="crit">If true, process critical damage methods</param> void ProcessAttack(GameObject target, bool crit) //deals damage to enemy { int calc_damage = 0; if (target.tag == "Enemy") { if (BSM.PerformList[0].chosenAttack.type == BaseAttack.Type.PHYSICAL) { calc_damage = hero.finalATK + BSM.PerformList[0].chosenAttack.damage; //calculates damage by hero's attack + the chosen attack's damage if (crit) { calc_damage = calc_damage * 2; Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and crits for " + calc_damage + " damage to " + target.GetComponent<EnemyStateMachine>().enemy.name + "!"); Debug.Log(BSM.PerformList[0].chosenAttack.name + " calc_damage - physical - hero's ATK: " + hero.finalATK + " + chosenAttack's damage: " + BSM.PerformList[0].chosenAttack.damage + " * 2 = " + calc_damage); StartCoroutine(BSM.ShowCrit(calc_damage, target)); } else { Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and does " + calc_damage + " damage to " + target.GetComponent<EnemyStateMachine>().enemy.name + "!"); Debug.Log(BSM.PerformList[0].chosenAttack.name + " calc_damage - physical - hero's ATK: " + hero.finalATK + " + chosenAttack's damage: " + BSM.PerformList[0].chosenAttack.damage + " = " + calc_damage); StartCoroutine(BSM.ShowDamage(calc_damage, target)); } float calc_threat = (((calc_damage / 2) + hero.finalThreatRating) * BSM.PerformList[0].chosenAttack.threatMultiplier); IncreaseThreat(target, hero, calc_threat); } else if (BSM.PerformList[0].chosenAttack.type == BaseAttack.Type.MAGIC) //--process from magic script { //can check if magic attack should have a flat value, ie gravity spell //calc_damage = hero.curMATK + BSM.PerformList[0].chosenAttack.damage; //calculates damage by hero's magic attack + the chosen attack's damage //Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and does " + calc_damage + " damage to " + ActionTarget.GetComponent<EnemyStateMachine>().enemy.name + "!"); //Debug.Log(BSM.PerformList[0].chosenAttack.name + " calc_damage - magic - hero's MATK: " + hero.curMATK + " + chosenAttack's damage: " + BSM.PerformList[0].chosenAttack.damage + " = " + calc_damage); BaseMagicScript magicScript = new BaseMagicScript(); magicScript.spell = BSM.PerformList[0].chosenAttack; //sets the spell to be cast by the chosen spell magicScript.heroPerformingAction = hero; //sets hero performing action to this hero magicScript.enemyReceivingAction = target.GetComponent<EnemyStateMachine>().enemy; //sets the enemy receiving action to the target's enemy magicScript.hsm = this; float calc_threat = (((magicDamage / 2) + hero.finalThreatRating) * BSM.PerformList[0].chosenAttack.threatMultiplier); IncreaseThreat(target, hero, calc_threat); foreach (BaseAddedEffect BAE in checkAddedEffects) { if (BAE.target == target) { magicScript.ProcessMagicHeroToEnemy(BAE.addedEffectProcced); //actually process the magic to hero BaseDamage damage = new BaseDamage(); damage.obj = target; damage.finalDamage = magicDamage; finalDamages.Add(damage); break; } } //StartCoroutine(BSM.ShowDamage(magicDamage, target)); } else //if attack type not found { calc_damage = hero.finalATK + BSM.PerformList[0].chosenAttack.damage; //calculates damage by hero's attack + the chosen attack's damage if (crit) { calc_damage = calc_damage * 2; } Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and does " + calc_damage + " damage to " + ActionTarget.GetComponent<EnemyStateMachine>().enemy.name + "! -- NOTE: ATTACK TYPE NOT FOUND: " + BSM.PerformList[0].chosenAttack.type); } target.GetComponent<EnemyStateMachine>().enemyBehavior.TakeDamage(calc_damage); //processes enemy take damage by above value } if (target.tag == "Hero") { if (BSM.PerformList[0].chosenAttack.type == BaseAttack.Type.PHYSICAL) { foreach (BaseAddedEffect BAE in checkAddedEffects) { if (BAE.target == target) { calc_damage = hero.finalATK + BSM.PerformList[0].chosenAttack.damage; //calculates damage by hero's attack + the chosen attack's damage if (crit) { calc_damage = calc_damage * 2; Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and crits for " + calc_damage + " damage to " + target.GetComponent<HeroStateMachine>().hero.name + "!"); Debug.Log(BSM.PerformList[0].chosenAttack.name + " calc_damage - physical - hero's ATK: " + hero.finalATK + " + chosenAttack's damage: " + BSM.PerformList[0].chosenAttack.damage + " * 2 = " + calc_damage); if (BAE.addedEffectProcced) { calc_damage = Mathf.CeilToInt(calc_damage * 2f); } StartCoroutine(BSM.ShowCrit(calc_damage, target)); } else { Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and does " + calc_damage + " damage to " + target.GetComponent<HeroStateMachine>().hero.name + "!"); Debug.Log(BSM.PerformList[0].chosenAttack.name + " calc_damage - physical - hero's ATK: " + hero.finalATK + " + chosenAttack's damage: " + BSM.PerformList[0].chosenAttack.damage + " = " + calc_damage); if (BAE.addedEffectProcced) { calc_damage = Mathf.CeilToInt(calc_damage * 2f); } StartCoroutine(BSM.ShowDamage(calc_damage, target)); } } } } else if (BSM.PerformList[0].chosenAttack.type == BaseAttack.Type.MAGIC) //--process from magic script { //can check if magic attack should have a flat value, ie gravity spell //calc_damage = hero.curMATK + BSM.PerformList[0].chosenAttack.damage; //calculates damage by hero's magic attack + the chosen attack's damage //Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and does " + calc_damage + " damage to " + ActionTarget.GetComponent<HeroStateMachine>().hero.name + "!"); //Debug.Log(BSM.PerformList[0].chosenAttack.name + " calc_damage - magic - hero's MATK: " + hero.curMATK + " + chosenAttack's damage: " + BSM.PerformList[0].chosenAttack.damage + " = " + calc_damage); BaseMagicScript magicScript = new BaseMagicScript(); magicScript.spell = BSM.PerformList[0].chosenAttack; //sets the spell to be cast by the chosen spell magicScript.heroPerformingAction = hero; //sets hero performing action to this hero magicScript.heroReceivingAction = target.GetComponent<HeroStateMachine>().hero; //sets the hero receiving action to the target's hero magicScript.hsm = this; foreach (BaseAddedEffect BAE in checkAddedEffects) { if (BAE.target == target) { magicScript.ProcessMagicHeroToHero(BAE.addedEffectProcced); //actually process the magic to hero BaseDamage damage = new BaseDamage(); damage.obj = target; damage.finalDamage = magicDamage; finalDamages.Add(damage); break; } } //magicScript.ProcessMagicHeroToHero(); //actually process the magic to hero //StartCoroutine(BSM.ShowDamage(magicDamage, target)); } else //if attack type not found { calc_damage = hero.finalATK + BSM.PerformList[0].chosenAttack.damage; //calculates damage by hero's attack + the chosen attack's damage if (crit) { calc_damage = calc_damage * 2; } Debug.Log(hero.name + " has chosen " + BSM.PerformList[0].chosenAttack.name + " and does " + calc_damage + " damage to " + target.GetComponent<HeroStateMachine>().hero.name + "! -- NOTE: ATTACK TYPE NOT FOUND: " + BSM.PerformList[0].chosenAttack.type); } target.GetComponent<HeroStateMachine>().TakeDamage(calc_damage); //processes enemy take damage by above value } } /// <summary> /// Processes chosen item /// </summary> void PerformItem() { //action item BaseItemScript itemScript = new BaseItemScript(); itemScript.scriptToRun = BSM.PerformList[0].chosenItem.name; //sets which item script to be run itemScript.hsm = this; foreach (GameObject target in targets) { if (target.tag == "Hero") { itemScript.ProcessItemToHero(target.GetComponent<HeroStateMachine>().hero); } if (target.tag == "Enemy") { itemScript.ProcessItemToEnemy(target.GetComponent<EnemyStateMachine>().enemy); } } Inventory.instance.Remove(BSM.PerformList[0].chosenItem); } /// <summary> /// Updates GUI with new HP/MP values after attack /// </summary> public void UpdateHeroStats() { GameObject[] heroes = GameObject.FindGameObjectsWithTag("Hero"); foreach (GameObject heroObj in heroes) { HeroStateMachine heroHSM = heroObj.GetComponent<HeroStateMachine>(); heroHSM.stats.HeroHP.text = "HP: " + heroHSM.hero.curHP + "/" + heroHSM.hero.finalMaxHP; heroHSM.stats.HeroMP.text = "MP: " + heroHSM.hero.curMP + "/" + heroHSM.hero.finalMaxMP; foreach (BaseHero hero in GameManager.instance.activeHeroes) { if (hero.name == heroHSM.hero.name) { hero.curHP = heroHSM.hero.curHP; hero.curMP = heroHSM.hero.curMP; } } } } /// <summary> /// Recovers MP based on spirit and calculations /// </summary> public void RecoverMPAfterTurn() { if (hero.curMP < hero.baseMP) { hero.curMP += hero.GetRegen(hero.finalRegenRating, hero.finalSpirit); Debug.Log(hero.name + " recovering " + hero.GetRegen(hero.finalRegenRating, hero.finalSpirit) + " MP"); } if (hero.curMP > hero.finalMaxMP) { hero.curMP = hero.finalMaxMP; } UpdateHeroStats(); } /// <summary> /// Adds status effect(s) from current attack to current target /// </summary> public void GetStatusEffectsFromCurrentAttack() { //if target is ally, add to ally's active status effects. if target is enemy, add to enemy's list if (BSM.PerformList[0].chosenAttack != null && BSM.PerformList[0].chosenAttack.statusEffects.Count > 0) { foreach (BaseStatusEffect statusEffect in BSM.PerformList[0].chosenAttack.statusEffects) { foreach (GameObject target in targets) { BaseEffect effectToApply = new BaseEffect(); effectToApply.effectName = statusEffect.name; effectToApply.effectType = statusEffect.effectType.ToString(); effectToApply.turnsRemaining = statusEffect.turnsApplied; effectToApply.baseValue = statusEffect.baseValue; Debug.Log("Status effect: " + effectToApply.effectName + ", type: " + effectToApply.effectType + " - applied to " + target.name); if (target.tag == "Enemy") { target.GetComponent<EnemyBehavior>().activeStatusEffects.Add(effectToApply); } else if (target.tag == "Hero") { target.GetComponent<HeroStateMachine>().activeStatusEffects.Add(effectToApply); } } } } else if (BSM.PerformList[0].chosenItem != null && BSM.PerformList[0].chosenItem.statusEffects.Count > 0) { foreach (BaseStatusEffect statusEffect in BSM.PerformList[0].chosenItem.statusEffects) { foreach (GameObject target in targets) { BaseEffect effectToApply = new BaseEffect(); effectToApply.effectName = statusEffect.name; effectToApply.effectType = statusEffect.effectType.ToString(); effectToApply.turnsRemaining = statusEffect.turnsApplied; effectToApply.baseValue = statusEffect.baseValue; Debug.Log("Status effect: " + effectToApply.effectName + ", type: " + effectToApply.effectType + " - applied to " + target.name); if (target.tag == "Enemy") { target.GetComponent<EnemyBehavior>().activeStatusEffects.Add(effectToApply); } else if (target.tag == "Hero") { target.GetComponent<HeroStateMachine>().activeStatusEffects.Add(effectToApply); } } } } } /// <summary> /// Processes the status effect(s) from current attack to current target, lowers the turns remaining, and removs the status effect if needed /// </summary> public void ProcessStatusEffects() { for (int i = 0; i < activeStatusEffects.Count; i++) { StatusEffect effectToProcess = new StatusEffect(); effectToProcess.hsm = this; effectToProcess.ProcessEffect(activeStatusEffects[i].effectName, activeStatusEffects[i].effectType, activeStatusEffects[i].baseValue, this.gameObject); if (effectDamage > 0) { StartCoroutine(BSM.ShowElementalDamage(effectDamage, this.gameObject, effectToProcess.elementColor)); } activeStatusEffects[i].turnsRemaining--; //lowers turns remaining by 1 Debug.Log(hero.name + " - turns remaining on " + activeStatusEffects[i].effectName + ": " + activeStatusEffects[i].turnsRemaining); if (activeStatusEffects[i].turnsRemaining == 0) //removes status effect if no more turns remaining { Debug.Log(activeStatusEffects[i].effectName + " removed from " + hero.name); activeStatusEffects.RemoveAt(i); } } UpdateHeroStats(); } /// <summary> /// Returns random integer between provided values /// </summary> /// <param name="min">Minimum value for random value</param> /// <param name="max">Maximum value for random value</param> int GetRandomInt(int min, int max) { Random.InitState(System.DateTime.Now.Millisecond); int rand = Random.Range(min, max); return rand; } /// <summary> /// Used in update method to increase the hero's ATB progress bar /// </summary> void UpgradeProgressBar() { cur_cooldown = (cur_cooldown + (Time.deltaTime / 1f)) + (hero.finalDexterity * .000055955f); //increases ATB gauge, first float dictates how slowly gauge fills (default 1f), while second float dictates how effective dexterity is float calc_cooldown = cur_cooldown / max_cooldown; //does math of % of ATB gauge to be filled each frame ProgressBar.transform.localScale = new Vector2(Mathf.Clamp(calc_cooldown, 0, 1), ProgressBar.transform.localScale.y); //shows graphic of ATB gauge increasing if (cur_cooldown >= max_cooldown) //if hero turn is ready { BSM.pendingTurn = true; calculatedTilesToMove = false; currentState = TurnState.ADDTOLIST; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Bit8Piano { static class Program { /// <summary> /// /// The main entry point for the application. /// </summary> [STAThread] static void Main() { IBeatModel beatModel = new BeatModel(); IBeatController controller = new BeatController(beatModel); Application.Run(controller.ViewProp); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New GunDefinition", menuName = "Old/New Secondary Gun")] public class SecondaryGunsDefinition : BaseGunDefinition { public override void AdsFire(ShootData shootData) { AddAdsRecoil(shootData.gunObject); } public override void HipFire(ShootData shootData) { AddHipRecoil(shootData.gunObject); } public override void AddAdsRecoil(GameObject gunModel) { } public override void AddHipRecoil(GameObject gunModel) { } }
using JhinBot.DiscordObjects; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; namespace JhinBot.Database { public interface IGuildConfigRepository : IRepository<GuildConfig> { GuildConfig For(ulong guildId, Func<DbSet<GuildConfig>, IQueryable<GuildConfig>> includes = null); IEnumerable<GuildConfig> GetAllGuildConfigs(); } }
using System.Threading.Tasks; using Uintra.Features.Notification.Models; namespace Uintra.Features.Notification.Configuration.BackofficeSettings.Helpers { public interface IBackofficeSettingsReader { string ReadSettings(ActivityEventNotifierIdentity notificationType); Task<string> ReadSettingsAsync(ActivityEventNotifierIdentity notificationType); } }
using System; namespace Task1_Vector { class Program { static void Main(string[] args) { try { //initialization instance Input input = new Input(); Output output = new Output(); //get 2 vectors Vector firstVector = input.GetUserInput(); Vector secondVector = input.GetUserInput(); //do all overload operations and print it output.PrintAllOperations(firstVector, secondVector); if (firstVector == secondVector) { Console.WriteLine("Векторы равны"); } if (firstVector != secondVector) { Console.WriteLine("Векторы НЕ равны"); } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
using System; using Autofac; namespace Simple.Wpf.Composition.Workspaces.Logging { public sealed class LoggingWorkspaceDescriptor : IWorkspaceDescriptor { private readonly Uri _resources = new Uri("/simple.wpf.composition;component/workspaces/logging/resources.xaml", UriKind.RelativeOrAbsolute); private readonly WorkspaceFactory _workspaceFactory; public LoggingWorkspaceDescriptor(WorkspaceFactory workspaceFactory) { _workspaceFactory = workspaceFactory; } public int Position => 0; public string Name => "Logging Workspace"; public Workspace CreateWorkspace() { return _workspaceFactory.Create<Registrar, LoggingController>(_resources); } // ReSharper disable once ClassNeverInstantiated.Local private sealed class Registrar { // Scoped registrations, these will be thrown away when the workspace is disposed... public Registrar(ContainerBuilder container) { container.RegisterType<MemoryLogReader>().As<ILogReader>() .WithParameter(new NamedParameter("logName", "memory")); container.RegisterType<LoggingViewModel>(); container.RegisterType<LoggingController>(); } } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class playerInput : MonoBehaviour { //public static InputField nameInput; //public Text nameText; // Update is called once per frame public void storeName(InputField nameInput){ StatsManager.playerName = nameInput.text; //nameText.text = StatsManager.playerName.ToString(); } public static void changeName () { //nameText.text = StatsManager.playerName; } }
using Report_ClassLibrary; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Login : System.Web.UI.Page { Dictionary<string, bool> UserList = new Dictionary<string, bool>(); private List<UserLogin> LoginUser = new List<UserLogin>(); string conStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session.Clear(); Session.RemoveAll(); Session.Abandon(); Session["QALogin"] = null; txtusername.Focus(); } var requestTarget = this.Request["__EVENTTARGET"]; //var requestArgs = this.Request["__EVENTARGUMENT"]; if (requestTarget != null && !string.IsNullOrEmpty(requestTarget)) { if (requestTarget == "enter_pass") { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "hideValidateMsg();", true); LogOn(); } } } private void LogOn() { bool verifyLogin = false; string username = txtusername.Text; string password = txtpassword.Text; if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { Dictionary<string, object> p = new Dictionary<string, object>(); p.Add("UserName", username); p.Add("Password", password); var dt = Helper.ExecuteProcedureToTable(conStr, "proc_qa_user_get", p); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { UserLogin u = new UserLogin(); u.UserName = row["UserName"].ToString(); u.Password = row["Password"].ToString(); u.BranchID = row["BranchID"].ToString(); u.FullName = row["FullName"].ToString(); u.PhoneNo = row["PhoneNo"].ToString(); LoginUser.Add(u); } if (LoginUser.Count > 0) { verifyLogin = true; Session["QALogin"] = LoginUser; } } } if (verifyLogin) { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "hideValidateMsg();", true); Response.Redirect("~/Page1.aspx"); } else { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "showValidateMsg();", true); Session["QALogin"] = null; } } protected void btnlogin_Click(object sender, EventArgs e) { LogOn(); } }
 [DBTable("Clients")] public class Client { [DBColumn("id")] public long Id { get; set; } [DBColumn("name")] public string Name { get; set; } [DBColumn("discount")] public long Discount { get; set; } public Client() { } public Client(long id, string name, long discount) { Id = id; Name = name; Discount = discount; } public Client(Client source) { Id = source.Id; Name = source.Name; Discount = source.Discount; } }
#version 430 layout(local_size_x = 32, local_size_y = 32) in; // bind buffers // prediction error covariance layout(std430, binding = 0) buffer bufferP { mat2 P []; }; // measurement vector layout(std430, binding = 1) buffer bufferZ { vec2 z []; }; // state vector layout(std430, binding = 2) buffer bufferX { vec2 x []; }; // set uniforms // set Process Model Jacobian uniform mat2 F; // set Measurement Funciton Jacobian uniform mat2 H; // approximate process noise using a small constant uniform mat2 Q; // approximate measurement noise using a small constant uniform mat2 R; // identity, size n x n mat2 I = mat2(1.0f); // set subroutines // predict void predict(in ivec2 _pos, inout mat2 _Pp) { /* P_k = F_{k-1} P_{k-1} F^T_{k-1} + Q_{k-1} */ _Pp = F * P[_pos.x] * transpose(F) + Q; } // update void update(in ivec2 _pos, inout mat2 _Pp) { /* G_k = P_k H^T_k (H_k P_k H^T_k + R)^{-1} */ mat2 G = _Pp * transpose(H) * inverse(H * _Pp * transpose(H) + R); /* \hat{x}_k = \hat{x_k} + G_k(z_k - h(\hat{x}_k)) */ x[_pos.x] = x[_pos.x] + G * (z[_pos.x] - H * x[_pos.x]); /* P_k = (I - G_k H_k) P_k */ P[_pos.x] = (I - (G * H)) * _Pp; } void main() { mat2 Pp; ivec2 pos = ivec2(gl_GlobalInvocationID.xy); predict(pos, Pp); update(pos, Pp); }
using UnityEngine; using System.Collections; using System.Collections.Generic; using MusicIO; public class BaseTool : MonoBehaviour { public GloveController glove{ get { return m_gloveController; }} protected GloveController m_gloveController = null; //For inspector previewing of active states public HandState activeGestureState; public ToolMode toolMode; //Variables protected List<object> m_targets = null; protected BaseInstrument m_instrumentRef = null; public enum ToolHand {BOTH = 0, LEFT, RIGHT }; protected ToolHand m_hand; public ToolHand Hand{get { return m_hand; }} //Tool modes public enum ToolMode{PRIMARY = 0, SECONDARY, TERTIARY, GRABBING, PLAY1, PLAY2, PLAY3, PLAY4, IDLE}; protected ToolMode m_mode = ToolMode.PRIMARY; public ToolMode mode{ get { return m_mode; }} //Hand states public enum HandState{ IDLE = 0, SEARCHING, HOLDING, RELEASING}; protected HandState m_toolHandState = HandState.IDLE; public HandState handState{ get { return m_toolHandState; }} //Constructor public BaseTool(){ } public virtual void Awake(){ m_toolHandState = BaseTool.HandState.SEARCHING; m_gloveController = GetComponent<GloveController>(); m_targets = new List<object>(); } public virtual void Update () { activeGestureState = m_toolHandState; //Inspector level previewing of state toolMode = m_mode; } public static SixenseHands ToolHandToSixenseHand(BaseTool.ToolHand hand){ if(hand == ToolHand.LEFT) return SixenseHands.LEFT; if(hand == ToolHand.RIGHT) return SixenseHands.RIGHT; return SixenseHands.UNKNOWN; } //Initializer public virtual void Init(ToolHand hand, BaseTool.ToolMode mode){ m_hand = hand; m_mode = mode; //Set collider model for hand based on active gesture glove.SetCollider(glove.activeGesture); //Trigger the transition TransitionIn(); } //Instrument tools public void setInstrument(BaseInstrument instrument){ m_instrumentRef = instrument; } //Transitions public virtual void TransitionIn(){ } public virtual void TransitionOut(){ } public virtual void LeavingProximity(){ } //Accessors public List<object> targets { get { return m_targets; }} public void setTargets<T>(T target){ List<object> valueList = new List<object>(); valueList.Add(target); this.setTargets(valueList); } public void setTargets(List<object> targets){ m_targets = targets; } public static Vector3 HandToObjectSpace(Vector3 worldPosition, Transform objectSpace){ return objectSpace.InverseTransformPoint(worldPosition); } } /* * String enum class defining interactable tag types */ public static class InteractableTypes { public const string GENERATOR = "Generator"; public const string INSTRUMENT = "Instrument"; public const string RBFPOINT = "RBFPoint"; public const string MUSICGROUP = "MusicGroup"; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_IssPrefeitura.Dominio.Entities { public class Config { public int ConfiguracoesId { get; set; } public string Titular { get; set; } public string CpfTitular { get; set; } public string Substituto { get; set; } public int Codigo { get; set; } public string Cmc { get; set; } public string RazaoSocial { get; set; } public string Endereco { get; set; } public string Bairro { get; set; } public string Cidade { get; set; } public string Uf { get; set; } public string Cep { get; set; } public string Telefone1 { get; set; } public string Telefone2 { get; set; } public string Email { get; set; } public string Cnpj { get; set; } public int ProximoLivro { get; set; } public int ProximaFolha { get; set; } public string TipoCalculoIss { get; set; } public double ValorAliquota { get; set; } public int TotalFolhasPorLivro { get; set; } public string NomeArquivoImportando { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using nsGEN_VarSession; using nsGEN_Java; using nsGEN_WebForms; using System.Data; using nsGEN; namespace Admisiones.Forms { public partial class ADMIS_BuscarPersona : System.Web.UI.Page { #region "Librerias Externas" GEN_VarSession axVarSes = new GEN_VarSession(); GEN_Java libJava = new GEN_Java(); GEN_WebForms webForms = new GEN_WebForms(); SIS_GeneralesSistema Generales = new SIS_GeneralesSistema(); #endregion #region "Clase de tablas de la Base de Datos" BD_ADMIS_DatosPersonales libDatos = new BD_ADMIS_DatosPersonales(); #endregion #region "Funciones y procedimientos" private void CargarDatosIniciales(string strCon) { if (!string.IsNullOrEmpty(strCon.Trim())) { /*libproc.StrConexion = axVarSes.Lee<string>("strConexion"); if (libproc.AccesoObjetoUsuario("ALM_ALM_AdministrarAlmacenes")) { lisubdeptos = new BD_GEN_Subdeptos(); lisubdeptos.StrConexion = axVarSes.Lee<string>("strConexion"); ddlSubdeptos.DataSource = lisubdeptos.DTVerSubdeptos(); ddlSubdeptos.DataTextField = "NOMBRE"; ddlSubdeptos.DataValueField = "NUM_SEC_subdepartamento"; ddlSubdeptos.DataBind(); if (!string.IsNullOrEmpty(ddlSubdeptos.SelectedValue)) { llenartabla(); } } else { axVarSes.Escribe("MostrarMensajeError", "1"); Response.Redirect("Index.aspx"); }*/ } else { Response.Redirect("~/Default.aspx"); } } protected void llenartabla() { } #endregion #region "Eventos" protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { CargarDatosIniciales(axVarSes.Lee<string>("strConexion")); } } protected void ddlSubdeptos_SelectedIndexChanged(object sender, EventArgs e) { pnMensajeError.Visible = false; llenartabla(); } protected void btnAgregarUsuario_Click(object sender, EventArgs e) { //pnbuscar.Visible = true; } /*protected void btnAdmUsu_Click(object sender, EventArgs e) { pnMensajeError.Visible = false; pnMensajeOK.Visible = false; if ((ddlAlmacenes.Items.Count != 0)&&(ddlPlantilla.Items.Count != 0)) { pnAdmUsuarios.Visible = true; pnPrincipal.Visible = true; libPasosUsu.StrConexion = axVarSes.Lee<string>("strConexion"); libPasosUsu.NumSecPaso = Convert.ToInt64(ddlPasos.SelectedValue); gvDatos1.Visible = true; gvDatos1.Columns[0].Visible = true; gvDatos1.Columns[2].Visible = true; gvDatos1.Columns[4].Visible = true; gvDatos1.DataSource = libPasosUsu.VerUsuariosPaso(); gvDatos1.DataBind(); gvDatos1.Columns[0].Visible = false; gvDatos1.Columns[2].Visible = false; gvDatos1.Columns[4].Visible = false; pnDeptos.Visible = true; libsubdeptos = new BD_GEN_Subdeptos(); libsubdeptos.StrConexion = axVarSes.Lee<string>("strConexion"); ddlDeptos.DataSource = libsubdeptos.DTVerSubdeptos(); ddlDeptos.DataTextField = "NOMBRE"; ddlDeptos.DataValueField = "NUM_SEC_subdepartamento"; ddlDeptos.DataBind(); } else { pnMensajeError.Visible = true; lblMensajeError.Text = "No existe ningún almacen creado o falta seleccionar un paso. "; } }*/ protected void btnBuscar_Click(object sender, EventArgs e) { pnMensajeError.Visible = false; pnMensajeOK.Visible = false; pnsugeridos.Visible = true; libDatos.StrConexion = axVarSes.Lee<string>("strConexion"); gvUsuarios.Visible = true; gvUsuarios.Columns[0].Visible = true; gvUsuarios.DataSource = libDatos.dtObtenerPersonas(tbusuario.Text); gvUsuarios.DataBind(); gvUsuarios.Columns[0].Visible = false; } protected void btnVolverMenu_Click(object sender, EventArgs e) { Response.Redirect("Index.aspx"); } protected void btnCancelarItem_Click(object sender, EventArgs e) { Response.Redirect("ALM_AdministrarPasos.aspx"); } protected void gvDatos1_RowCommand(object sender, GridViewCommandEventArgs e) { /* int indice = Convert.ToInt32(e.CommandArgument); bool blOpCorrecta = false; libSubdeptoPer.NumSecSubdepto = Convert.ToInt64(ddlSubdeptos.SelectedValue); libSubdeptoPer.StrConexion = axVarSes.Lee<string>("strConexion"); if (e.CommandName == "agregar") { libSubdeptoPer.NumSecPersona = Convert.ToInt64(gvUsuarios.Rows[indice].Cells[3].Text); libSubdeptoPer.NumSecPersonaAutoriza = Convert.ToInt64(gvUsuarios.Rows[indice].Cells[3].Text); if (!libSubdeptoPer.Insertar()) { pnMensajeError.Visible = true; lblMensajeError.Text = "No se pudo agregar la persona. " + Convert.ToInt64(gvUsuarios.Rows[indice].Cells[2].Text) + ". " + libSubdeptoPer.Mensaje; pnMensajeOK.Visible = false; } else { blOpCorrecta = true; } } if (e.CommandName == "eliminar") { libSubdeptoPer.NumSecPersona = Convert.ToInt64(gvDatos1.Rows[indice].Cells[3].Text); libSubdeptoPer.NumSecPersonaAutoriza = Convert.ToInt64(gvDatos1.Rows[indice].Cells[3].Text); if (!libSubdeptoPer.Borrar()) { pnMensajeError.Visible = true; lblMensajeError.Text = "No se pudo eliminar la persona. " + Convert.ToInt64(gvDatos1.Rows[indice].Cells[2].Text) + ". " + libSubdeptoPer.Mensaje; pnMensajeOK.Visible = false; } else { blOpCorrecta = true; } } if (blOpCorrecta) { pnMensajeError.Visible = false; } else { pnVacio.Focus(); } if (!string.IsNullOrEmpty(ddlSubdeptos.SelectedValue)) { llenartabla(); }*/ } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BetterCrabPotsConfigUpdater.ModConfigs { class Item { public int Id { get; set; } public int Chance { get; set; } public int Quantity { get; set; } public Item(int id = -1, int chance = 1, int quantity = 1) { Id = id; Chance = chance; Quantity = quantity; } } }
using DAL.API; using Models; using System.Collections.Generic; using System.Linq; namespace DAL { public class UserRepository : IUserRepository { readonly Data _data; public UserRepository(Data data) { _data = data; } public IEnumerable<string> GetAllUserNames() => _data.Users.Select(u => u.UserName); public bool Login(User user) { foreach (var u in _data.Users) if (u.UserName == user.UserName && u.Password == user.Password) return true; return false; } public bool Register(User user) { var res = _data.Users.FirstOrDefault(u => u.UserName == user.UserName); if (res != null) return false;// user exist _data.Users.Add(user); _data.SaveChanges(); return true; } } }
using Xamarin.Forms; namespace SOS.Views { public partial class SignUpORLogin : ContentPage { public SignUpORLogin() { InitializeComponent(); } } }
namespace DelftTools.TestUtils { /// <summary> /// Used to make paths strongly typed, see <see cref="TestHelper.GetTestDataPath"/> /// </summary> public class TestDataPath { public string Path { get; set; } public static implicit operator TestDataPath(string path) { return new TestDataPath {Path = path}; } public static class Plugins { public static class Habitat { public static readonly TestDataPath DeltaShellPluginsImportersHabitatTests = @"Plugins/Habitat/DeltaShell.Plugins.Importers.Habitat.Tests"; public static readonly TestDataPath DeltaShellPluginsHabitatTests = @"Plugins/Habitat/DeltaShell.Plugins.Habitat.Tests"; public static readonly TestDataPath DeltaShellPluginsImportExportDemisTests = @"Plugins/Habitat/DeltaShell.Plugins.ImportExport.Demis.Tests"; public static readonly TestDataPath DeltaShellPluginsDemisMapControlTests = @"Plugins/Habitat/DeltaShell.Plugins.Demis.MapControl.Tests"; } public static class DelftModels { public static readonly TestDataPath DeltaShellPluginsDelftModelsWaterFlowModelTests = @"Plugins/DelftModels/DeltaShell.Plugins.DelftModels.WaterFlowModel.Tests"; public static readonly TestDataPath DeltaShellPluginsImportExportSobekTests = @"Plugins/DelftModels/DeltaShell.Plugins.ImportExport.Sobek.Tests"; public static readonly TestDataPath DeltaShellPluginsWaterFlowModelIntegrationTests = @"Plugins\DelftModels\DeltaShell.Plugins.DelftModels.WaterFlowModel.IntegrationTests"; } } public static class Common { public static class DelftTools { public static readonly TestDataPath DelftToolsTests = @"Common/DelftTools.Tests"; public static readonly TestDataPath DelftToolsTestsUtilsXmlSerialization = @"Common/DelftTools.Tests/Utils/Xml/Serialization"; } } public static class DeltaShell { public static readonly TestDataPath DeltaShellDeltaShellPluginsDataXmlTests = @"DeltaShell/DeltaShell.Plugins.Data.Xml.Tests"; public static readonly TestDataPath DeltaShellDeltaShellPluginsSharpMapGisTests = @"DeltaShell/DeltaShell.Plugins.SharpMapGis.Tests/"; public static readonly TestDataPath DeltaShellDeltaShellPluginsSharpMapGisTestsRasterData = @"DeltaShell/DeltaShell.Plugins.SharpMapGis.Tests/RasterData/"; public static readonly TestDataPath DeltaShellDeltaShellIntegrationTests = @"DeltaShell/DeltaShell.IntegrationTests/"; public static readonly TestDataPath DeltaShellDeltaShellIntegrationTestsNetCdf = @"DeltaShell/DeltaShell.IntegrationTests/NetCdf/"; public static readonly TestDataPath DeltaShellDeltaShellIntegrationTestsGDAL = @"DeltaShell/DeltaShell.IntegrationTests/GDAL/"; public static readonly TestDataPath DeltaShellPluginsDataNHibernateTests = @"DeltaShell/DeltaShell.Plugins.Data.NHibernate.Tests"; public static readonly TestDataPath DeltaShellPluginsNetCDFTests = @"DeltaShell/DeltaShell.Plugins.NetCDF.Tests"; public static readonly TestDataPath DeltaShellPluginsDataNHibernateIntegrationTests = @"DeltaShell/DeltaShell.Plugins.Data.NHibernate.IntegrationTests/"; } public static class VectorData { public static readonly TestDataPath VectorDataPath = @"vectorData"; } public static class RasterData { public static readonly TestDataPath RasterDataPath = @"rasterData"; } public static class NetCdfData { public static readonly TestDataPath NetCdfDataPath = @"netCdfData"; } //public static class DeltaShell //{ // internal static class DelftShell // { // public static class Plugin // { // public static class Data // { // public static class Xml // { // public static readonly TestDataPath Tests = @"DeltaShell/DeltaShell.Plugins.Data.Xml.Tests"; // } // } // } // } //} } }
using System.Drawing; namespace DelftTools.Utils.Drawing { public interface IShape { int Width { get; set; } int Height { get; set; } Color ColorFillSolid { get; set; } float BorderWidth { get; set; } Color BorderColor { get; set; } ShapeType ShapeType { get; set; } void Paint(Graphics graphics); } }
using AkvelonTaskMilosBelic.Interfaces; using AkvelonTaskMilosBelic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace AkvelonTaskMilosBelic.Repository { public class ProjectRepository: IDisposable, IProjectRepository { private ModelsDbContext db = new ModelsDbContext(); public IEnumerable<Project> GetAll(string sortType) { if(sortType.Equals("StartDateAscending")) { return db.Projects.Include(x => x.ProjectTasks).OrderBy(x => x.StartDate); } else if(sortType.Equals("StartDateDescending")) { return db.Projects.Include(x => x.ProjectTasks).OrderByDescending(x => x.StartDate); } else if (sortType.Equals("PriorityAscending")) { return db.Projects.Include(x => x.ProjectTasks).OrderBy(x => x.Priority); } else if (sortType.Equals("PriorityDescending")) { return db.Projects.Include(x => x.ProjectTasks).OrderByDescending(x => x.Priority); } return db.Projects.Include(x => x.ProjectTasks); } public IEnumerable<Project> GetByPriority(Filter filter) { return db.Projects.Include(x => x.ProjectTasks).Where(x => x.Priority >= filter.Min && x.Priority <= filter.Max); } public Project GetById(int id) { foreach(Project project in db.Projects) { if(project.Id == id) { return project; } } throw new Exception("There is no project with this id:" + id); } public void Create(Project project) { db.Projects.Add(project); db.SaveChanges(); } public void Delete(int id) { foreach (Project project in db.Projects) { if (id == project.Id) { db.Projects.Remove(project); db.SaveChanges(); } } } public void Update(Project project) { db.Entry(project).State = EntityState.Modified; try { db.SaveChanges(); } catch(DbUpdateConcurrencyException) { throw; } } public void AddTaskToProject(Project project, ProjectTask projectTask) { if (!project.ProjectTasks.Contains(projectTask)) { project.ProjectTasks.Add(projectTask); db.SaveChanges(); } else throw new Exception("The project already contains a task in its task list"); } public void DeleteTaskFromProject(Project project, ProjectTask projectTask) { if (project.ProjectTasks.Contains(projectTask)) { project.ProjectTasks.Remove(projectTask); db.SaveChanges(); } else throw new Exception("The project doesnt contains this task in its task list"); } public void Dispose(bool disposing) { if (disposing) { if (db != null) { db.Dispose(); db = null; } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
using System; using UnityEditor; using UnityEngine; namespace ScriptableObjectFramework.Attributes { /// <summary> /// Shows property only in play mode if PlayMode is true. Only outside of play mode if PlayMode if false; /// </summary> [AttributeUsage(AttributeTargets.Field)] public class ShowByPlayMode : PropertyModifier { public bool PlayMode = true; #if UNITY_EDITOR public override void BeforeGUI(ref Rect position, SerializedProperty property, GUIContent label, ref bool visible) { visible = EditorApplication.isPlaying == PlayMode; } public override float GetPropertyHeight(SerializedProperty property, GUIContent label, float height) { return EditorApplication.isPlaying == PlayMode ? height : 0; } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Projet2Cpi { public class Seance { public string name; public string description; public DateTime begin; public DateTime end; public string priority; } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace PizzaBox.Client.Models { public partial class PizzaBoxContext : DbContext { public PizzaBoxContext() { } public PizzaBoxContext(DbContextOptions<PizzaBoxContext> options) : base(options) { } public virtual DbSet<Crust> Crust { get; set; } public virtual DbSet<Customers> Customers { get; set; } public virtual DbSet<Orders> Orders { get; set; } public virtual DbSet<Pizzas> Pizzas { get; set; } public virtual DbSet<Store> Store { get; set; } public virtual DbSet<Toppings> Toppings { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Crust>(entity => { entity.ToTable("Crust", "Pizza"); entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.Crust1) .HasColumnName("crust") .IsUnicode(false); entity.Property(e => e.Price) .HasColumnName("price") .HasColumnType("money"); }); modelBuilder.Entity<Customers>(entity => { entity.HasKey(e => e.Customerid) .HasName("PK__Customer__B61ED7F5ACBFFD19"); entity.ToTable("Customers", "Pizza"); entity.Property(e => e.Customerid).HasColumnName("customerid"); entity.Property(e => e.Fname) .HasColumnName("fname") .IsUnicode(false); entity.Property(e => e.Lastorder) .HasColumnName("lastorder") .HasColumnType("datetime"); entity.Property(e => e.Lname) .HasColumnName("lname") .IsUnicode(false); }); modelBuilder.Entity<Orders>(entity => { entity.HasKey(e => e.Orderuid) .HasName("PK__Orders__A69E34B48D441910"); entity.ToTable("Orders", "Pizza"); entity.Property(e => e.Orderuid).HasDefaultValueSql("(newid())"); entity.Property(e => e.Crust).HasColumnName("crust"); entity.Property(e => e.Customerid).HasColumnName("customerid"); entity.Property(e => e.Dateordered) .HasColumnName("dateordered") .HasColumnType("datetime"); entity.Property(e => e.Ordercost) .HasColumnName("ordercost") .HasColumnType("money"); entity.Property(e => e.Storeid).HasColumnName("storeid"); entity.HasOne(d => d.CrustNavigation) .WithMany(p => p.Orders) .HasForeignKey(d => d.Crust) .HasConstraintName("FK__Orders__crust__4D5F7D71"); entity.HasOne(d => d.Customer) .WithMany(p => p.Orders) .HasForeignKey(d => d.Customerid) .HasConstraintName("FK__Orders__customer__14270015"); entity.HasOne(d => d.Store) .WithMany(p => p.Orders) .HasForeignKey(d => d.Storeid) .HasConstraintName("FK_Orders_Store"); }); modelBuilder.Entity<Pizzas>(entity => { entity.ToTable("Pizzas", "Pizza"); entity.Property(e => e.Id).HasColumnName("id"); entity.HasOne(d => d.Order) .WithMany(p => p.Pizzas) .HasForeignKey(d => d.Orderid) .HasConstraintName("FK__Pizzas__Orderid__634EBE90"); entity.HasOne(d => d.ToppingNavigation) .WithMany(p => p.Pizzas) .HasForeignKey(d => d.Topping) .HasConstraintName("FK__Pizzas__Topping__625A9A57"); }); modelBuilder.Entity<Store>(entity => { entity.ToTable("Store", "Pizza"); entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.Loc) .HasColumnName("loc") .IsUnicode(false); }); modelBuilder.Entity<Toppings>(entity => { entity.ToTable("Toppings", "Pizza"); entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.Price) .HasColumnName("price") .HasColumnType("money"); entity.Property(e => e.Topping) .HasColumnName("topping") .IsUnicode(false); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
using System; using System.IO; using System.Windows.Forms; namespace Epic.Training.Project.Inventory.Text.Persistence { class Persist { private static string defaultBinDir = String.Format(@"{0}\{1}", Environment.GetEnvironmentVariable(Resource1.DefaultBinDirEnv), Resource1.DefaultBinDir); internal static void createPersistentDir() { if (!Directory.Exists(defaultBinDir)) { Directory.CreateDirectory(defaultBinDir); } } #region INVENTORY (DE)SERIALIZATION - GetFileName;SaveInventory;LoadInventory /// <summary> /// Creates a [Save|Open]FileDialog for *.bin files located in %APPDATA%\EpicInventory and [Saves|Opens] the selected filename. /// </summary> /// <param name="load">True: Loading Inventory. False: Saving Inventory</param> /// <returns>String - Absolute path of file</returns> private static string GetFilename(bool load, string currentPath = null) { string filePath = null; if (load) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "INVENTORY-TRACKER-LOADING"; dlg.Filter = "Binary files (*.bin)|*.bin"; dlg.InitialDirectory = defaultBinDir; if (dlg.ShowDialog() == DialogResult.OK) { filePath = dlg.FileName; } } else { SaveFileDialog slg = new SaveFileDialog(); slg.Title = "INVENTORY-TRACKER-SAVING"; slg.Filter = "Binary files (*.bin)|*.bin"; slg.InitialDirectory = defaultBinDir; slg.FileName = currentPath; //Defaults as the previously/currently loaded *.bin file. Empty if saving a new inventory if (slg.ShowDialog() == DialogResult.OK) { filePath = slg.FileName; } } return filePath; } internal static void SaveInventory(Inventory inv, ref string currentName) { if (!String.IsNullOrWhiteSpace(currentName)) { Console.WriteLine("[File path of currently loaded inventory - {0}]\n", currentName); } string filePath = GetFilename(false, currentName); FileStream s; try { //s = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); s = File.Create(filePath); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); b.Serialize(s, inv); Console.WriteLine(@"Formatted inventory saved to {0}", filePath); s.Close(); currentName = filePath; } catch (Exception ex) { throw ex; //Explicit reminder to let InventoryMenu deal with this. } //catch (ArgumentNullException) //{ // Console.WriteLine("\n[! No valid file selection was made. Returning to Inventory Menu !]\n"); //} //catch (System.Runtime.Serialization.SerializationException ex) //{ // Console.WriteLine("\n[! IOError: {0}\n Returning to Inventory Menu !]\n", ex.Message); //} } /// <summary> /// Loads a *.bin file representing a serialized Inventory /// </summary> /// <param name="filePath">Absolute filepath of *.bin to load</param> /// <exception>Generic Exception thrown upon IO or Serialization exceptions</exception> /// <returns>Inventory object. Parameter 'filePath' is modified</returns> public static Inventory LoadInventory(out string filePath) { filePath = GetFilename(true); FileStream s; try { s = File.OpenRead(filePath); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); Inventory inventory = (Inventory)b.Deserialize(s); s.Close(); return inventory; } catch (Exception ex) { throw ex; //Explicit reminder to let MainMenu deal with this. } //catch (ArgumentNullException ex) //{ // Console.WriteLine("\n[! No valid file selection was made. Returning to Main Menu !]\n"); //} //catch (System.Runtime.Serialization.SerializationException ex) //{ // Console.WriteLine("\n[! IOError: {0}\n Returning to Main Menu !]\n", ex.Message); //} //catch (Exception ex) //{ // Console.WriteLine("\n[! Error: {0}\n Returning to Main Menu !]\n", ex.Message); //} //System.Threading.Thread.Sleep(2000); //return null; } #endregion } }
using System; class House { static void Main() { int n = int.Parse(Console.ReadLine()); for (int row = 0; row < (n + 1) / 2; row++) { int countDash = (n - 1) / 2 - row; int countStar = n - 2 * countDash; string dash = new string('-', countDash); string stars = new string('*', countStar); Console.WriteLine(dash + stars + dash); } for (int row = 0; row < n-(n+1)/2; row++) { Console.WriteLine('|'+new string('*',n-2)+'|'); } } }
using System; using System.Collections.Generic; using System.Text; namespace EqualityLogic { public class Person : IPerson { private string name; private int age; public Person(string name, int age) { this.Name = name; this.Age = age; } public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public int CompareTo(IPerson other) { int result = this.Name.CompareTo(other.Name); if (result == 0) { result = this.Age.CompareTo(other.Age); } return result; } public override bool Equals(object obj) { Person person = obj as Person; return !Object.ReferenceEquals(null, person) && String.Equals(this.Name, person.Name) && String.Equals(this.Age, person.Age); } public override int GetHashCode() { unchecked { const int HashingBase = (int)2166136261; const int HashingMultiplier = 16777619; int hash = HashingBase; hash = (hash * HashingMultiplier) ^ (!Object.ReferenceEquals(null, this.Name) ? this.Name.GetHashCode() : 0); hash = (hash * HashingMultiplier) ^ (!Object.ReferenceEquals(null, this.Age) ? this.Age.GetHashCode() : 0); return hash; } } } }
namespace CubicsRule { using System; using System.Linq; using System.Numerics; public class Startup { public static void Main() { byte size = byte.Parse(Console.ReadLine()); var input = Console.ReadLine(); var sum = new BigInteger(); var freeDimensions = BigInteger.Pow(size, 3); while (input != "Analyze") { //dimentions - 3 and 1 value that we will use to mark the array with var args = input.Split(' ').Select(int.Parse).ToArray(); var firstDim = args[0]; var secondDim = args[1]; var thirdDim = args[2]; var value = args[3]; if (firstDim < size && firstDim >= 0 && secondDim < size && secondDim >= 0 && thirdDim < size && thirdDim >= 0) { sum += value; if (value > 0) { freeDimensions--; } } input = Console.ReadLine(); } Console.WriteLine(sum); Console.WriteLine(freeDimensions); } } }
using System; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Careers { public class AdminCareerImport : Entity { public virtual Career Career { get; set; } public virtual AdminCareerImportType AdminCareerImportType { get; set; } public virtual DateTime ImportDate { get; set; } public virtual int PreviousID { get; set; } public virtual bool Archive { get; set; } public virtual string Notes { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Tugwell { public partial class FormReport : Form { public FormReport(FormMain main, string dbasePath, bool isOrderTable) { InitializeComponent(); this._main = main; this._dbasePath = dbasePath; this._isOrderTable = isOrderTable; if (_isOrderTable) this.Text += "OrderTable"; else this.Text += "QuoteTable"; load(); } private FormMain _main; private string _dbasePath; private bool _isOrderTable; private List<string> _colNames = new List<string>(); public bool IsSelected = false; private void load() { this.comboBoxField.Items.Clear(); this.comboBoxField2.Items.Clear(); if (this._isOrderTable) { #region OrderTable string[] data = new string[] { //"Any Field", "PO", "Date", "EndUser", "Equipment", "VendorName", "JobNumber", "CustomerPO", "VendorNumber", "SalesAss", "SoldTo", "Street1", "Street2", "City", "State", "Zip", "ShipTo", "ShipStreet1", "ShipStreet2", "ShipCity", "ShipState", "ShipZip", "Carrier", "ShipDate", "IsComOrder", "IsComPaid", "Grinder", "SerialNo", "PumpStk", "ReqDate", "SchedShip", "PODate", "POShipVia", "TrackDate1", "TrackBy1", "TrackSource1", "TrackNote1", "TrackDate2", "TrackBy2", "TrackSource2", "TrackNote2", "TrackDate3", "TrackBy3", "TrackSource3", "TrackNote3", "TrackDate4", "TrackBy4", "TrackSource4", "TrackNote4", "TrackDate5", "TrackBy5", "TrackSource5", "TrackNote5", "TrackDate6", "TrackBy6", "TrackSource6", "TrackNote6", "TrackDate7", "TrackBy7", "TrackSource7", "TrackNote7", "TrackDate8", "TrackBy8", "TrackSource8", "TrackNote8", "TrackDate9", "TrackBy9", "TrackSource9", "TrackNote9", "TrackDate10", "TrackBy10", "TrackSource10", "TrackNote10", "TrackDate11", "TrackBy11", "TrackSource11", "TrackNote11", "TrackDate12", "TrackBy12", "TrackSource12", "TrackNote12", "TrackDate13", "TrackBy13", "TrackSource13", "TrackNote13", "TrackDate14", "TrackBy14", "TrackSource14", "TrackNote14", "TrackDate15", "TrackBy15", "TrackSource15", "TrackNote15", "TrackDate16", "TrackBy16", "TrackSource16", "TrackNote16", "TrackDate17", "TrackBy17", "TrackSource17", "TrackNote17", "TrackDate18", "TrackBy18", "TrackSource18", "TrackNote18", "QuotePrice", "Credit", "Freight", "ShopTime", "TotalCost", "GrossProfit", "Profit", "Description", "Quant1", "Descr1", "Costs1", "ECost1", "Quant2", "Descr2", "Costs2", "ECost2", "Quant3", "Descr3", "Costs3", "ECost3", "Quant4", "Descr4", "Costs4", "ECost4", "Quant5", "Descr5", "Costs5", "ECost5", "Quant6", "Descr6", "Costs6", "ECost6", "Quant7", "Descr7", "Costs7", "ECost7", "Quant8", "Descr8", "Costs8", "ECost8", "Quant9", "Descr9", "Costs9", "ECost9", "Quant10", "Descr10", "Costs10", "ECost10", "Quant11", "Descr11", "Costs11", "ECost11", "Quant12", "Descr12", "Costs12", "ECost12", "Quant13", "Descr13", "Costs13", "ECost13", "Quant14", "Descr14", "Costs14", "ECost14", "Quant15", "Descr15", "Costs15", "ECost15", "Quant16", "Descr16", "Costs16", "ECost16", "Quant17", "Descr17", "Costs17", "ECost17", "Quant18", "Descr18", "Costs18", "ECost18", "Quant19", "Descr19", "Costs19", "ECost19", "Quant20", "Descr20", "Costs20", "ECost20", "Quant21", "Descr21", "Costs21", "ECost21", "Quant22", "Descr22", "Costs22", "ECost22", "Quant23", "Descr23", "Costs23", "ECost23", "InvInstructions", "InvNotes", "VendorNotes", "CrMemo", "InvNumber", "InvDate", "Status", "CheckNumbers", "CheckDates", "ComDate1", "ComCheckNumber1", "ComPaid1", "ComDate2", "ComCheckNumber2", "ComPaid2", "ComDate3", "ComCheckNumber3", "ComPaid3", "ComDate4", "ComCheckNumber4", "ComPaid4", "ComDate5", "ComCheckNumber5", "ComPaid5", "ComAmount", "ComBalance", "DeliveryNotes", "PONotes"}; this.comboBoxField.Items.AddRange(data); this.comboBoxField2.Items.AddRange(data); #endregion } else { #region QuoteTable string[] data = new string[] { //"Any Field", "PO", "Date", "Status", "Company", "VendorName", "JobName", "CustomerPO", "VendorNumber", "SalesAss", "SoldTo", "Street1", "Street2", "City", "State", "Zip", "Delivery", "Terms", "FreightSelect", "IsQManual", "IsPManual", "Location", "Equipment", "EquipCategory", "QuotePrice", "Credit", "Freight", "ShopTime", "TotalCost", "GrossProfit", "Profit", "MarkUp", "Description", "Quant1", "Descr1", "Costs1", "ECost1", "Price1", "Quant2", "Descr2", "Costs2", "ECost2", "Price2", "Quant3", "Descr3", "Costs3", "ECost3", "Price3", "Quant4", "Descr4", "Costs4", "ECost4", "Price4", "Quant5", "Descr5", "Costs5", "ECost5", "Price5", "Quant6", "Descr6", "Costs6", "ECost6", "Price6", "Quant7", "Descr7", "Costs7", "ECost7", "Price7", "Quant8", "Descr8", "Costs8", "ECost8", "Price8", "Quant9", "Descr9", "Costs9", "ECost9", "Price9", "Quant10", "Descr10", "Costs10", "ECost10", "Price10", "Quant11", "Descr11", "Costs11", "ECost11", "Price11", "Quant12", "Descr12", "Costs12", "ECost12", "Price12", "Quant13", "Descr13", "Costs13", "ECost13", "Price13", "Quant14", "Descr14", "Costs14", "ECost14", "Price14", "Quant15", "Descr15", "Costs15", "ECost15", "Price15", "Quant16", "Descr16", "Costs16", "ECost16", "Price16", "Quant17", "Descr17", "Costs17", "ECost17", "Price17", "Quant18", "Descr18", "Costs18", "ECost18", "Price18", "Quant19", "Descr19", "Costs19", "ECost19", "Price19", "Quant20", "Descr20", "Costs20", "ECost20", "Price20", "Quant21", "Descr21", "Costs21", "ECost21", "Price21", "Quant22", "Descr22", "Costs22", "ECost22", "Price22", "Quant23", "Descr23", "Costs23", "ECost23", "Price23", "InvNotes", "DeliveryNotes", "QuoteNotes"}; this.comboBoxField.Items.AddRange(data); this.comboBoxField2.Items.AddRange(data); #endregion } this.comboBoxField.SelectedIndex = 0; this.comboBoxField2.SelectedIndex = 0; buildComboBox(); } private void buttonCancel_Click(object sender, EventArgs e) { this.Close(); } private void buttonGenerate_Click(object sender, EventArgs e) { List<List<string>> rows = getTheList(this.textBoxFrom.Text, this.textBoxTo.Text, (this._isOrderTable) ? "OrderTable" : "QuoteTable"); CSV csv = new CSV(); // headers csv.StartCol(); foreach (string col in this._colNames) { csv.AddCol(col); } // datas foreach (List<string> row in rows) { csv.StartCol(); foreach (string col in row) { csv.AddCol(col); } } string file = generateCSVFileName(); csv.Save(file); csv.ShowCSV(file); } private void buttonAdd_Click(object sender, EventArgs e) { this._colNames.Add(this.comboBoxField.Text); buildListView(); } private void textBoxDate_DoubleClick(object sender, EventArgs e) { TextBox box = (TextBox)sender; FormDatePicker dp = new FormDatePicker(box.Text); dp.ShowDialog(this); if (dp.IsConfirmed) { box.Text = dp.Date; } } public void textBoxDate_Leave(object sender, EventArgs e) { TextBox box = (TextBox)sender; try { DateTime d = Convert.ToDateTime(box.Text); box.Text = d.ToString(@"MM/dd/yyyy"); } catch { } } private void buildListView() { this.listViewReport.Columns.Clear(); foreach (string colName in this._colNames) { this.listViewReport.Columns.Add(colName, 90); } this.listViewReport.Columns[0].Width = 91; } private void buildComboBox() { List<string> names = getNamesFromReportList((this._isOrderTable) ? "OrderTable" : "QuoteTable"); this.comboBoxPreRecorded.Items.Clear(); foreach (string name in names) { this.comboBoxPreRecorded.Items.Add(name); } if (this.comboBoxPreRecorded.Items.Count > 0) this.comboBoxPreRecorded.SelectedIndex = 0; } private List<string> getColFromTable(string colName, string tableName) { List<string> POs = new List<string>(); System.Data.SQLite.SQLiteConnection con = Sql.GetConnection(); //using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + this._dbasePath)) { using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) { com.CommandText = "Select " + colName + " FROM " + tableName; try { //con.Open(); using (System.Data.SQLite.SQLiteDataReader reader = com.ExecuteReader()) { while (reader.Read()) { POs.Add(reader[colName] as string); } } } catch (SqlException ex) { MessageBox.Show(this, "Database error: " + ex.Message); } } } return POs; } private List<List<string>> getTheList(string from, string to, string tableName) { List<List<string>> datas = new List<List<string>>(); System.Data.SQLite.SQLiteConnection con = Sql.GetConnection(); //using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + _dbasePath)) { using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) { com.CommandText = "Select * FROM " + tableName; string f = from.Trim(); string t = to.Trim(); DateTime? dFrom = null, dTo = null; try { dFrom = Convert.ToDateTime(from); dTo = Convert.ToDateTime(to); } catch { } try { //con.Open(); using (System.Data.SQLite.SQLiteDataReader reader = com.ExecuteReader()) { while (reader.Read()) { #region Date filter string date = reader["Date"] as string; if (f == "" || date == "") { // ignore this } else if (t == "") { // from to all future dates DateTime rDate = Convert.ToDateTime(date); if (rDate < dFrom) continue; } else { // use complete data range DateTime rDate = Convert.ToDateTime(date); if (rDate < dFrom) continue; else if (rDate > dTo) continue; } #endregion #region T filter if (this.checkBoxFilerOutTs.Checked) { string po = reader["PO"] as string; if (po.EndsWith("T")) { continue; } } #endregion #region Filter on text, must contain it to be added to datas if (!String.IsNullOrEmpty(this.textBoxFilterText.Text)) { string theText = reader[this.comboBoxField2.Text] as string; if (!theText.ToLower().Contains(this.textBoxFilterText.Text.ToLower())) continue; } #endregion List<string> cols = new List<string>(); foreach (string colName in this._colNames) { cols.Add(reader[colName] as string); } datas.Add(cols); } } } catch (SqlException ex) { MessageBox.Show(this, "Database error: " + ex.Message); } } } return datas; } #region Dbase Low-Level Helpers for Reports //private int getRowCounts() //{ // int? count = 0; // using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + _dbasePath)) // { // using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) // { // con.Open(); // Open the connection to the database // com.CommandText = "Select COUNT(*) From CompanyTable"; // Select all rows from our database table // try // { // object o = com.ExecuteScalar(); // count = Convert.ToInt32(o); // } // catch { }; // } // } // return (count == null) ? 0 : count.Value; //} private void deleteReport(string Name) { System.Data.SQLite.SQLiteConnection con = Sql.GetConnection(); //using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + _dbasePath)) { using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) { com.CommandText = "DELETE From ReportsTable Where Name = '" + Name + "';"; try { //con.Open(); com.ExecuteNonQuery(); } catch (SqlException ex) { MessageBox.Show(this, "Database error: " + ex.Message); } } } } private List<string> getNamesFromReportList(string tableName) { List<string> names = new List<string>(); System.Data.SQLite.SQLiteConnection con = Sql.GetConnection(); //using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + _dbasePath)) { using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) { com.CommandText = "Select * FROM ReportsTable"; try { //con.Open(); using (System.Data.SQLite.SQLiteDataReader reader = com.ExecuteReader()) { while (reader.Read()) { string currTable = reader["TableName"] as string; if (currTable != tableName) continue; //string c = (reader["Category"] as string) + "|" + (reader["Description"] as string) + "|" + (reader["Price"] as string); names.Add(reader["Name"] as string); } } } catch (SqlException ex) { MessageBox.Show(this, "Database error: " + ex.Message); } } } return names; } private bool getReportRowByName(string TableName, string Name, out string Columns) { System.Data.SQLite.SQLiteConnection con = Sql.GetConnection(); //using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + _dbasePath)) { using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) { com.CommandText = "Select * FROM ReportsTable Where Name = '" + Name + "'"; // Select all rows from our database table try { //con.Open(); using (System.Data.SQLite.SQLiteDataReader reader = com.ExecuteReader()) { while (reader.Read()) { string tableName = reader["TableName"] as string; if (tableName != TableName) continue; Columns = reader["Columns"] as string; //con.Close(); return true; } } } catch (SqlException ex) { MessageBox.Show(this, "Database error: " + ex.Message); } } } Columns = ""; return false; } //private int updatePartRow(string Table, string Name, string Columns) //{ // using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + _dbasePath)) // { // using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) // { // #region update string for OrderTable // com.CommandText = // "UPDATE ReportsTable SET Category = @Category, Description = @Description, Price = @Price " + // "Where Category = @Category and Description = @Description"; // #endregion // #region Parameters for OrderTable // com.Parameters.AddWithValue("@Category", Category); // com.Parameters.AddWithValue("@Description", Description); // com.Parameters.AddWithValue("@Price", Price); // #endregion // try // { // con.Open(); // Open the connection to the database // return com.ExecuteNonQuery(); // Execute the query // } // catch (SqlException ex) // { // MessageBox.Show(this, "Database error: " + ex.Message); // return 0; // } // } // } //} private int insertReportRow(string TableName, string Name, string Columns) { System.Data.SQLite.SQLiteConnection con = Sql.GetConnection(); //using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=" + _dbasePath)) { using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con)) { #region insert string for ReportsTable com.CommandText = "INSERT INTO ReportsTable (TableName, Name, Columns) VALUES (@TableName, @Name, @Columns)"; #endregion #region Parameters for ReportsTable com.Parameters.AddWithValue("@TableName", TableName); com.Parameters.AddWithValue("@Name", Name); com.Parameters.AddWithValue("@Columns", Columns); #endregion try { //con.Open(); // Open the connection to the database return com.ExecuteNonQuery(); // Execute the query } catch (SqlException ex) { MessageBox.Show(this, "Database error: " + ex.Message); return 0; } } } } #endregion private void buttonRemember_Click(object sender, EventArgs e) { if (this.textBoxReportName.Text.Trim() != "") { string cols = ""; bool isFirst = true; foreach (string name in this._colNames) { cols += (isFirst) ? name : "|" + name; isFirst = false; } insertReportRow((this._isOrderTable) ? "OrderTable" : "QuoteTable", this.textBoxReportName.Text.Trim(), cols); // rebuild it buildComboBox(); MessageBox.Show(this, "Remembered!"); } } private void buttonSelect_Click(object sender, EventArgs e) { string cols; if (getReportRowByName((this._isOrderTable) ? "OrderTable" : "QuoteTable", this.comboBoxPreRecorded.Text, out cols)) { string[] split = cols.Split('|'); if (split.Count() > 0) { this._colNames.Clear(); foreach (string col in split) { this._colNames.Add(col); } // rebuild it buildListView(); } } } private string generateCSVFileName() { string docs = _dbasePath;//Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string date = DateTime.Now.ToString(@"_hhmm_"); string filename; int count = 1; do { filename = System.IO.Path.GetDirectoryName(docs) + @"\Report" + date + count + ".csv"; count++; } while (System.IO.File.Exists(filename)); return filename; } private void buttonRemove_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(this.comboBoxPreRecorded.Text)) { if (MessageBox.Show("Do you really want to remove '" + this.comboBoxPreRecorded.Text + "'?", "Remove?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { deleteReport(this.comboBoxPreRecorded.Text); // rebuild it buildComboBox(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Kulula.com.Helpers; using Kulula.com.Models; using Kulula.com.Services; using Kulula.com.ViewModels; using Kulula.com.Views; using Rg.Plugins.Popup.Services; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Kulula.com.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class FlightTravellers : ContentPage { private FlightTravellerDetailsService flightTravellerService = new FlightTravellerDetailsService(); private FlightTravellerDetail flightTraveller; private CartService cartService = new CartService(); public FlightTravellers () { InitializeComponent (); airpotname.Text = Settings.AirportName; arrival.Text = Settings.Arrivalairport; NumberOfTravellers.Text = Settings.NumberOfTravellers; Departingdate.Text = Settings.FlightDate; } protected override async void OnAppearing() { List<Cart> carts = await cartService.GetCart(); base.OnAppearing(); cartview.Text = "R" + carts[0].Totalprice.ToString(); } private void DatePicker_DateSelected(object sender, DateChangedEventArgs e) { var dates = e.NewDate.ToString(); var t1 = dates.Remove(10); Settings.Date = t1; } private async void Submit(object sender, System.EventArgs e) { flightTraveller = new FlightTravellerDetail { TravellerID = 0, CustomerID = Convert.ToInt32(Settings.CustomerID), SeatNumber = null, Firstname = FirstName.Text, Lastname = LastName.Text, Dateofbirth = Settings.Date, Gender = Gender.Text, Mobilenumber = MobileNumber.Text, Email = Email.Text }; await flightTravellerService.AddFlightTravellerDetail(flightTraveller); await DisplayAlert("Sucessfully save", "", "Ok"); } private void Button_Clicked(object sender, EventArgs e) { Application.Current.MainPage = new SeatSelection(); } void ShowPopup(object o, EventArgs e) { PopupNavigation.Instance.PushAsync(new Viewcartpopup()); } } }
using System; using System.Collections.Generic; using System.Text; namespace MazeGenerator { public class Player { public bool goUp { get; set; } public bool goDown { get; set; } public bool goLeft { get; set; } public bool goRight { get; set; } public Player() { } } }
using Comp; using Dapper; using Model.RawMaterial; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL.RawMaterial { /// <summary> /// 原料单位 /// </summary> public class D_RawMaterialUnit { /// <summary> /// 获取规格列表 /// </summary> /// <returns>返回对应原料集合</returns> public List<E_RawMaterialUnit> GetList(E_RawMaterialUnit model) { List<E_RawMaterialUnit> list = new List<E_RawMaterialUnit>(); //查询语句 StringBuilder strwhere = new StringBuilder(); if (model.rawareaid > 0) //品号ID { strwhere.AddWhere($"rawareaid={model.rawareaid}"); } //主查询Sql StringBuilder search = new StringBuilder(); search.AppendFormat(@"select * from RawMaterial_Unit {0}", strwhere.ToString()); //执行查询语句 using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr())) { list = conn.Query<E_RawMaterialUnit>(search.ToString(), model)?.ToList(); } return list; } /// <summary> /// 添加规格 /// </summary> public int Add(E_RawMaterialUnit model) { //主查询Sql StringBuilder search = new StringBuilder(); search.AppendFormat(@"INSERT INTO RawMaterial_Unit ([rawareaid],[unitid],[number]) VALUES (@rawareaid,@unitid,@number);select @@IDENTITY;"); //执行查询语句 using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr())) { return Convert.ToInt32(conn.ExecuteScalar(search.ToString(), model)); } } /// <summary> /// 删除规格 /// </summary> /// <returns>返回是否删除成功</returns> public bool Del(E_RawMaterialUnit model) { //查询语句 StringBuilder strwhere = new StringBuilder(); if (model.rawareaid > 0) //品号ID { strwhere.AddWhere($"rawareaid={model.rawareaid}"); } //主查询Sql StringBuilder search = new StringBuilder(); search.AppendFormat($@"delete from RawMaterial_Unit {strwhere.ToString()}"); //执行查询语句 using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr())) { return conn.Execute(search.ToString(), model) > 0; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyDataAccess { class Program { static void Main(string[] args) { //using interface for connection a db using (IDbConnection conn = CreateConnection()) { conn.Open(); ExecuteScalar(conn); //count ExecuteReader(conn); //select ExecuteNonQuery(conn); //update } Console.ReadKey(true); } private static void ExecuteScalar(IDbConnection conn) { IDbCommand cmd = //new SqlCommand("select count(*) from CorsiPerStudente", (SqlConnection)conn); conn.CreateCommand(); //count scalar string sql = "select count(*) from CorsiPerStudente"; cmd.CommandText = sql; //casting int result = (int)cmd.ExecuteScalar(); Console.WriteLine($"{ sql } --> { result }"); } private static void ExecuteNonQuery(IDbConnection conn) { //dati di input int idAula = 4; //poi idAula string cfDocente = "GJKDWT25F2382D"; //poi @cfDocente int idCorso = 2; //poi @idCorso // Inizia una transazione di database con il livello di isolamento specificato //identico per insert and delete using (IDbTransaction tran = conn.BeginTransaction(IsolationLevel.RepeatableRead)) { //string sql = $"update Corso set Id_aula={ idAula }, CF_Docente='{ cfDocente }' where id={ idCorso }"; //modalità update: //UPDATE table-name SET column-name = value, column-name = value, ...WHERE condition // [Id], [Nome], [Id_Aula],[CF_Docente] //1 string sql = "UPDATE Corso SET Id_aula = @idAula, CF_Docente = @cfDocente WHERE id = @idCorso"; // RETURNS COMAND OBJECT ASSOCIATED WITH CONNECTION var cmdObject = conn.CreateCommand(); //set properties of command object cmdObject.Transaction = tran; cmdObject.CommandText = sql; //create parameters (fondamentale per la sicurezza) un per idAula altro per cfDocente e infine pe idCorso //2 var idAulaParam = cmdObject.CreateParameter(); //idAulaParam.DbType = DbType.Int32; //idAulaParam.Direction = ParameterDirection.Input; idAulaParam.ParameterName = "idAula"; idAulaParam.Value = idAula; cmdObject.Parameters.Add(idAulaParam); //per cfDocente var cfDocenteParam = cmdObject.CreateParameter(); cfDocenteParam.ParameterName = "cfDocente"; cfDocenteParam.Value = cfDocente; cmdObject.Parameters.Add(cfDocenteParam); //PER idCorso var idCorsoParam = cmdObject.CreateParameter(); idCorsoParam.ParameterName = "idCorso"; idCorsoParam.Value = idCorso; cmdObject.Parameters.Add(idCorsoParam); int rows = cmdObject.ExecuteNonQuery(); tran.Commit(); //anche no }//using } private static void ExecuteReader(IDbConnection conn) { string sql = "select * from CorsiPerStudente"; var cmd = conn.CreateCommand(); cmd.CommandText = sql; StringBuilder sb = new StringBuilder(); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { sb.AppendFormat("col[{0}]={1} | ", i, reader.GetValue(i)); } sb.AppendLine(); } } Console.WriteLine(sb.ToString()); } private static IDbConnection CreateConnection() { return new SqlConnection("Server=192.168.9.219;Database=Corsi;User Id=corso;Password = corso;"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HugeHouse : MonoBehaviour { // Use this for initialization void Start () { this.transform.Translate(Random.Range(-50, 50), 0, Random.Range(-50, 50)); } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using 信息抓取.Linqs; using System.Net; using System.IO; using System.Text; using System.Data; using System.Text.RegularExpressions; using System.Web.Services; namespace 信息抓取 { public partial class WqhomeTest : System.Web.UI.Page { public static ZhuaQuDataContext zhua = new ZhuaQuDataContext(); protected void Page_Load(object sender, EventArgs e) { } //获取网页源码 public static string Get_Http(string a_strUrl, int timeout) { string strResult; try { HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(a_strUrl); myReq.Timeout = timeout; HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse(); Stream myStream = HttpWResp.GetResponseStream(); Encoding encoding = Encoding.GetEncoding("UTF-8"); //如果是gb2312编码 //StreamReader sr = new StreamReader(myStream, Encoding.UTF8); //如果是utf-8编码 //StreamReader sr = new StreamReader(myStream, Encoding.UTF8); //如果是GBK编码 StreamReader sr = new StreamReader(myStream, Encoding.GetEncoding("GBK")); StringBuilder strBuilder = new StringBuilder(); while (-1 != sr.Peek()) { strBuilder.Append(sr.ReadLine() + "/r/n"); } strResult = strBuilder.ToString(); } catch (Exception exp) { strResult = "错误:" + exp.Message; } return strResult; } //转换成实体 public static MsgInfo getinfomation(string strhtml, string strbtstart, string strbtend,string strsjstart,string strsjend,string strnrstart,string strnrend) { string retitle = string.Format("{0}(?<g>(.|[\r\n])+?){1}", strbtstart, strbtend);//匹配标题 string redate = string.Format("{0}(?<g>(.|[\r\n])+?){1}", strsjstart, strsjend);//匹配日期 string recontent = string.Format("{0}(?<g>(.|[\r\n])+?){1}", strnrstart, strnrend);//匹配正文 string title = Regex.Match(strhtml, retitle).Groups["g"].Value; string date = Regex.Match(strhtml, redate).Groups["g"].Value; string contents = Regex.Match(strhtml, recontent).Groups["g"].Value; MsgInfo msg = new MsgInfo(); msg.title = title; msg.pubdate = Convert.ToDateTime(date); msg.content = contents; return msg; } //插入数据库 [WebMethod] public static bool insertinfo(string url, string strbtstart, string strbtend, string strsjstart, string strsjend, string strnrstart, string strnrend) { bool bol = false; try { string pagehtml =Get_Http(url, 5000); MsgInfo minfo = getinfomation(pagehtml, strbtstart, strbtend, strsjstart, strsjend, strnrstart, strnrend); zhua.MsgInfo.InsertOnSubmit(minfo); zhua.SubmitChanges(); bol = true; } catch (Exception) { bol = false; } return bol; } //绑定 public string bind() { string strlist = ""; StringBuilder sb = new StringBuilder(); List<MsgInfo> list = (from info in zhua.MsgInfo select info).ToList(); for (int i = 0; i < list.Count; i++) { sb.Append("<p style=\" margin:5px 15px 0px 15px;padding:5px; height:25px; line-height:25px;\"><a style=\"float:left;\" onclick=\"selcontent("+list[i].id+")\">"+list[i].title+"</a><span style=\"float:right;\">"+list[i].pubdate+"</span></p>"); } strlist = sb.ToString(); return strlist; } //根据id查询 [WebMethod] public static string getcontent(int id) { string contents = ""; contents = (from info in zhua.MsgInfo where info.id == id select info.content).ToList()[0]; return contents; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SortingAlgorithms.Interfaces; namespace SortingAlgorithms.Algorithms { public class BubbleSort : ISortingAlgorithm { public int[] Sort(int[] unsortedArray) { bool notSorted; do { notSorted = false; for (int i = 1; i < unsortedArray.Length; ++i) { if (unsortedArray[i] < unsortedArray[i - 1]) { notSorted = true; int tempInt = unsortedArray[i]; unsortedArray[i] = unsortedArray[i - 1]; unsortedArray[i - 1] = tempInt; } } } while (notSorted); return unsortedArray; } } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace StudentsRegister.Models.Register { public class RegisterModel { [DisplayName("Email")] [Required(ErrorMessage = "You must type your e-mail")] [EmailAddress(ErrorMessage = "You must type proper e-mail address")] public string Email { get; set; } [DisplayName("Firstname")] [Required(ErrorMessage = "You must type your firstname")] public string FirstName { get; set; } [DisplayName("Lastname")] [Required(ErrorMessage = "You must type your lastname")] public string LastName { get; set; } [DisplayName("Password")] [Required(ErrorMessage = "You must type in your password")] public string Password { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems.AdventOfCode.Y2020 { public class Problem24 : AdventOfCodeBase { private List<List<Move>> _moves; private Dictionary<Tuple<int, int>, bool> _hash; public override string ProblemName => "Advent of Code 2020: 24"; public override string GetAnswer() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { GetMoves(input); return PerformFlips(); } private int Answer2(List<string> input) { GetMoves(input); PerformFlips(); return PerformFlipsAcrossDays(100); } private int PerformFlips() { _hash = new Dictionary<Tuple<int, int>, bool>(); foreach (var moves in _moves) { int x = 0; int y = 0; foreach (var move in moves) { x += move.X; y += move.Y; } var key = new Tuple<int, int>(x, y); if (_hash.ContainsKey(key)) { _hash[key] = !_hash[key]; } else { _hash.Add(key, true); } } return GetFlippedCount(); } private int PerformFlipsAcrossDays(int days) { var neighbors = new List<Move>() { new MoveE(), new MoveNE(), new MoveNW(), new MoveSE(), new MoveSW(), new MoveW() }; for (int day = 1; day <= days; day++) { var counts = new Dictionary<Tuple<int, int>, int>(); foreach (var black in _hash.Where(x => x.Value)) { foreach (var neighbor in neighbors) { var key = new Tuple<int, int>(black.Key.Item1 + neighbor.X, black.Key.Item2 + neighbor.Y); if (counts.ContainsKey(key)) { counts[key]++; } else { counts.Add(key, 1); } } } var flips = new List<Tuple<int, int>>(); foreach (var tile in counts) { if (!_hash.ContainsKey(tile.Key)) { _hash.Add(tile.Key, false); } var value = _hash[tile.Key]; if (!value) { if (tile.Value == 2) { flips.Add(tile.Key); } } else { if (tile.Value == 0 || tile.Value > 2) { flips.Add(tile.Key); } } } foreach (var black in _hash.Where(x => x.Value)) { if (!counts.ContainsKey(black.Key)) { flips.Add(black.Key); } } foreach (var flip in flips) { _hash[flip] = !_hash[flip]; } } return GetFlippedCount(); } private int GetFlippedCount() { return _hash.Values.Where(value => value).Count(); } private void GetMoves(List<string> input) { _moves = new List<List<Move>>(); foreach (var line in input) { var moves = new List<Move>(); int index = 0; while (index < line.Length) { if (line[index] == 'e') { moves.Add(new MoveE()); index++; } else if (line[index] == 'w') { moves.Add(new MoveW()); index++; } else if (line[index] == 's' && line[index + 1] == 'e') { moves.Add(new MoveSE()); index += 2; } else if (line[index] == 's' && line[index + 1] == 'w') { moves.Add(new MoveSW()); index += 2; } else if (line[index] == 'n' && line[index + 1] == 'w') { moves.Add(new MoveNW()); index += 2; } else if (line[index] == 'n' && line[index + 1] == 'e') { moves.Add(new MoveNE()); index += 2; } } _moves.Add(moves); } } private List<string> Test1Input() { return new List<string>() { "esew" }; } private List<string> Test2Input() { return new List<string>() { "nwwswee" }; } private List<string> Test3Input() { return new List<string>() { "sesenwnenenewseeswwswswwnenewsewsw", "neeenesenwnwwswnenewnwwsewnenwseswesw", "seswneswswsenwwnwse", "nwnwneseeswswnenewneswwnewseswneseene", "swweswneswnenwsewnwneneseenw", "eesenwseswswnenwswnwnwsewwnwsene", "sewnenenenesenwsewnenwwwse", "wenwwweseeeweswwwnwwe", "wsweesenenewnwwnwsenewsenwwsesesenwne", "neeswseenwwswnwswswnw", "nenwswwsewswnenenewsenwsenwnesesenew", "enewnwewneswsewnwswenweswnenwsenwsw", "sweneswneswneneenwnewenewwneswswnese", "swwesenesewenwneswnwwneseswwne", "enesenwswwswneneswsenwnewswseenwsese", "wnwnesenesenenwwnenwsewesewsesesew", "nenewswnwewswnenesenwnesewesw", "eneswnwswnwsenenwnwnwwseeswneewsenese", "neswnwewnwnwseenwseesewsenwsweewe", "wseweeenwnesenwwwswnew" }; } private abstract class Move { public abstract string Text { get; } public abstract int X { get; } public abstract int Y { get; } } private class MoveE : Move { public override string Text { get => "E"; } public override int X => 1; public override int Y => 0; } private class MoveSE : Move { public override string Text { get => "SE"; } public override int X => 0; public override int Y => -1; } private class MoveSW : Move { public override string Text { get => "SW"; } public override int X => -1; public override int Y => -1; } private class MoveW : Move { public override string Text { get => "W"; } public override int X => -1; public override int Y => 0; } private class MoveNW : Move { public override string Text { get => "NW"; } public override int X => 0; public override int Y => 1; } private class MoveNE : Move { public override string Text { get => "NE"; } public override int X => 1; public override int Y => 1; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using Xamarin.Forms; using KSF_Surf.ViewModels; using KSF_Surf.Models; using System.Collections.ObjectModel; namespace KSF_Surf.Views { [DesignTimeVisible(false)] public partial class PlayerMapsCompletionPage : ContentPage { private readonly PlayerViewModel playerViewModel; private bool hasLoaded = false; private bool isLoading = false; private readonly int CALL_LIMIT = 999; // objects used by "(In)Complete Maps" call private List<PlayerCompletionRecord> recordsData; private int list_index = 1; // variables for filters private readonly EFilter_Game game; private readonly EFilter_Mode mode; private readonly EFilter_PlayerType playerType; private readonly string playerValue; private readonly EFilter_PlayerCompletionType completionType; // collection view public ObservableCollection<Tuple<string, string, string>> mapsCompletionCollectionViewItemsSource { get; } = new ObservableCollection<Tuple<string, string, string>>(); public PlayerMapsCompletionPage(string title, EFilter_Game game, EFilter_Mode mode, EFilter_PlayerCompletionType completionType, EFilter_PlayerType playerType, string playerValue) { this.game = game; this.mode = mode; this.playerType = playerType; this.playerValue = playerValue; this.completionType = completionType; playerViewModel = new PlayerViewModel(); InitializeComponent(); Title = title; HeaderLabel.Text = EFilter_ToString.toString2(completionType); MapsCompletionCollectionView.ItemsSource = mapsCompletionCollectionViewItemsSource; } // UI ----------------------------------------------------------------------------------------------- #region UI private async Task ChangeCompletion() { var completionDatum = await playerViewModel.GetPlayerMapsCompletion(game, mode, completionType, playerType, playerValue, list_index); recordsData = completionDatum?.data.records; if (recordsData is null) return; LayoutRecords(); } // Dispaying Changes ------------------------------------------------------------------------------- private void LayoutRecords() { foreach (PlayerCompletionRecord datum in recordsData) { if (datum.completedZones is null) datum.completedZones = "0"; string mapCompletionString = datum.mapName + " (" + datum.completedZones + "/" + datum.totalZones + ")"; EFilter_MapType mapType = (EFilter_MapType)int.Parse(datum.mapType); string cptypeString = (mapType == EFilter_MapType.linear) ? "CPs" : "Stages"; string rrinfoString = datum.cp_count + " " + cptypeString + ", " + datum.b_count + " Bonus"; if (datum.b_count != "1") rrinfoString += "es"; string mapSummaryString = "Tier " + datum.tier + " " + EFilter_ToString.toString(mapType) + " - " + rrinfoString; mapsCompletionCollectionViewItemsSource.Add(new Tuple<string, string, string>( mapCompletionString, mapSummaryString, datum.mapName)); list_index++; } if (list_index == 0) // no (in)complete maps { MapsCompletionCollectionViewEmptyLabel.Text = "None ! " + ((completionType == EFilter_PlayerCompletionType.complete) ? ":(" : ":)"); } } #endregion // Event Handlers ---------------------------------------------------------------------------------- #region events protected override async void OnAppearing() { if (!hasLoaded) { hasLoaded = true; await ChangeCompletion(); LoadingAnimation.IsRunning = false; MapsCompletionStack.IsVisible = true; } } private async void MapsCompletion_ThresholdReached(object sender, EventArgs e) { if (isLoading || !BaseViewModel.hasConnection() || list_index == CALL_LIMIT) return; if ((list_index - 1) % 10 != 0) return; // avoid loading more when there weren't enough before isLoading = true; LoadingAnimation.IsRunning = true; await ChangeCompletion(); LoadingAnimation.IsRunning = false; isLoading = false; } private async void MapsCompletion_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.CurrentSelection.Count == 0) return; Tuple<string, string, string> selectedMap = (Tuple<string, string, string>)MapsCompletionCollectionView.SelectedItem; MapsCompletionCollectionView.SelectedItem = null; string mapName = selectedMap.Item3; if (BaseViewModel.hasConnection()) { await Navigation.PushAsync(new MapsMapPage(mapName, game)); } else { await DisplayAlert("Could not connect to KSF!", "Please connect to the Internet.", "OK"); } } #endregion } }
using Newtonsoft.Json; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net; using System.Threading; namespace WebAPI { static class Extensions { public static T GetRequestRestPayload<T>(this HttpListenerRequest httpRequest) { using (var stream = new StreamReader(httpRequest.InputStream)) return JsonConvert.DeserializeObject<T>(stream.ReadToEnd()); } public static void SendRestResponse(this object payload, HttpListenerResponse httpResponse) { httpResponse.Headers.Add(HttpResponseHeader.ContentType, "application/json"); Listener.SendTextResponse(httpResponse, JsonConvert.SerializeObject(payload)); } } public interface IConsoleMethods { void WriteLine(string message); string ReadLine(); void ReleaseReadLine(); } [ExcludeFromCodeCoverage] public class ConsoleMethods : IConsoleMethods { public void WriteLine(string message) { Console.WriteLine(message); } public string ReadLine() { return Console.ReadLine(); } public void ReleaseReadLine() { } } public class ConsoleMethodsMock : IConsoleMethods { public ConsoleMethodsMock() { Monitor.Enter(Locker); } public void WriteLine(string message) { Console.WriteLine(message); } public string ReadLine() { Monitor.Enter(Locker); return Locker.ToString(); } public void ReleaseReadLine() { Monitor.Exit(Locker); } private static readonly object Locker = new object(); } }
using Framework.Core.Common; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Van.Main.List { public class EmployerList : BaseListPage { #region Elements public new IWebElement Header { get { return _driver.FindElement(By.XPath("//span[contains(text (), 'Employers')]")); } } #endregion public EmployerList(Driver driver) : base(driver) { } #region Methods #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entities.Asimco { public class PackageLine { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 产线叶标识 /// </summary> public int T134LeafID { get; set; } /// <summary> /// 产线代码 /// </summary> public string T134Code { get; set; } /// <summary> /// 产线名称 /// </summary> public string T134Name { get; set; } public override string ToString() { return $"[{T134Code}]{T134Name}"; } } }
using Newtonsoft.Json; namespace gView.Framework.OGC.GeoJson { public class GeoJsonFeatures { [JsonProperty("type")] public string Type => "FeatureCollection"; [JsonProperty("features")] public GeoJsonFeature[] Features { get; set; } } }
using Dapper; using Model.RawMaterial; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL.RawMaterial { /// <summary> /// 原料大类 /// </summary> public class D_RawMaterials { /// <summary> /// 获取大类 /// </summary> /// <param name="eRawMaterial">查询参数实体</param> /// <returns>返回对应原料集合</returns> public List<E_RawMaterials> GetList() { List<E_RawMaterials> list = new List<E_RawMaterials>(); //主查询Sql StringBuilder search = new StringBuilder(); search.AppendFormat(@"select * from RawMaterials "); //执行查询语句 using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr())) { list = conn.Query<E_RawMaterials>(search.ToString())?.ToList(); } return list; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _05_Rubik_s_Matrix { public class _05_Rubik_s_Matrix { public static void Main() { var dimentions = Console.ReadLine().Split().Select(int.Parse).ToArray(); var rows = dimentions[0]; var cols = dimentions[1]; var matrix = new int[rows][]; var number = 1; for (int i = 0; i < rows; i++) { matrix[i] = new int[cols]; for (int j = 0; j < cols; j++) { matrix[i][j] = number; number++; } } var n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { var input = Console.ReadLine().Split(); var column = int.Parse(input[0]); var direction = input[1]; var move = int.Parse(input[2]); switch (direction) { case "up":Up(matrix, move, column); break; case "down": Down(matrix, move, column); break; case "left": Left(matrix, move, column); break; case "right": Right(matrix, move, column); break; } } number = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i][j] == number) { Console.WriteLine("No swap required"); } else { for (int x = 0; x < rows; x++) { for (int y = 0; y < cols; y++) { if (matrix[x][y] == number) { var tempRow = x; var tempCol = y; Console.WriteLine($"Swap ({i}, {j}) with ({tempRow}, {tempCol})"); var temp = matrix[i][j]; matrix[i][j] = matrix[tempRow][tempCol]; matrix[tempRow][tempCol] = temp; break; } } } } number++; } } } private static void Right(int[][] matrix, int move, int column) { var length = matrix[0].Length; move = move % length; var row = column; for (int j = 0; j < move; j++) { var temp = matrix[row][length - 1]; for (int x = length - 1; x > 0; x--) { matrix[row][x] = matrix[row][x - 1]; } matrix[row][0] = temp; } } private static void Left(int[][] matrix, int move, int column) { var length = matrix[0].Length; move = move % length; var row = column; for (int j = 0; j < move; j++) { var temp = matrix[row][0]; for (int x = 0; x < length - 1; x++) { matrix[row][x] = matrix[row][x+1]; } matrix[row][length-1] = temp; } } private static void Down(int[][] matrix, int move, int column) { move = move % matrix.Length; for (int j = 0; j < move; j++) { var temp = matrix[matrix.Length - 1][column]; for (int x = matrix.Length - 1; x > 0; x--) { matrix[x][column] = matrix[x - 1][column]; } matrix[0][column] = temp; } } private static void Up(int[][] matrix, int move, int column) { move = move % matrix.Length; for (int j = 0; j < move; j++) { var temp = matrix[0][column]; for (int x = 0; x < matrix.Length-1; x++) { matrix[x][column] = matrix[x+1][column]; } matrix[matrix.Length - 1][column] = temp; } } } }
 namespace PhonebookApplication { using System; using System.Collections.Generic; using System.Linq; using Wintellect.PowerCollections; public class Repository : IPhonebookRepository { private readonly Dictionary<string, Entry> _entriesDictionary; private readonly MultiDictionary<string, Entry> _entriesMultiDictionary; private readonly OrderedSet<Entry> _entriesSorOrderedSet; public Repository() { this._entriesDictionary = new Dictionary<string, Entry>(); this._entriesMultiDictionary = new MultiDictionary<string, Entry>(false); this._entriesSorOrderedSet = new OrderedSet<Entry>(); } public bool AddPhone(string name, IEnumerable<string> phoneNumbers) { name = name.ToLowerInvariant(); Entry entry; bool notExisting = !_entriesDictionary.TryGetValue(name, out entry); if (notExisting) { entry = new Entry(); entry.Name = name; entry.entyPhones = new SortedSet<string>(); _entriesDictionary.Add(name, entry); _entriesSorOrderedSet.Add(entry); } foreach (string number in phoneNumbers) { _entriesMultiDictionary.Add(number, entry); } entry.entyPhones.UnionWith(phoneNumbers); return notExisting; } public int ChangePhone(string oldPhoneNumber, string newPhoneNumber) { List<Entry> found = _entriesMultiDictionary[oldPhoneNumber].ToList(); //todo: maybe bug foreach (Entry entry in found) { entry.entyPhones.Remove(oldPhoneNumber); _entriesMultiDictionary.Remove(oldPhoneNumber, entry); entry.entyPhones.Add(newPhoneNumber); _entriesMultiDictionary.Add(newPhoneNumber, entry); } return found.Count; } public Entry[] ListEntries(int first, int num) { if (first < 0 || first + num > _entriesDictionary.Count) { //no exception message is thorwn here, the exception is passed for processing throw new IndexOutOfRangeException(); } var list = new Entry[num]; for (int i = first; i <= first + num - 1; i++) { Entry entry = _entriesSorOrderedSet[i]; list[i - first] = entry; } return list; } } }
using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Interfaces; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Models; namespace CurrencyConverter.Controllers { public class HomeController : Controller { private readonly ICurrenciesService _currenciesService; private readonly ILogger<HomeController> _logger; public HomeController(ICurrenciesService currenciesService, ILogger<HomeController> logger) { _currenciesService = currenciesService; _logger = logger; } public async Task<IActionResult> Index() { var rates = await _currenciesService.GetExchangeRates(DateTime.Now); return View(new ExchangeRatesViewModel { Rates = rates, Date = DateTime.Now, From = rates.FirstOrDefault(), To = rates.FirstOrDefault(), Amount = 1 }); } [HttpPost] public async Task<IActionResult> Index(CurrencyConvertViewModel model) { if (!ModelState.IsValid) { return View(new ExchangeRatesViewModel { ErrorMessage = "One or more selected values are invalid" }); } var rates = await _currenciesService.GetExchangeRates(model.Date.Value); var convertionRate = _currenciesService.GetExchangeRate(model.From, model.To, model.Date.Value); var convertedAmount = _currenciesService.GetExchangeRate(model.From, model.To, model.Date.Value, model.Amount); return View(new ExchangeRatesViewModel { Rates = rates, Date = model.Date.Value, From = rates.FirstOrDefault(r => r.Currency == model.From), To = rates.FirstOrDefault(r => r.Currency == model.To), ConvertionRate = convertionRate, ConvertedAmount = convertedAmount }); } [HttpGet] public async Task<JsonResult> GetCurrencyRate(string from, string to, DateTime date) { if (string.IsNullOrWhiteSpace(from) || string.IsNullOrWhiteSpace(to)) return Json(""); if (!string.IsNullOrWhiteSpace(from) && from.Length != 3 || !string.IsNullOrWhiteSpace(to) && to.Length != 3) return Json(""); if (date < new DateTime(2000, 01, 01) || date > DateTime.Now) return Json(""); await _currenciesService.GetExchangeRates(date); var rate = _currenciesService.GetExchangeRate(from, to, date); return Json(rate); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodsExcercise { class Program { static void Main(string[] args) { int firstNumber = int.Parse(Console.ReadLine()); int secondNumber = int.Parse(Console.ReadLine()); int thirdNumber = int.Parse(Console.ReadLine()); int smallerNumber = SmallerNumber(firstNumber, secondNumber); int result = SmallerNumber(smallerNumber, thirdNumber); Console.WriteLine(result); } static int SmallerNumber(int number1,int number2) // return number1 <= number2 ? number1 : number2; { if(number1<=number2) { return number1; } else { return number2; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Autofac; using Autofac.Integration.Mvc; using Integer.Domain.Paroquia; using Integer.Infrastructure.Repository; using Integer.Infrastructure.Events; using Integer.Domain.Agenda; using Raven.Client; using Raven.Database.Server; using Integer.Web.Infra.AutoMapper; using Integer.Infrastructure.Email; using System.Text; using Integer.Infrastructure.IoC; using Integer.Domain.Acesso; using Integer.Infrastructure.Tasks; namespace Integer { public class MvcApplication : System.Web.HttpApplication { private const string RavenSessionKey = "RavenDB.Session"; public static IDocumentSession CurrentSession { get { return (IDocumentSession)HttpContext.Current.Items[RavenSessionKey]; } set { HttpContext.Current.Items[RavenSessionKey] = value; } } public MvcApplication() { BeginRequest += this.Application_BeginRequest; EndRequest += this.Application_EndRequest; } public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{*allsvg}", new { allsvg = @".*\.svg(/.*)?" }); routes.IgnoreRoute("{*robotstxt}", new { robotstxt = @"(.*/)?robots.txt(/.*)?" }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Calendario", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); Initialize(); } private void Initialize() { DocumentStoreHolder.Initialize(); InitializeIoC(); AutoMapperConfiguration.Configure(); } private void InitializeIoC() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.Register(c => CurrentSession).As<IDocumentSession>(); builder.RegisterType<EventoRepository>().As<Eventos>(); builder.RegisterType<GrupoRepository>().As<Grupos>(); builder.RegisterType<LocalRepository>().As<Locais>(); builder.RegisterType<UsuarioRepository>().As<Usuarios>(); builder.RegisterType<UsuarioTokenRepository>().As<UsuarioTokens>(); builder.RegisterType<RemoveConflitoService>().As<DomainEventHandler<EventoCanceladoEvent>>(); builder.RegisterType<RemoveConflitoService>().As<DomainEventHandler<ReservaDeLocalCanceladaEvent>>(); builder.RegisterType<RemoveConflitoService>().As<DomainEventHandler<HorarioDeReservaDeLocalAlteradoEvent>>(); builder.RegisterType<RemoveConflitoService>().As<DomainEventHandler<HorarioDeEventoAlteradoEvent>>(); builder.Register<AgendaEventoService>(c => new AgendaEventoService(c.Resolve<Eventos>())); builder.Register<TrocaSenhaService>(c => new TrocaSenhaService(c.Resolve<Usuarios>(), c.Resolve<UsuarioTokens>())); var container = builder.Build(); var resolver = new AutofacDependencyResolver(container); DependencyResolver.SetResolver(resolver); IoCWorker.Initialize(resolver); } protected void Application_BeginRequest(object sender, EventArgs e) { CurrentSession = DocumentStoreHolder.DocumentStore.OpenSession(); } protected void Application_EndRequest(object sender, EventArgs e) { using (var session = CurrentSession) { if (session == null) return; if (Server.GetLastError() != null) return; session.SaveChanges(); } TaskExecutor.StartExecuting(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PlayerManager2 : MonoBehaviour { // 属性值 public int player1LifeValue = 3; public int player1Score = 0; public int player2LifeValue = 3; public int player2Score = 0; public bool isPlayer1Dead; public bool isPlayer2Dead; public bool isDefeat; // 引用 public GameObject Born; public Text player1ScoreText; public Text player1LifeValueText; public Text player2ScoreText; public Text player2LifeValueText; public GameObject UIGameOver; // 单例 private static PlayerManager2 instance2; public static PlayerManager2 Instance2 { get { return instance2; } set { instance2 = value; } } private void Awake() { Instance2 = this; } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (isDefeat) { UIGameOver.SetActive(true); Invoke("ReturnToMenu", 5.0f); return; } if (isPlayer1Dead) { Recover1(); } if (isPlayer2Dead) { Recover2(); } if (player1LifeValue <= 0 && player2LifeValue <= 0) { isDefeat = true; } player1ScoreText.text = player1Score.ToString(); player1LifeValueText.text = player1LifeValue.ToString(); player2ScoreText.text = player2Score.ToString(); player2LifeValueText.text = player2LifeValue.ToString(); } // 复活 private void Recover1() { if (player1LifeValue > 0) { player1LifeValue--; Instantiate(Born, new Vector3(-2, -8, 0), Quaternion.identity); isPlayer1Dead = false; } } private void Recover2() { if (player2LifeValue > 0) { player2LifeValue--; GameObject go = Instantiate(Born, new Vector3(2, -8, 0), Quaternion.identity); go.GetComponent<Born>().isPlayer1 = false; isPlayer2Dead = false; } } private void ReturnToMenu() { SceneManager.LoadScene("Start"); } }
using Bloodhound.Core.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Bloodhound.Core.Workflows { public class OffenderNewLocationWorkflow { protected BloodhoundContext dbContext; protected Offender offender; protected OffenderLocation lastLocation; protected List<OffenderGeoFence> geoFences; public OffenderNewLocationWorkflow(BloodhoundContext dbContext, long offenderId) { this.dbContext = dbContext ?? throw new ArgumentNullException(nameof(offenderId)); this.offender = dbContext.Offenders.Find(offenderId) ?? throw new EntityNotFoundException(nameof(Offender), offenderId); this.lastLocation = dbContext.OffenderLocations.Where(x => x.OffenderId == this.offender.OffenderId).Take(1).OrderByDescending(x => x.LocationTime).FirstOrDefault(); this.geoFences = dbContext.OffenderGeoFences.Where(x => x.OffenderId == this.offender.OffenderId).ToList(); } public void AddNewLocation(decimal latitude, decimal longitude, DateTimeOffset locationTime) { } } }
using System; using Divar.Core.Domain.UserProfiles.Commands; using Divar.Core.Domain.UserProfiles.Data; using Divar.Core.Domain.UserProfiles.ValueObjects; using Divar.Framework.Domain.ApplicationServices; using Divar.Framework.Domain.Data; namespace Divar.Core.ApplicationService.UserProfiles.CommandHandlers { public class UpdateUserNameHandler : ICommandHandler<UpdateUserName> { private readonly IUnitOfWork _unitOfWork; private readonly IUserProfileRepository _userProfileRepository; public UpdateUserNameHandler(IUnitOfWork unitOfWork, IUserProfileRepository userProfileRepository) { this._unitOfWork = unitOfWork; _userProfileRepository = userProfileRepository; } public void Handle(UpdateUserName command) { var user = _userProfileRepository.Load(command.UserId); if (user == null) throw new InvalidOperationException($"کاربری با شناسه {command.UserId} یافت نشد."); user.UpdateName(FirstName.FromString(command.FirstName), LastName.FromString(command.LastName)); _unitOfWork.Commit(); } } }
using DFC.ServiceTaxonomy.GraphSync.Enums; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Results.ValidateAndRepair; namespace DFC.ServiceTaxonomy.GraphSync.ViewModels { public class TriggerSyncValidationViewModel { public IValidateAndRepairResults? ValidateAndRepairResults { get; set; } public ValidationScope? Scope { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; public partial class Vista_Inicio_actualizaciones : System.Web.UI.Page { #region Page_Load protected void Page_Load(object sender, EventArgs e) { SessionTimeOut obj_session = new SessionTimeOut(); bool bSessionE = obj_session.IsSessionTimedOut(); ///INICIO SESSION if (!bSessionE) { //Se declaran los breadCrumbs string[] sDatos = { "Actualizaciones" }; string[] sUrl = { "" }; breadCrum.migajas(sDatos, sUrl); ///TRY try { ///recupera el id de Usuario string sCveUser = Session["iIdUsuario"].ToString(); ///Objeto a Clientes Actualizacion obj_actualizacion = new Actualizacion(); obj_actualizacion.getContenidoEncabezado(obj_actualizacion); alblListaActualizacion.Text = obj_actualizacion.sContenido; }///FIN TRY ///INICIO CATCH catch (Exception ex) { ///HAY ERROR EN EJECUCION, REDIRECCIONA A INICIO Response.Redirect("../Inicio/Inicio.aspx"); }///FIN CATCH }///FIN IF SESSION ///INICIO ELSE SESSION else { ///CIERRA LA SESSION Y REDIRECCIONA A LOGIN Session.Clear(); Session.Abandon(); Response.Redirect("../../Login.aspx"); } ///FIN ELSE SESSION } #endregion #region fn_generar_PDF /// <summary> /// Método para generar la vista del pdf /// </summary> /// <param name="sIdNotificacion"></param> /// <returns></returns> [WebMethod] public static Actualizacion fn_generar_PDF(string sIdNotificacion) { ///Instancia a la clase Actualizacion Actualizacion obj_actualizacion = new Actualizacion(); ///Instancia a la clase Security para desencriptar el id Security obj_idNotificacion = new Security(sIdNotificacion); ///Se asignan valores obj_actualizacion.giIdNotificacion = int.Parse(obj_idNotificacion.DesEncriptar()); ///Se llama al método recuperar datos obj_actualizacion.recuperaDatosManual(obj_actualizacion); ///Se retorna el objeto return obj_actualizacion; } #endregion #region fn_recupera_datos_actualizacion /// <summary> /// Método para recuperar los datos de la actualización /// </summary> /// <param name="sIdNotificacion"></param> /// <returns></returns> [WebMethod] public static Actualizacion fn_recupera_datos_actualizacion(string sIdNotificacion) { ///Instancia a la clase Actualizacion Actualizacion obj_actualizacion = new Actualizacion(); ///Instancia a la clase Security para desencriptar el id Security obj_idNotificacion = new Security(sIdNotificacion); ///Se asignan valores obj_actualizacion.giIdNotificacion = int.Parse(obj_idNotificacion.DesEncriptar()); ///Se llama al método recuperar datos obj_actualizacion.recuperaDatosActualizacion(obj_actualizacion); ///Se retorna el objeto return obj_actualizacion; } #endregion }
using System; class LongestNonDecreasingSubsequence { static void Main() { Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!"); while (true) { // ????? } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Stack_and_Queue { class ThreeStackWithOneArray { private int[] stackTopIndex = new int[3]; private int indiStackSize; private int[] storage; public ThreeStackWithOneArray(int singleStackSize) { if(singleStackSize <= 0) { throw new Exception("capacity is invalid"); } indiStackSize = singleStackSize; storage = new int[singleStackSize * 3]; stackTopIndex[0] = 0; stackTopIndex[1] = singleStackSize; stackTopIndex[2] = 2 * singleStackSize; } public int Pop(int stackNum) { if(stackNum >=0 && stackNum < 3) { if(stackTopIndex[stackNum]> stackNum*indiStackSize) { int indexAffected = --stackTopIndex[stackNum]; int retVal = storage[indexAffected]; storage[indexAffected] = 0; return retVal; } else { throw new Exception("stack is empty"); } } else { throw new Exception("invalid stack number"); } } public void Push(int stackNum, int data) { if (stackNum >= 0 && stackNum < 3) { if (stackTopIndex[stackNum] < ((stackNum+1) * indiStackSize)) { storage[stackTopIndex[stackNum]++] = data; } else { throw new Exception("stack is full"); } } else { throw new Exception("invalid stack number"); } } #region Testing public static void TestThreeStackWithOneArray() { Console.WriteLine("test the three stack array"); ThreeStackWithOneArray threeStack = new ThreeStackWithOneArray(3); try { threeStack.Push(1, 3); threeStack.Push(1, 3); threeStack.Push(1, 3); threeStack.Push(1, 3); threeStack.Push(1, 3); threeStack.Push(1, 3); threeStack.Push(1, 3); } catch(Exception e) { Console.WriteLine(e.Message); } threeStack.PrintStorage(); try { threeStack.Pop(1); threeStack.Pop(1); threeStack.Pop(1); threeStack.Pop(1); threeStack.Pop(1); } catch (Exception e) { Console.WriteLine(e.Message); } threeStack.PrintStorage(); } public void PrintStorage() { for (int i = 0; i<storage.Length; i++) { Console.Write(storage[i] + " "); } Console.WriteLine(); } #endregion } }
using UnityEngine; using System.Collections; public class ZhunXingCtrl : MonoBehaviour { bool IsFixZhunXing; public UISprite ZhunXingSprite; public UISprite ZhunXingJuLiFuSprite; public static ZhunXingCtrl _Instance; public static ZhunXingCtrl GetInstance() { return _Instance; } // Use this for initialization void Start() { _Instance = this; //ZhunXingSprite = GetComponent<UISprite>(); ZhunXingSprite.enabled = false; ZhunXingJuLiFuSprite.enabled = false; gameObject.SetActive(false); IsFixZhunXing = !Screen.fullScreen; pcvr.GetInstance().OnUpdateCrossEvent += OnUpdateCrossEvent; } // Update is called once per frame void Update() { if (ZhunXingSprite.enabled || ZhunXingJuLiFuSprite.enabled) { CheckZhunXingImg(); if(IsFixZhunXing != Screen.fullScreen) { IsFixZhunXing = Screen.fullScreen; int iScreenW = FreeModeCtrl.GetSystemMetrics(FreeModeCtrl.SM_CXSCREEN); int iScreenH = FreeModeCtrl.GetSystemMetrics(FreeModeCtrl.SM_CYSCREEN); if(!Screen.fullScreen) { iScreenW = Screen.width; iScreenH = Screen.height; } float sx = (1360f *(float)iScreenH) / (768f * (float)iScreenW); //ScreenLog.Log("sx **** " + sx + ", Screen: " + iScreenW + ", " + iScreenH ); transform.localScale = new Vector3(sx, transform.localScale.y, transform.localScale.z); } transform.localPosition = pcvr.CrossPosition; } } void OnUpdateCrossEvent() { if (Application.loadedLevel == (int)GameLeve.Movie || Application.loadedLevel == (int)GameLeve.SetPanel) { pcvr.GetInstance().OnUpdateCrossEvent -= OnUpdateCrossEvent; return; } if (ZhunXingSprite.enabled || ZhunXingJuLiFuSprite.enabled) { transform.localPosition = pcvr.CrossPosition; } } void CheckZhunXingImg() { if (!GlobalData.GetInstance().IsActiveJuLiFu) { ZhunXingSprite.enabled = true; ZhunXingJuLiFuSprite.enabled = false; } else { ZhunXingSprite.enabled = false; ZhunXingJuLiFuSprite.enabled = true; } } public void ShowPlayerZhunXing() { if (pcvr.bIsHardWare && !pcvr.IsGetValByKey) { return; } if(gameObject.activeSelf) { return; } CheckZhunXingImg(); ZhunXingSprite.enabled = true; gameObject.SetActive(true); } public void ClosePlayerZhunXing() { if(!gameObject.activeSelf) { return; } ZhunXingSprite.enabled = false; gameObject.SetActive(false); } }
namespace Simulator.Compile { internal readonly struct DataToken { internal int Address { get; } internal int Length { get; } internal int Value { get; } public DataToken(int address, int length, int value) { Address = address; Length = length; Value = value; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SolidPrinciples.LiskovSubstitution.Voilation { class ReadWrite { public string FileSource { get; set; } public string FileContent { get; set; } public string LoadContent() { return "File is Read Only"; } public void SaveContent() { throw new IOException("File cannot be saved"); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace GDS.Comon { public static class MvcExtensions { /// <summary> /// 给Url路径添加版本号,解决js缓存问题 /// </summary> /// <param name="helper"></param> /// <param name="contentPath"></param> /// <returns></returns> public static string VersionContent(this UrlHelper helper, string contentPath) { contentPath = contentPath ?? ""; var version = ConfigurationManager.AppSettings["PublishVersion"]; version = string.IsNullOrEmpty(version) ? "20161201001" : version; var prefix = contentPath.Contains("?") ? "&" : "?"; contentPath = string.Format("{0}{1}v={2}", contentPath, prefix, version); return helper.Content(contentPath); } } }
// ReSharper disable InconsistentNaming namespace Simulator { public static class Constants { public static readonly string[] CHAR_COMMENT = {"#"}; public static readonly string[] CHAR_LABEL = {"_"}; public static readonly string[] CHAR_DATA = {"."}; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using System.Collections.ObjectModel; using Microsoft.Toolkit.Uwp.UI.Controls; using VéloMax.bdd; using VéloMax.pages; namespace VéloMax.pages { public sealed partial class AjouterCatalUI : Page { Fournisseur f; public AjouterCatalUI() { this.InitializeComponent(); pieceCombo.ItemsSource = Piece.ListerString(); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); f = (Fournisseur)e.Parameter; } public void AjoutCatalogue(object sender, RoutedEventArgs e) { try { Piece p = Piece.Lister()[pieceCombo.SelectedIndex]; int id = int.Parse(numPF.Text); int prix = int.Parse(prixPF.Text); int delai = int.Parse(delaiF.Text); new CatalFournisseur(f, p, id, prix, delai); ((this.Frame.Parent as NavigationView).Content as Frame).Navigate(typeof(CatalogueUI), f); } catch { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GossipBoard.Models; using GossipBoard.Repository; using GossipBoard.Dto; using Microsoft.AspNetCore.Mvc; namespace GossipBoard.Services { public class PostService : IPostService { private readonly IPostRepository _repository; public PostService(IPostRepository repository) { _repository = repository; } public async Task<Post> GetPostById(int id) { var post = await _repository.GetById(id); return post; } public async Task<ICollection<PostDto>> GetAllPosts(int offset, int limit) { var posts = await _repository.GetAll(offset, limit); return posts; } public async Task<int> Update(Post newPost) { var post = await _repository.Update(newPost); return post; } public async Task<int> Create(Post newPost) { var post = await _repository.Create(newPost); return post; } public async Task<IActionResult> DeleteById(ApplicationUser user, int id) { return await _repository.DeleteById(user,id); } public async Task DeleteByIdWithoutUser(int id) { await _repository.DeleteByIdWithoutUser(id); } public async Task<int> UpVotePost(ApplicationUser user, int id) { var postLikeCount = await _repository.UpVotePost(user, id); return postLikeCount; } public ICollection<Post> SearchPosts(string str, int offset, int limit) { var result = _repository.Search(str, offset, limit); return result; } } }
using System; using System.Collections.Generic; using System.Text; namespace GameProject_Homework { class GamerValidationManager : IGamerValidationService { public bool Validation(Gamer gamer) { if (gamer.LationalityId == "16912829815" && gamer.FirstName.ToUpper() == "HAYDAR" && gamer.LastName.ToUpper()=="GÖBEL" && gamer.DateOfBirth.Year == 1999) return true; else return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Level { ONE, TWO, THREE } public class GarbageManager : MonoBehaviour { public Garbage res; public Level level; private float timer = 0; public float cd = 0.5f; public float timeRandomRange = 0.2f; public float randomCountMin = 1; public float randomCountMax = 3; public readonly Rect level1scanout = new Rect(0, 8, 19, 5); public void Update() { timer -= Time.deltaTime; if(timer<=0) { timer = cd + Random.Range(-timeRandomRange, timeRandomRange); for (int i = 0; i < Random.Range(randomCountMin,randomCountMax); i++) { switch (level) { case Level.ONE: CreateGarbage1(); break; case Level.TWO: CreateGarbage2(); break; case Level.THREE: CreateGarbage3(); break; default: break; } } } } private void CreateGarbage1() { GameObject g = GameObject.Instantiate(res.gameObject); Garbage gar = g.GetComponent<Garbage>(); gar.is_alive = true; g.gameObject.SetActive(true); var x = Random.Range(level1scanout.x + level1scanout.width / 2, level1scanout.x - level1scanout.width / 2); var y = Random.Range(level1scanout.y + level1scanout.height / 2, level1scanout.y - level1scanout.height / 2); Vector3 randomV3 = new Vector3(x, y); g.transform.position = randomV3; var rig = g.GetComponent<Rigidbody2D>(); rig.velocity = new Vector2(Random.Range(-0.5f,0.5f),-1)*Random.Range(2,3); rig.AddTorque(Random.Range(-.5f, .5f)); var sp = ResMgr.Instance.garbages[Random.Range(0, ResMgr.Instance.garbages.Length)]; gar.SetSprite(sp); } private void CreateGarbage2() { var dir = Random.Range(0, 4); float x=0; float y=0; float dir_x = 0; float dir_y = 0;float dir_xm = 0; float dir_ym = 0; float speedx = 0; float speedy = 0; switch (dir) { case 0: x = Random.Range(level1scanout.x + level1scanout.width / 2, level1scanout.x - level1scanout.width / 2); y = Random.Range(level1scanout.y + level1scanout.height / 2, level1scanout.y - level1scanout.height / 2); dir_x = -0.5f; dir_xm = 0.5f; dir_y = -1; dir_ym = -1.1f; break; case 1: x = Random.Range(level1scanout.x + level1scanout.width / 2, level1scanout.x - level1scanout.width / 2); y = -Random.Range(level1scanout.y + level1scanout.height / 2, level1scanout.y - level1scanout.height / 2); dir_x = -0.5f; dir_xm = 0.5f; dir_y = 1; dir_ym = 1.1f; break; case 2: x = Random.Range(-13f, -15f); y = -Random.Range(-5f, -5f); dir_y = -0.5f; dir_ym = 0.5f; dir_x = 1; dir_xm = 1.1f; break; case 3: x = Random.Range(13f, 15f); y = -Random.Range(-5f, 5f); dir_y = -0.5f; dir_ym = 0.5f; dir_x = -1; dir_xm = -1.1f; break; default: break; } GameObject g = GameObject.Instantiate(res.gameObject); Garbage gar = g.GetComponent<Garbage>(); g.transform.localScale = Vector3.one * 0.6f; gar.is_alive = true; g.gameObject.SetActive(true); Vector3 randomV3 = new Vector3(x, y); g.transform.position = randomV3; var rig = g.GetComponent<Rigidbody2D>(); rig.velocity = new Vector2(Random.Range(dir_x, dir_xm), Random.Range(dir_y, dir_ym)) * Random.Range(4, 5); rig.AddTorque(Random.Range(-1f, 1f)); var sp = ResMgr.Instance.garbages[Random.Range(0, ResMgr.Instance.garbages.Length)]; gar.SetSprite(sp); } private void CreateGarbage3() { GameObject g = GameObject.Instantiate(res.gameObject); Garbage gar = g.GetComponent<Garbage>(); gar.is_alive = true; g.gameObject.SetActive(true); var x = Random.Range(level1scanout.x + level1scanout.width / 2, level1scanout.x - level1scanout.width / 2); var y = -Random.Range(level1scanout.y + level1scanout.height / 2, level1scanout.y - level1scanout.height / 2); Vector3 randomV3 = new Vector3(x, y); g.transform.position = randomV3; var rig = g.GetComponent<Rigidbody2D>(); rig.velocity = new Vector2(Random.Range(-0.8f, 0.8f), 1) * Random.Range(2, 6); rig.AddTorque(Random.Range(-4f, 4f)); var sp = ResMgr.Instance.garbages[Random.Range(0, ResMgr.Instance.garbages.Length)]; gar.SetSprite(sp); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace EduHome.ViewModels.Account { public class RegisterVM { [Required, StringLength(maximumLength: 100)] public string FullName { get; set; } [Required, DataType("nvarchar(50)")] public string Username { get; set; } [Required, DataType(DataType.EmailAddress)] public string Email { get; set; } [Required, DataType(DataType.Password)] public string Password { get; set; } [Required(ErrorMessage = "Confirm Password mustn't be empty"), DataType(DataType.Password), Compare(nameof(Password))] public string ConfirmPassword { get; set; } } }
using Alabo.App.Share.TaskExecutes.ResultModel; using System; namespace Alabo.App.Share.OpenTasks.Parameter { public class GlobalDividendParameter : TaskQueueParameterBase { public GlobalDividendParameter(int configurationId) : base(configurationId) { } /// <summary> /// 金额(无效) /// </summary> public decimal Amount { get; set; } /// <summary> /// 本轮起始时间 /// </summary> public DateTime StartTime { get; set; } } }